@urun-sh/openai 0.6.56 → 0.6.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Md=Object.create;var mi=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var Fd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Bd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nd(e))!Dd.call(t,o)&&o!==n&&mi(t,o,{get:()=>e[o],enumerable:!(r=$d(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Md(Ud(t)):{},Hd(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var T=Fd(()=>{"use strict"});var gi=Bd(()=>{"use strict";T();var hi;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(d,c)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return Ro(Object.create(null))}:l?function(){return Ro({__proto__:null})}:function(){return Ro({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Td(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Od(),m=typeof WeakMap=="function"?WeakMap:Pd(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=xd(),x=Ad(E);function v(k,I,L,D){if(N(L)){if(!vn(k))throw new TypeError;if(!ai(I))throw new TypeError;return b(k,I)}else{if(!vn(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(D)&&!N(D)&&!ee(D))throw new TypeError;return ee(D)&&(D=void 0),L=$e(L),C(k,I,L,D)}}e("decorate",v);function _(k,I){function L(D,Y){if(!ue(D))throw new TypeError;if(!N(Y)&&!Rd(Y))throw new TypeError;X(k,I,D,Y)}return L}e("metadata",_);function p(k,I,L,D){if(!ue(L))throw new TypeError;return N(D)||(D=$e(D)),X(k,I,L,D)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),M(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),U(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function O(k,I,L){if(!ue(I))throw new TypeError;if(N(L)||(L=$e(L)),!ue(I))throw new TypeError;N(L)||(L=$e(L));var D=bn(I,L,!1);return N(D)?!1:D.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",O);function b(k,I){for(var L=k.length-1;L>=0;--L){var D=k[L],Y=D(I);if(!N(Y)&&!ee(Y)){if(!ai(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,D){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,D);if(!N(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;D=ke}}return D}function $(k,I,L){var D=M(k,I,L);if(D)return!0;var Y=ko(I);return ee(Y)?!1:$(k,Y,L)}function M(k,I,L){var D=bn(I,L,!1);return N(D)?!1:Me(D.OrdinaryHasOwnMetadata(k,I,L))}function U(k,I,L){var D=M(k,I,L);if(D)return q(k,I,L);var Y=ko(I);if(!ee(Y))return U(k,Y,L)}function q(k,I,L){var D=bn(I,L,!1);if(!N(D))return D.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,D){var Y=bn(L,D,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,D)}function G(k,I){var L=re(k,I),D=ko(k);if(D===null)return L;var Y=G(D,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=bn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function N(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",D=li(k,s);if(D!==void 0){var Y=D.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var D=L.call(k);if(!ue(D))return D}var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}}else{var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}var ve=k.toString;if(at(ve)){var D=ve.call(k);if(!ue(D))return D}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function vn(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function ai(k){return typeof k=="function"}function Rd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function So(k,I){return k===I||k!==k&&I!==I}function li(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ui(k){var I=li(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function di(k){return k.value}function ci(k){var I=k.next();return I.done?!1:I}function pi(k){var I=k.return;I&&I.call(k)}function ko(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,D=L&&Object.getPrototypeOf(L);if(D==null||D===Object.prototype)return I;var Y=D.constructor;return typeof Y!="function"||Y===k?I:Y}function Ed(){var k;!N(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Id(n.Reflect));var I,L,D,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case N(I):I=V;break;case I===V:break;case N(L):L=V;break;case L===V:break;default:D===void 0&&(D=new h),D.add(V);break}}function ne(V,oe){if(!N(I)){if(I.isProviderFor(V,oe))return I;if(!N(L)){if(L.isProviderFor(V,oe))return I;if(!N(D))for(var pe=ui(D);;){var be=ci(pe);if(!be)return;var Je=di(be);if(Je.isProviderFor(V,oe))return pi(pe),Je}}}if(!N(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return N(pe)||(be=pe.get(oe)),N(be)&&(be=ne(V,oe),N(be)||(N(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(N(V))throw new TypeError;return I===V||L===V||!N(D)&&D.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!N(be))return!1;var Je=Y.get(V);N(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function xd(){var k;return!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),N(k)&&(k=Ed()),!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function Ad(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return N(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function D(W,J,V){var oe=I.get(W),pe=!1;if(N(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(N(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=D(J,V,!1);return N(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=D(J,V,!1);if(!N(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=D(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=D(W,J,!1);if(N(oe))return V;for(var pe=oe.keys(),be=ui(pe),Je=0;;){var fi=ci(be);if(!fi)return V.length=Je,V;var Cd=di(fi);try{V[Je]=Cd}catch(Ld){try{pi(be)}finally{throw Ld}}Je++}}function B(W,J,V){var oe=D(J,V,!1);if(N(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);N(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Id(k){var I=k.defineMetadata,L=k.hasOwnMetadata,D=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!N(J)&&J.has(W)?!0:Y(B,W).length?(N(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:D,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function bn(k,I,L){var D=E.getProvider(k,I);if(!N(D))return D;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Td(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),D=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,So(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!So(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(So(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return D;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function Od(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Pd(){var k=16,I=d.create(),L=D();return(function(){function B(){this._key=D()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=D()},B})();function D(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function Ro(k){return k.__=void 0,delete k.__,k}})})(hi||(hi={}))});T();var iS=Ee(gi(),1),et=Ee(require("process"),1);T();var hc=Ee(require("os"),1),gc=Ee(require("path"),1),yc=require("url"),wc=require("util");T();var Di=require("crypto");T();var he=class extends Error{},jd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qd(t){if(typeof t!="string")return!1;let e=jd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Gd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",qd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yi(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new he(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Eo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function wi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Gd(await r.json())}T();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}T();var Be=class extends Error{name="ModelPriceError"},xo="per_million_input_tokens",Ao="per_million_output_tokens",vi="model_id,variant,unit,price_usd,effective_at,expires_at",_i={per_request:!0,per_minute:!0,per_output_unit:!0},Wd=5e3;function Jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function bi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Vd(t,e,n){return t===null?null:bi(t,e,n)}function Kd(t,e){if(t===xo)return"input";if(t===Ao)return"output";if(typeof t=="string"&&Object.hasOwn(_i,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${xo} | ${Ao}) nor a known GPU-time unit (${Object.keys(_i).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 zd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function Io(t,e){return`${t}\0${e}`}function Yd(t){if(!Array.isArray(t))throw new Be(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of vi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Kd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Jd(s.price_usd,o),effective_at:bi(s.effective_at,o,"effective_at"),expires_at:Vd(s.expires_at,o,"expires_at")})}return e}function Si(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=zd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(Io(l,m))?E.rate:{reason:`the ${h} 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`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Sn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var kn={prices:[],refusals:[]};async function ki(t){let e=t.fetchImpl??fetch,n=`${xo},${Ao}`,r=await e(`${t.catalogUrl}/model_prices?select=${vi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Yd(await r.json())}T();var Rt="/partners/openrouter/models",Xd={chat:!0,code:!0,agent:!0,vl:!0},Ri={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Qd(t){let e=t.toLowerCase();return Object.hasOwn(Ri,e)?Ri[e]:null}var Ei={"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 Zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ei,o)?Ei[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ai={2:"Llama2",3:"Llama3"};function ec(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xi,s))return xi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ai,i))return Ai[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var tc=["context_length","max_model_len"];function nc(t){let e=tc.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function or(t){let e=t.map(nc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function rc(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function To(t){if(t.length===0)return null;let e=t.map(rc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Oo(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function oc(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return Rn(r);let o=Oo(t,e);return o.length>0?Rn(o):null}function Rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:sc(t),matches:t}:null}function sc(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var mt=class extends Error{name="ModelCreatedError"};function Jt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new mt(`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 r=n[0];if(!n.every(d=>d===r))throw new mt(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function sr(t,e,n){let r=oc(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=or(s),a=Jt(s),l=Sn(o.model_id,o.variant,n),u=Oi(o,s),d=To(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ic=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...ic],defect:o}:{published:[],defect:o}}function Po(t){let e=t.length>0?Rn(t):null;return e===null?{published:[],defect:null}:Oi(e.row,e.matches)}function Ii(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ti(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ii(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ii(t.output)}]}}function ac(t,e,n,r){if(e.length===0)return null;let o=Rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Xd[s.task]!==!0)return null;let a=or(i),l=Sn(s.model_id,s.variant,n),u=ec(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Jt(i),quantization:Qd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ti(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ti(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Pi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ac(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}T();var Ci={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Li(t){let e=t.t;if(typeof e!="string"||!(e in Ci))throw new Vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ci).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function lc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Vt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Vt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Li(t)}function Mi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function $i(t,e){let n=t.stream("stt");if(typeof n.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*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Mi(e);let s=o.next();if(e!==void 0&&await uc(s,e)==="aborted")throw s.catch(()=>{}),Mi(e);let i=await s;if(i.done)return;yield lc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},$o="credits_exhausted",No="insufficient_credits",Lo="urs1.";function An(t,e){return Lo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Lo))return null;try{let e=JSON.parse(Buffer.from(t.slice(Lo.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 Fi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Ni(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=pc(t);return e===null?[]:[e]}function dc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var Md=Object.create;var mi=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var Fd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Bd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nd(e))!Dd.call(t,o)&&o!==n&&mi(t,o,{get:()=>e[o],enumerable:!(r=$d(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Md(Ud(t)):{},Hd(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var T=Fd(()=>{"use strict"});var gi=Bd(()=>{"use strict";T();var hi;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(d,c)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return Ro(Object.create(null))}:l?function(){return Ro({__proto__:null})}:function(){return Ro({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Td(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Od(),m=typeof WeakMap=="function"?WeakMap:Pd(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=xd(),x=Ad(E);function v(k,I,L,D){if(N(L)){if(!vn(k))throw new TypeError;if(!ai(I))throw new TypeError;return b(k,I)}else{if(!vn(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(D)&&!N(D)&&!ee(D))throw new TypeError;return ee(D)&&(D=void 0),L=$e(L),C(k,I,L,D)}}e("decorate",v);function _(k,I){function L(D,Y){if(!ue(D))throw new TypeError;if(!N(Y)&&!Rd(Y))throw new TypeError;X(k,I,D,Y)}return L}e("metadata",_);function p(k,I,L,D){if(!ue(L))throw new TypeError;return N(D)||(D=$e(D)),X(k,I,L,D)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),M(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),U(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function O(k,I,L){if(!ue(I))throw new TypeError;if(N(L)||(L=$e(L)),!ue(I))throw new TypeError;N(L)||(L=$e(L));var D=bn(I,L,!1);return N(D)?!1:D.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",O);function b(k,I){for(var L=k.length-1;L>=0;--L){var D=k[L],Y=D(I);if(!N(Y)&&!ee(Y)){if(!ai(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,D){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,D);if(!N(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;D=ke}}return D}function $(k,I,L){var D=M(k,I,L);if(D)return!0;var Y=ko(I);return ee(Y)?!1:$(k,Y,L)}function M(k,I,L){var D=bn(I,L,!1);return N(D)?!1:Me(D.OrdinaryHasOwnMetadata(k,I,L))}function U(k,I,L){var D=M(k,I,L);if(D)return q(k,I,L);var Y=ko(I);if(!ee(Y))return U(k,Y,L)}function q(k,I,L){var D=bn(I,L,!1);if(!N(D))return D.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,D){var Y=bn(L,D,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,D)}function G(k,I){var L=re(k,I),D=ko(k);if(D===null)return L;var Y=G(D,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=bn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function N(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",D=li(k,s);if(D!==void 0){var Y=D.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var D=L.call(k);if(!ue(D))return D}var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}}else{var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}var ve=k.toString;if(at(ve)){var D=ve.call(k);if(!ue(D))return D}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function vn(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function ai(k){return typeof k=="function"}function Rd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function So(k,I){return k===I||k!==k&&I!==I}function li(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ui(k){var I=li(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function di(k){return k.value}function ci(k){var I=k.next();return I.done?!1:I}function pi(k){var I=k.return;I&&I.call(k)}function ko(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,D=L&&Object.getPrototypeOf(L);if(D==null||D===Object.prototype)return I;var Y=D.constructor;return typeof Y!="function"||Y===k?I:Y}function Ed(){var k;!N(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Id(n.Reflect));var I,L,D,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case N(I):I=V;break;case I===V:break;case N(L):L=V;break;case L===V:break;default:D===void 0&&(D=new h),D.add(V);break}}function ne(V,oe){if(!N(I)){if(I.isProviderFor(V,oe))return I;if(!N(L)){if(L.isProviderFor(V,oe))return I;if(!N(D))for(var pe=ui(D);;){var be=ci(pe);if(!be)return;var Je=di(be);if(Je.isProviderFor(V,oe))return pi(pe),Je}}}if(!N(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return N(pe)||(be=pe.get(oe)),N(be)&&(be=ne(V,oe),N(be)||(N(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(N(V))throw new TypeError;return I===V||L===V||!N(D)&&D.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!N(be))return!1;var Je=Y.get(V);N(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function xd(){var k;return!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),N(k)&&(k=Ed()),!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function Ad(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return N(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function D(W,J,V){var oe=I.get(W),pe=!1;if(N(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(N(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=D(J,V,!1);return N(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=D(J,V,!1);if(!N(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=D(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=D(W,J,!1);if(N(oe))return V;for(var pe=oe.keys(),be=ui(pe),Je=0;;){var fi=ci(be);if(!fi)return V.length=Je,V;var Cd=di(fi);try{V[Je]=Cd}catch(Ld){try{pi(be)}finally{throw Ld}}Je++}}function B(W,J,V){var oe=D(J,V,!1);if(N(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);N(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Id(k){var I=k.defineMetadata,L=k.hasOwnMetadata,D=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!N(J)&&J.has(W)?!0:Y(B,W).length?(N(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:D,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function bn(k,I,L){var D=E.getProvider(k,I);if(!N(D))return D;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Td(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),D=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,So(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!So(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(So(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return D;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function Od(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Pd(){var k=16,I=d.create(),L=D();return(function(){function B(){this._key=D()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=D()},B})();function D(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function Ro(k){return k.__=void 0,delete k.__,k}})})(hi||(hi={}))});T();var iS=Ee(gi(),1),et=Ee(require("process"),1);T();var hc=Ee(require("os"),1),gc=Ee(require("path"),1),yc=require("url"),wc=require("util");T();var Di=require("crypto");T();var he=class extends Error{},jd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qd(t){if(typeof t!="string")return!1;let e=jd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Gd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",qd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yi(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new he(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Eo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function wi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Gd(await r.json())}T();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}T();var Be=class extends Error{name="ModelPriceError"},xo="per_million_input_tokens",Ao="per_million_output_tokens",vi="model_id,variant,unit,price_usd,effective_at,expires_at",_i={per_request:!0,per_minute:!0,per_output_unit:!0},Wd=5e3;function Jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function bi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Vd(t,e,n){return t===null?null:bi(t,e,n)}function Kd(t,e){if(t===xo)return"input";if(t===Ao)return"output";if(typeof t=="string"&&Object.hasOwn(_i,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${xo} | ${Ao}) nor a known GPU-time unit (${Object.keys(_i).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 zd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function Io(t,e){return`${t}\0${e}`}function Yd(t){if(!Array.isArray(t))throw new Be(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of vi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Kd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Jd(s.price_usd,o),effective_at:bi(s.effective_at,o,"effective_at"),expires_at:Vd(s.expires_at,o,"expires_at")})}return e}function Si(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=zd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(Io(l,m))?E.rate:{reason:`the ${h} 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`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Sn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var kn={prices:[],refusals:[]};async function ki(t){let e=t.fetchImpl??fetch,n=`${xo},${Ao}`,r=await e(`${t.catalogUrl}/model_prices?select=${vi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Yd(await r.json())}T();var Rt="/partners/openrouter/models",Xd={chat:!0,code:!0,agent:!0,vl:!0},Ri={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Qd(t){let e=t.toLowerCase();return Object.hasOwn(Ri,e)?Ri[e]:null}var Ei={"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 Zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ei,o)?Ei[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ai={2:"Llama2",3:"Llama3"};function ec(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xi,s))return xi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ai,i))return Ai[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var tc=["context_length","max_model_len"];function nc(t){let e=tc.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function or(t){let e=t.map(nc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function rc(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function To(t){if(t.length===0)return null;let e=t.map(rc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Oo(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function oc(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return Rn(r);let o=Oo(t,e);return o.length>0?Rn(o):null}function Rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:sc(t),matches:t}:null}function sc(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var mt=class extends Error{name="ModelCreatedError"};function Jt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new mt(`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 r=n[0];if(!n.every(d=>d===r))throw new mt(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function sr(t,e,n){let r=oc(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=or(s),a=Jt(s),l=Sn(o.model_id,o.variant,n),u=Oi(o,s),d=To(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ic=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...ic],defect:o}:{published:[],defect:o}}function Po(t){let e=t.length>0?Rn(t):null;return e===null?{published:[],defect:null}:Oi(e.row,e.matches)}function Ii(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ti(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ii(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ii(t.output)}]}}function ac(t,e,n,r){if(e.length===0)return null;let o=Rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Xd[s.task]!==!0)return null;let a=or(i),l=Sn(s.model_id,s.variant,n),u=ec(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Jt(i),quantization:Qd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ti(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ti(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Pi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ac(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}T();var Ci={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},Vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Li(t){let e=t.t;if(typeof e!="string"||!(e in Ci))throw new Vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ci).join(", ")}`);let n={kind:e};return e!=="turn_dropped"&&typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function lc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Vt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Vt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Li(t)}function Mi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function $i(t,e){let n=t.stream("stt");if(typeof n.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*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Mi(e);let s=o.next();if(e!==void 0&&await uc(s,e)==="aborted")throw s.catch(()=>{}),Mi(e);let i=await s;if(i.done)return;yield lc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},$o="credits_exhausted",No="insufficient_credits",Lo="urs1.";function An(t,e){return Lo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Lo))return null;try{let e=JSON.parse(Buffer.from(t.slice(Lo.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 Fi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Ni(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=pc(t);return e===null?[]:[e]}function dc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
4
  `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function Uo(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||Ue(`${r.model_id}-${r.variant}`)===e.appSlug||Ue(r.model_id)===e.appSlug)),n?dc(n.engine_args?.pool):null}function Co(t,e,n,r,o){if(!o)throw new he(`shared model "${t}" 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||n===void 0)throw new he(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new he(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Ui(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new he(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Bi="shared:",Kt="speech:",yt="realtime:";function gt(t){return t.sharedApp?Bi+t.appSlug:t.appSlug}function xn(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Mo(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ue(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function cc(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function pc(t){let e=t.map(cc),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var fc={stt:"stt",tts:"tts"};function ht(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:fc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Hi(t,e){let n=Mo(t,e);return n.length>0?n:Oo(t,e)}function En(t,e){return Hi(t.appSlug,e)}function mc(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new he(`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 n}var ir=6e4,ar=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,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??ir):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??ir):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??ir):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??ir;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof Be)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
5
  `),kn}let r=Si(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-WXO7IIRV.js";import"../chunk-NMNR3SQ5.js";import"../chunk-CAR4AEQJ.js";import"../chunk-MBIJRS4O.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-B3GQYAJ5.js";import"../chunk-KNWFUWXY.js";import{v as m,w as p}from"../chunk-6R3TCKOH.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
2
+ import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-SNCDIY53.js";import"../chunk-HIM6EB3J.js";import"../chunk-CAR4AEQJ.js";import"../chunk-RONITPWW.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-2VZR5MAX.js";import"../chunk-EA3GQ2MM.js";import{v as m,w as p}from"../chunk-O3Z5AY5E.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-4GW343S5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
3
3
  `);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
4
4
  `),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
5
5
  `),o.exit(1)});
@@ -1,5 +1,5 @@
1
1
  "use strict";var dd=Object.create;var Vn=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var pd=Object.getOwnPropertyNames;var fd=Object.getPrototypeOf,md=Object.prototype.hasOwnProperty;var gd=(t,e)=>{for(var n in e)Vn(t,n,{get:e[n],enumerable:!0})},di=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pd(e))!md.call(t,o)&&o!==n&&Vn(t,o,{get:()=>e[o],enumerable:!(r=cd(e,o))||r.enumerable});return t};var fe=(t,e,n)=>(n=t!=null?dd(fd(t)):{},di(e||!t||!t.__esModule?Vn(n,"default",{value:t,enumerable:!0}):n,t)),hd=t=>di(Vn({},"__esModule",{value:!0}),t);var hg={};gd(hg,{ANONYMOUS_KEY_ID:()=>Vr,BIND_HOST:()=>ed,BUCKET_DOMAIN:()=>Os,BoundedLabel:()=>Qt,ControlPlaneUnavailableError:()=>$e,ConversationBackhauls:()=>on,ConversationCapacityError:()=>Wn,DEFAULT_PORT:()=>zs,EDGE_IDENTITY_PORT:()=>Uu,EDGE_KEY_FINGERPRINT_HEADER:()=>Ts,EDGE_KEY_ID_HEADER:()=>Is,InferenceMetrics:()=>Zt,LEDGER_FUNCTION_PATH:()=>ri,LEDGER_WRITE_TIMEOUT_MS:()=>oi,LedgerClient:()=>an,LedgerDuplicateError:()=>sn,LedgerSurfaceError:()=>le,MAX_CACHED_KEYS:()=>Us,MAX_CACHED_MEMBERSHIPS:()=>Bs,MAX_CONVERSATIONS:()=>to,MAX_CONVERSATION_HANDLES:()=>Xs,MAX_MODEL_LABELS:()=>ks,MAX_ORG_LABELS:()=>Rs,MAX_TENANTS:()=>Ys,MEMBERSHIP_CHECK_TIMEOUT_MS:()=>Fs,MEMBERSHIP_VERDICT_TTL_MS:()=>Ds,METRICS_PATH:()=>Wr,METRICS_PORT:()=>Mu,MembershipGate:()=>qn,MembershipRefusalError:()=>Ge,NO_MODEL_LABEL:()=>Ss,ORG_BINDING_TTL_MS:()=>Ns,OTHER_LABEL:()=>Xt,OrgResolver:()=>St,ProxyAuthError:()=>V,READINESS_TIMEOUT_MS:()=>ai,READINESS_TTL_MS:()=>ii,SERVE_FUNCTION:()=>Gn,TIER_DOMAIN:()=>Ps,TenantRegistry:()=>rn,bearerFrom:()=>tn,bearerTokenOf:()=>$s,createEdgeIdentityServer:()=>Kr,createHostedProxy:()=>ud,createMetricsServer:()=>Jr,edgeBucketId:()=>Cs,edgeTierFingerprint:()=>Ls,laneOf:()=>Es,parseLedgerRecorded:()=>si,resolveHostedConfig:()=>td,statusClassOf:()=>xs,tenantSubject:()=>nn});module.exports=hd(hg);var id=require("http");function zn(t){let e=t.byteLength>>1,n=0;for(let r=0;r<e;r++){let o=t.readInt16LE(r*2);if(o>16||o<-16)return!1;n+=o*o}return n<=64*e}var pi="audio",io=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"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}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 o of this.outHandlers)o(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 fi(t,e,n=1e4){try{return await yd(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function yd(t,e,n){let r=new io(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(pi);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await wd(t,n);return await r.startInbound(i),r}function wd(t,e){let n=t.stream(pi);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var ci="rt-video-in",un=256e3;function lo(t){let e=t.stream(ci),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ci}') 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>un)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${un}-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 _d=24e3,ln=480,vd=111,bd=50,Kn=null;async function Sd(){if(Kn)return;let t=await import("opusscript");Kn=t.default??t}function kd(){if(!Kn)throw new Error("[opus-guard] opusscript module not loaded");return new Kn(_d,1,2048)}var ao=class{constructor(e=kd){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>=bd}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){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: ${o instanceof Error?o.message:String(o)}`);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 mi(){let t=await import("werift");await Sd();let e=new ao;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=ln;){let d=l.subarray(u,u+ln);u+=ln;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,ln);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+ln>>>0;let g=new t.RtpHeader({version:2,payloadType:vd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(g,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}var Yn=require("@urun-sh/core"),uo="rt-video-out";var Rd="h264";function Ed(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 xd(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(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}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 o=r;Ed(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var gi="urun.videoOut.v2-ws";function hi(t){let e=t.stream(uo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${uo}') 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,o=new Set,s=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${uo}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=xd(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:Rd,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var er="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ad=1007,wi=1008,Be=1011,tr=1008,L=class extends Error{constructor(n,r=Ad){super(n);this.closeCode=r}closeCode},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Xn=["setup","clientContent","realtimeInput","toolResponse"];function _i(t){let e;try{e=JSON.parse(t)}catch{throw new L("client message is not valid JSON")}let n=ie(e);if(!n)throw new L("client message must be a JSON object");let r=Xn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Xn.includes(a));if(o.length>0)throw new L(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Xn.join(", ")}`);if(r.length!==1)throw new L(`client message must contain exactly one of ${Xn.join(", ")} (got ${r.length})`);let s=r[0],i=ie(n[s]);if(!i)throw new L(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function vi(t,e){if(typeof t=="string")return t;let n=ie(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new L(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ie(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new L(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new L(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new L(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
- `)}var Id={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function bi(t){return{framing:gi,codec:t}}function Si(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Td={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Od=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],yi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pd(t){let e=ie(t);if(!e)throw new L("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new L(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new L("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new L(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new L("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!yi.includes(e.activityHandling))throw new L(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${yi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cd=["temperature","maxOutputTokens","responseModalities"];function ki(t){for(let[c,f]of Object.entries(Td))if(t[c]!==void 0)throw new L(f);for(let c of Object.keys(t))if(!Od.includes(c))throw new L(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new L('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new L("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Cd.includes(c))throw new L(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new L("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new L("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let g=String(f).toUpperCase();if(g==="AUDIO"){o=!0;continue}if(g!=="TEXT")throw new L(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:vi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new L("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new L("setup.tools entries must be objects");for(let g of Object.keys(f))if(g!=="functionDeclarations")throw new L(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new L("tool.functionDeclarations must be an array");for(let g of f.functionDeclarations){let m=ie(g);if(!m||typeof m.name!="string")throw new L("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new L("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new L(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new L("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?Id:Pd(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ie(t[nt]))throw new L(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function Ri(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ei(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function xi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new L(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new L("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new L("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new L(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:vi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Qn=16e3,Ai=24e3,Ld=`audio/pcm;rate=${Ai}`,Ii=Buffer.alloc(960).toString("base64");function $d(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Md(t){let e=ie(t);if(!e)throw new L("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new L("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Nd(t){let e=ie(t);if(!e)throw new L("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Qn)throw new L(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Qn} Hz (audio/pcm;rate=${Qn})`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new L(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=$d(o,Qn,Ai);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ti(t){if(t.mediaChunks!==void 0)throw new L('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new L("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new L(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new L(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new L(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Nd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Md(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new L("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new L("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Oi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new L(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new L("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new L("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Pi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ci(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ld,data:t}}]}}}}function Li(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new L(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Be);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new L(`upstream function_call arguments are not valid JSON: ${c}`,Be)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var sa=require("crypto"),ia=require("ws");var ta=require("crypto");var ee=class extends Error{},Ud=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Dd(t){if(typeof t!="string")return!1;let e=Ud.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Fd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new ee(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new ee(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Dd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new ee(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $i(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function co(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new ee(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function Mi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Fd(await r.json())}function we(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ve=class extends Error{name="ModelPriceError"},po="per_million_input_tokens",fo="per_million_output_tokens",Ui="model_id,variant,unit,price_usd,effective_at,expires_at",Ni={per_request:!0,per_minute:!0,per_output_unit:!0},Bd=5e3;function Hd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ve(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Di(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ve(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function jd(t,e,n){return t===null?null:Di(t,e,n)}function qd(t,e){if(t===po)return"input";if(t===fo)return"output";if(typeof t=="string"&&Object.hasOwn(Ni,t))return null;throw new ve(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${po} | ${fo}) nor a known GPU-time unit (${Object.keys(Ni).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 Gd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function mo(t,e){return`${t}\0${e}`}function Wd(t){if(!Array.isArray(t))throw new ve(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ve(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Ui.split(","))if(!Object.hasOwn(s,u))throw new ve(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=qd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ve(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ve(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Hd(s.price_usd,o),effective_at:Di(s.effective_at,o,"effective_at"),expires_at:jd(s.expires_at,o,"expires_at")})}return e}function Fi(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,g,m)=>{let w=f&&f.length>0?f:d?.[g];if(!w||w.length===0)return null;let E=Gd(w,g);return"reason"in E?E:E.rate.usd===0?g==="output"&&m!==null&&n?.has(mo(l,m))?E.rate:{reason:`the ${g} 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`}:E.rate};for(let[f,g]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",g),E=c(m?.output,"output",g);if(w!==null&&"reason"in w){i.push({model_id:l,variant:g,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:g,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:g,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function dn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var cn={prices:[],refusals:[]};async function Bi(t){let e=t.fetchImpl??fetch,n=`${po},${fo}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ui}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Bd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Wd(await r.json())}var ot="/partners/openrouter/models",Jd={chat:!0,code:!0,agent:!0,vl:!0},Hi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Vd(t){let e=t.toLowerCase();return Object.hasOwn(Hi,e)?Hi[e]:null}var ji={"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 Kd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ji,o)?ji[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var qi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gi={2:"Llama2",3:"Llama3"};function zd(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(qi,s))return qi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gi,i))return Gi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Yd=["context_length","max_model_len"];function Xd(t){let e=Yd.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function nr(t){let e=t.map(Xd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Qd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function go(t){if(t.length===0)return null;let e=t.map(Qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ho(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Zd(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>we(s.model_id)===t);if(r.length>0)return pn(r);let o=ho(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ec(t),matches:t}:null}function ec(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var We=class extends Error{name="ModelCreatedError"};function Et(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new We(`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 r=n[0];if(!n.every(d=>d===r))throw new We(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function rt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rr(t,e,n){let r=Zd(t,e);if(!r)return rt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=nr(s),a=Et(s),l=dn(o.model_id,o.variant,n),u=Vi(o,s),d=go(s);return rt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var tc=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...tc],defect:o}:{published:[],defect:o}}function yo(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:Vi(e.row,e.matches)}function Wi(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ji(t){return{input:[{type:"prompt",unit:"token",cost_usd:Wi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Wi(t.output)}]}}function nc(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Jd[s.task]!==!0)return null;let a=nr(i),l=dn(s.model_id,s.variant,n),u=zd(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Et(i),quantization:Vd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ji(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ji(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ki(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Rt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Kd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=nc(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var zi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},xt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Yi(t){let e=t.t;if(typeof e!="string"||!(e in zi))throw new xt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(zi).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function rc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new xt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new xt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Yi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new xt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Yi(t)}function Xi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function oc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Qi(t,e){let n=t.stream("stt");if(typeof n.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*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Xi(e);let s=o.next();if(e!==void 0&&await oc(s,e)==="aborted")throw s.catch(()=>{}),Xi(e);let i=await s;if(i.done)return;yield rc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var J=class extends Error{},G=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},bo="credits_exhausted",So="insufficient_credits",_o="urs1.";function gn(t,e){return _o+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function st(t){if(!t.startsWith(_o))return null;try{let e=JSON.parse(Buffer.from(t.slice(_o.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 na(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Zi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ac(t);return e===null?[]:[e]}function sc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ `)}var Id={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function bi(t){return{framing:gi,codec:t}}function Si(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Td={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Od=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],yi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pd(t){let e=ie(t);if(!e)throw new L("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new L(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new L("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new L(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new L("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!yi.includes(e.activityHandling))throw new L(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${yi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cd=["temperature","maxOutputTokens","responseModalities"];function ki(t){for(let[c,f]of Object.entries(Td))if(t[c]!==void 0)throw new L(f);for(let c of Object.keys(t))if(!Od.includes(c))throw new L(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new L('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new L("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Cd.includes(c))throw new L(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new L("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new L("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let g=String(f).toUpperCase();if(g==="AUDIO"){o=!0;continue}if(g!=="TEXT")throw new L(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:vi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new L("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new L("setup.tools entries must be objects");for(let g of Object.keys(f))if(g!=="functionDeclarations")throw new L(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new L("tool.functionDeclarations must be an array");for(let g of f.functionDeclarations){let m=ie(g);if(!m||typeof m.name!="string")throw new L("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new L("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new L(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new L("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?Id:Pd(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ie(t[nt]))throw new L(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function Ri(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ei(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function xi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new L(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new L("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new L("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new L(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:vi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Qn=16e3,Ai=24e3,Ld=`audio/pcm;rate=${Ai}`,Ii=Buffer.alloc(960).toString("base64");function $d(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Md(t){let e=ie(t);if(!e)throw new L("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new L("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Nd(t){let e=ie(t);if(!e)throw new L("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Qn)throw new L(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Qn} Hz (audio/pcm;rate=${Qn})`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new L(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=$d(o,Qn,Ai);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ti(t){if(t.mediaChunks!==void 0)throw new L('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new L("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new L(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new L(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new L(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Nd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Md(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new L("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new L("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Oi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new L(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new L("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new L("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Pi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ci(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ld,data:t}}]}}}}function Li(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new L(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Be);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new L(`upstream function_call arguments are not valid JSON: ${c}`,Be)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var sa=require("crypto"),ia=require("ws");var ta=require("crypto");var ee=class extends Error{},Ud=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Dd(t){if(typeof t!="string")return!1;let e=Ud.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Fd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new ee(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new ee(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Dd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new ee(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $i(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function co(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new ee(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function Mi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Fd(await r.json())}function we(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ve=class extends Error{name="ModelPriceError"},po="per_million_input_tokens",fo="per_million_output_tokens",Ui="model_id,variant,unit,price_usd,effective_at,expires_at",Ni={per_request:!0,per_minute:!0,per_output_unit:!0},Bd=5e3;function Hd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ve(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Di(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ve(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function jd(t,e,n){return t===null?null:Di(t,e,n)}function qd(t,e){if(t===po)return"input";if(t===fo)return"output";if(typeof t=="string"&&Object.hasOwn(Ni,t))return null;throw new ve(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${po} | ${fo}) nor a known GPU-time unit (${Object.keys(Ni).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 Gd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function mo(t,e){return`${t}\0${e}`}function Wd(t){if(!Array.isArray(t))throw new ve(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ve(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Ui.split(","))if(!Object.hasOwn(s,u))throw new ve(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=qd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ve(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ve(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Hd(s.price_usd,o),effective_at:Di(s.effective_at,o,"effective_at"),expires_at:jd(s.expires_at,o,"expires_at")})}return e}function Fi(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,g,m)=>{let w=f&&f.length>0?f:d?.[g];if(!w||w.length===0)return null;let E=Gd(w,g);return"reason"in E?E:E.rate.usd===0?g==="output"&&m!==null&&n?.has(mo(l,m))?E.rate:{reason:`the ${g} 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`}:E.rate};for(let[f,g]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",g),E=c(m?.output,"output",g);if(w!==null&&"reason"in w){i.push({model_id:l,variant:g,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:g,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:g,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function dn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var cn={prices:[],refusals:[]};async function Bi(t){let e=t.fetchImpl??fetch,n=`${po},${fo}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ui}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Bd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Wd(await r.json())}var ot="/partners/openrouter/models",Jd={chat:!0,code:!0,agent:!0,vl:!0},Hi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Vd(t){let e=t.toLowerCase();return Object.hasOwn(Hi,e)?Hi[e]:null}var ji={"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 Kd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ji,o)?ji[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var qi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gi={2:"Llama2",3:"Llama3"};function zd(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(qi,s))return qi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gi,i))return Gi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Yd=["context_length","max_model_len"];function Xd(t){let e=Yd.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function nr(t){let e=t.map(Xd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Qd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function go(t){if(t.length===0)return null;let e=t.map(Qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ho(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Zd(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>we(s.model_id)===t);if(r.length>0)return pn(r);let o=ho(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ec(t),matches:t}:null}function ec(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var We=class extends Error{name="ModelCreatedError"};function Et(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new We(`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 r=n[0];if(!n.every(d=>d===r))throw new We(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function rt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rr(t,e,n){let r=Zd(t,e);if(!r)return rt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=nr(s),a=Et(s),l=dn(o.model_id,o.variant,n),u=Vi(o,s),d=go(s);return rt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var tc=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...tc],defect:o}:{published:[],defect:o}}function yo(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:Vi(e.row,e.matches)}function Wi(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ji(t){return{input:[{type:"prompt",unit:"token",cost_usd:Wi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Wi(t.output)}]}}function nc(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Jd[s.task]!==!0)return null;let a=nr(i),l=dn(s.model_id,s.variant,n),u=zd(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Et(i),quantization:Vd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ji(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ji(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ki(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Rt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Kd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=nc(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var zi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},xt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Yi(t){let e=t.t;if(typeof e!="string"||!(e in zi))throw new xt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(zi).join(", ")}`);let n={kind:e};return e!=="turn_dropped"&&typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function rc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new xt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new xt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Yi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new xt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Yi(t)}function Xi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function oc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Qi(t,e){let n=t.stream("stt");if(typeof n.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*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Xi(e);let s=o.next();if(e!==void 0&&await oc(s,e)==="aborted")throw s.catch(()=>{}),Xi(e);let i=await s;if(i.done)return;yield rc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var J=class extends Error{},G=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},bo="credits_exhausted",So="insufficient_credits",_o="urs1.";function gn(t,e){return _o+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function st(t){if(!t.startsWith(_o))return null;try{let e=JSON.parse(Buffer.from(t.slice(_o.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 na(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Zi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ac(t);return e===null?[]:[e]}function sc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
4
  `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function ko(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||we(`${r.model_id}-${r.variant}`)===e.appSlug||we(r.model_id)===e.appSlug)),n?sc(n.engine_args?.pool):null}function wo(t,e,n,r,o){if(!o)throw new ee(`shared model "${t}" 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||n===void 0)throw new ee(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new ee(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function ea(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new ee(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var ra="shared:",At="speech:",Ke="realtime:";function Ve(t){return t.sharedApp?ra+t.appSlug:t.appSlug}function mn(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function vo(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>we(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ic(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ac(t){let e=t.map(ic),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var lc={stt:"stt",tts:"tts"};function Je(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:lc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function oa(t,e){let n=vo(t,e);return n.length>0?n:ho(t,e)}function fn(t,e){return oa(t.appSlug,e)}function uc(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new ee(`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 n}var or=6e4,sr=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,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??or):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??or):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??or):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??or;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ve)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
5
  `),cn}let r=Fi(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
@@ -1,5 +1,5 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-CIOofxp2.cjs';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-4JhDPmCP.cjs';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
@@ -1,5 +1,5 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-lokLYIya.js';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-BjRgfMOX.js';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
@@ -1 +1 @@
1
- import{A as g,B as x,C as H,D as B,E as P,F as v,G as y,H as u,I as G,J as h,K as U,L as b,M as X,N as F,O as K,P as Y,Q as k,R as V,S as j,T as W,U as q,V as w,W as z,X as J,Y as Q,Z,a as r,b as o,c as t,d as E,e as _,f as n,g as a,h as T,i,j as s,k as M,l as O,m as p,n as I,o as R,p as S,q as A,r as C,s as D,t as N,u as f,v as L,w as d,x as l,y as m,z as c}from"../chunk-WXO7IIRV.js";import"../chunk-NMNR3SQ5.js";import"../chunk-CAR4AEQJ.js";import"../chunk-MBIJRS4O.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-B3GQYAJ5.js";import"../chunk-KNWFUWXY.js";import"../chunk-6R3TCKOH.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{A as ANONYMOUS_KEY_ID,G as BIND_HOST,R as BUCKET_DOMAIN,i as BoundedLabel,d as ControlPlaneUnavailableError,k as ConversationBackhauls,Y as ConversationCapacityError,y as DEFAULT_PORT,O as EDGE_IDENTITY_PORT,I as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,s as InferenceMetrics,V as LEDGER_FUNCTION_PATH,j as LEDGER_WRITE_TIMEOUT_MS,z as LedgerClient,W as LedgerDuplicateError,q as LedgerSurfaceError,c as MAX_CACHED_KEYS,B as MAX_CACHED_MEMBERSHIPS,F as MAX_CONVERSATIONS,K as MAX_CONVERSATION_HANDLES,_ as MAX_MODEL_LABELS,n as MAX_ORG_LABELS,U as MAX_TENANTS,H as MEMBERSHIP_CHECK_TIMEOUT_MS,x as MEMBERSHIP_VERDICT_TTL_MS,o as METRICS_PATH,r as METRICS_PORT,v as MembershipGate,P as MembershipRefusalError,E as NO_MODEL_LABEL,m as ORG_BINDING_TTL_MS,t as OTHER_LABEL,g as OrgResolver,L as ProxyAuthError,Q as READINESS_TIMEOUT_MS,J as READINESS_TTL_MS,u as SERVE_FUNCTION,S as TIER_DOMAIN,X as TenantRegistry,l as bearerFrom,N as bearerTokenOf,f as createEdgeIdentityServer,Z as createHostedProxy,M as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,w as parseLedgerRecorded,h as resolveHostedConfig,T as statusClassOf,b as tenantSubject};
1
+ import{A as g,B as x,C as H,D as B,E as P,F as v,G as y,H as u,I as G,J as h,K as U,L as b,M as X,N as F,O as K,P as Y,Q as k,R as V,S as j,T as W,U as q,V as w,W as z,X as J,Y as Q,Z,a as r,b as o,c as t,d as E,e as _,f as n,g as a,h as T,i,j as s,k as M,l as O,m as p,n as I,o as R,p as S,q as A,r as C,s as D,t as N,u as f,v as L,w as d,x as l,y as m,z as c}from"../chunk-SNCDIY53.js";import"../chunk-HIM6EB3J.js";import"../chunk-CAR4AEQJ.js";import"../chunk-RONITPWW.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-2VZR5MAX.js";import"../chunk-EA3GQ2MM.js";import"../chunk-O3Z5AY5E.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-4GW343S5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{A as ANONYMOUS_KEY_ID,G as BIND_HOST,R as BUCKET_DOMAIN,i as BoundedLabel,d as ControlPlaneUnavailableError,k as ConversationBackhauls,Y as ConversationCapacityError,y as DEFAULT_PORT,O as EDGE_IDENTITY_PORT,I as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,s as InferenceMetrics,V as LEDGER_FUNCTION_PATH,j as LEDGER_WRITE_TIMEOUT_MS,z as LedgerClient,W as LedgerDuplicateError,q as LedgerSurfaceError,c as MAX_CACHED_KEYS,B as MAX_CACHED_MEMBERSHIPS,F as MAX_CONVERSATIONS,K as MAX_CONVERSATION_HANDLES,_ as MAX_MODEL_LABELS,n as MAX_ORG_LABELS,U as MAX_TENANTS,H as MEMBERSHIP_CHECK_TIMEOUT_MS,x as MEMBERSHIP_VERDICT_TTL_MS,o as METRICS_PATH,r as METRICS_PORT,v as MembershipGate,P as MembershipRefusalError,E as NO_MODEL_LABEL,m as ORG_BINDING_TTL_MS,t as OTHER_LABEL,g as OrgResolver,L as ProxyAuthError,Q as READINESS_TIMEOUT_MS,J as READINESS_TTL_MS,u as SERVE_FUNCTION,S as TIER_DOMAIN,X as TenantRegistry,l as bearerFrom,N as bearerTokenOf,f as createEdgeIdentityServer,Z as createHostedProxy,M as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,w as parseLedgerRecorded,h as resolveHostedConfig,T as statusClassOf,b as tenantSubject};
@@ -1,4 +1,4 @@
1
- import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-N3Y2GDQK.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
1
+ import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-4GW343S5.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
2
2
  `)}catch(o){if(!V){V=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(o)}); further urun-side console output will be dropped
3
3
  `)}catch{}}}}var f=t=>(...e)=>te(t,e),j={log:f("log"),info:f("info"),warn:f("warn"),error:f("error"),debug:f("debug"),trace:f("trace"),dir:f("dir"),table:f("table"),group:f("group"),groupCollapsed:f("groupCollapsed"),groupEnd:f("groupEnd"),count:f("count"),countReset:f("countReset"),time:f("time"),timeLog:f("timeLog"),timeEnd:f("timeEnd"),assert:(t,...e)=>{t||te("assert",e.length>0?e:["Assertion failed"])}};function q(t){try{process.stderr.write(t)}catch{}}C();async function ne(t){let e=await Q(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var ae="urun-serve",xe="serve",Re=131072,be=16384,oe=3,Te=42e4,Ee=6e4,re=2,Se=15e3;function Ae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||W,fnName:(t.URUN_FUNCTION??"").trim()||xe}}function Ue(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let s=(t.URUN_API_KEY??"").trim();if(!s)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let l=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:s,gatewayUrl:l}}}function Ie(t){let e=null;return n=>{e===null&&(we(ve(t),{recursive:!0}),e=_e(t,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";ke(e,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
4
4
  `)}}function Pe(t){let e=Ie(J());return async(n,o,s)=>{let{baseUrl:l,orgId:i,auth:p}=Ue(n),{App:k,createClientToken:a}=await t(),m=(p.lane==="jwt"?k(o,{baseUrl:l,orgId:i,jwt:p.jwt,diagnosticSink:e}):k(o,{baseUrl:l,orgId:i,diagnosticSink:e,getAccessToken:async()=>(await a(p.apiKey,{baseUrl:p.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${s}`]})).token}))[s];if(typeof m!="function")throw new Error(`urun pi extension: app "${o}" has no function "${s}"`);let h=m();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${o}" function "${s}" returned a session without end()`);let A=h.connect;return typeof A=="function"&&await A.call(h),h}}var Ce=Pe(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function Ne(t,e){try{return Promise.resolve(t.end()).then(()=>{},n=>e(n))}catch(n){return e(n),Promise.resolve()}}function $e(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let n=e.indexOf("--mode");return n!==-1&&(e[n+1]==="json"||e[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function le(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var H=class{constructor(e,n,o,s=(l,i)=>j.warn(le(l,i))){this.open=e;this.env=n;this.fnName=o;this.onReleaseError=s}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(s=>({session:s,responses:new z(s)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);if(!n)return Promise.resolve();this.pool.delete(e);let o=n.then(s=>Ne(s.session,l=>this.onReleaseError(e,l)),()=>{});return this.releasing.add(o),o.then(()=>this.releasing.delete(o)),o}closeAll(){let e=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...e,...this.releasing]).then(()=>{})}};function Le(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){if(n.role==="toolResult"){e.push({type:"function_call_output",call_id:n.toolCallId,output:De(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let s="",l=()=>{s&&(e.push({role:"assistant",content:s}),s="")};for(let i of n.content)if(i.type==="text")s+=String(i.text??"");else if(i.type==="toolCall")l(),e.push({type:"function_call",call_id:String(i.id??""),name:String(i.name??""),arguments:JSON.stringify(i.arguments??{})});else{if(i.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(i.type)}"`)}l();continue}let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:Me(n.content)})}return Oe(e)}function Oe(t){let e=[];for(let n of t){let o=e[e.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(s=>s.length>0).join(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as Ce}from"../chunk-LM4E5YM2.js";import{a as te,b as ne,c as se,d as re}from"../chunk-B3GQYAJ5.js";import{a as X}from"../chunk-KNWFUWXY.js";import{c as W,v as q,w as z}from"../chunk-6R3TCKOH.js";import{a as Q,b as Z,d as ee}from"../chunk-XNRPTMSL.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as A}from"../chunk-N3Y2GDQK.js";import{b as Ge,c as p}from"../chunk-YSFSRI3D.js";p();var mn=Ge(Ce(),1);import w from"process";import{Redis as kt}from"ioredis";p();p();var D=`
2
+ import{a as Ce}from"../chunk-LM4E5YM2.js";import{a as te,b as ne,c as se,d as re}from"../chunk-2VZR5MAX.js";import{a as X}from"../chunk-EA3GQ2MM.js";import{c as W,v as q,w as z}from"../chunk-O3Z5AY5E.js";import{a as Q,b as Z,d as ee}from"../chunk-XNRPTMSL.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as A}from"../chunk-4GW343S5.js";import{b as Ge,c as p}from"../chunk-YSFSRI3D.js";p();var mn=Ge(Ce(),1);import w from"process";import{Redis as kt}from"ioredis";p();p();var D=`
3
3
  local slot, retired, meta, idx = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
4
4
  local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
5
5
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md