@urun-sh/openai 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4MSBS7M6.js +1 -0
- package/dist/{chunk-G3NMGP4N.js → chunk-GBBY3PCZ.js} +1 -1
- package/dist/chunk-K23AZPI4.js +1 -0
- package/dist/chunk-OI2OY32M.js +1 -0
- package/dist/chunk-RQBD4OAA.js +6 -0
- package/dist/{chunk-EWCEZIOX.js → chunk-STFRT5OY.js} +1 -1
- package/dist/{chunk-M6ICU4F5.js → chunk-VNM4M4P3.js} +12 -12
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +6 -0
- package/dist/gemini-live.d.ts +6 -0
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +16 -16
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +16 -16
- package/dist/hosted/index.d.cts +94 -13
- package/dist/hosted/index.d.ts +44 -11
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -18
- package/dist/index.d.ts +2 -18
- package/dist/index.js +1 -1
- package/dist/models-NYMZrklp.d.cts +38 -0
- package/dist/models-NYMZrklp.d.ts +38 -0
- package/dist/pi-extension/index.cjs +6 -6
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +50 -50
- package/dist/proxy/cli.cjs +31 -31
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +13 -13
- package/dist/proxy/index.d.cts +1 -1
- package/dist/proxy/index.d.ts +1 -1
- package/dist/proxy/index.js +1 -1
- package/dist/{server-l1himPxc.d.ts → server-DuH_5OD9.d.ts} +2 -0
- package/dist/{server-BfME37pQ.d.cts → server-wmUnMewW.d.cts} +6 -0
- package/package.json +3 -3
- package/dist/chunk-F2TEK34X.js +0 -1
- package/dist/chunk-TE6632EU.js +0 -6
- package/dist/chunk-UVAY7Q7Z.js +0 -1
- package/dist/chunk-XHIIEA6Z.js +0 -1
package/dist/hosted/bin.cjs
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var an=Object.create;var gt=Object.defineProperty;var un=Object.getOwnPropertyDescriptor;var cn=Object.getOwnPropertyNames;var ln=Object.getPrototypeOf,dn=Object.prototype.hasOwnProperty;var pn=(t,n,e)=>()=>{if(e)throw e[0];try{return t&&(n=t(t=0)),n}catch(r){throw e=[r],r}};var fn=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var mn=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of cn(n))!dn.call(t,o)&&o!==e&>(t,o,{get:()=>n[o],enumerable:!(r=un(n,o))||r.enumerable});return t};var ve=(t,n,e)=>(e=t!=null?an(ln(t)):{},mn(n||!t||!t.__esModule?gt(e,"default",{value:t,enumerable:!0}):e,t));var S=pn(()=>{"use strict"});var wt=fn(()=>{"use strict";S();var yt;(function(t){(function(n){var e=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:l(),r=o(t);typeof e.Reflect<"u"&&(r=o(e.Reflect,r)),n(r,e),typeof e.Reflect>"u"&&(e.Reflect=t);function o(d,p){return function(h,x){Object.defineProperty(d,h,{configurable:!0,writable:!0,value:x}),p&&p(h,x)}}function u(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return u()||a()}})(function(n,e){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",u=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",d={__proto__:[]}instanceof Array,p=!l&&!d,h={create:l?function(){return Je(Object.create(null))}:d?function(){return Je({__proto__:null})}:function(){return Je({})},has:p?function(s,i){return r.call(s,i)}:function(s,i){return i in s},get:p?function(s,i){return r.call(s,i)?s[i]:void 0}:function(s,i){return s[i]}},x=Object.getPrototypeOf(Function),A=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:tn(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:nn(),P=typeof WeakMap=="function"?WeakMap:rn(),T=o?Symbol.for("@reflect-metadata:registry"):void 0,g=Qt(),F=Zt(g);function G(s,i,c,f){if(y(c)){if(!ut(s))throw new TypeError;if(!ct(i))throw new TypeError;return z(s,i)}else{if(!ut(s))throw new TypeError;if(!R(i))throw new TypeError;if(!R(f)&&!y(f)&&!L(f))throw new TypeError;return L(f)&&(f=void 0),c=Z(c),N(s,i,c,f)}}n("decorate",G);function K(s,i){function c(f,b){if(!R(f))throw new TypeError;if(!y(b)&&!Yt(b))throw new TypeError;ce(s,i,f,b)}return c}n("metadata",K);function W(s,i,c,f){if(!R(c))throw new TypeError;return y(f)||(f=Z(f)),ce(s,i,c,f)}n("defineMetadata",W);function Y(s,i,c){if(!R(i))throw new TypeError;return y(c)||(c=Z(c)),j(s,i,c)}n("hasMetadata",Y);function _(s,i,c){if(!R(i))throw new TypeError;return y(c)||(c=Z(c)),Q(s,i,c)}n("hasOwnMetadata",_);function D(s,i,c){if(!R(i))throw new TypeError;return y(c)||(c=Z(c)),ne(s,i,c)}n("getMetadata",D);function ee(s,i,c){if(!R(i))throw new TypeError;return y(c)||(c=Z(c)),$(s,i,c)}n("getOwnMetadata",ee);function J(s,i){if(!R(s))throw new TypeError;return y(i)||(i=Z(i)),pe(s,i)}n("getMetadataKeys",J);function X(s,i){if(!R(s))throw new TypeError;return y(i)||(i=Z(i)),fe(s,i)}n("getOwnMetadataKeys",X);function te(s,i,c){if(!R(i))throw new TypeError;if(y(c)||(c=Z(c)),!R(i))throw new TypeError;y(c)||(c=Z(c));var f=Ee(i,c,!1);return y(f)?!1:f.OrdinaryDeleteMetadata(s,i,c)}n("deleteMetadata",te);function z(s,i){for(var c=s.length-1;c>=0;--c){var f=s[c],b=f(i);if(!y(b)&&!L(b)){if(!ct(b))throw new TypeError;i=b}}return i}function N(s,i,c,f){for(var b=s.length-1;b>=0;--b){var V=s[b],q=V(i,c,f);if(!y(q)&&!L(q)){if(!R(q))throw new TypeError;f=q}}return f}function j(s,i,c){var f=Q(s,i,c);if(f)return!0;var b=qe(i);return L(b)?!1:j(s,b,c)}function Q(s,i,c){var f=Ee(i,c,!1);return y(f)?!1:ge(f.OrdinaryHasOwnMetadata(s,i,c))}function ne(s,i,c){var f=Q(s,i,c);if(f)return $(s,i,c);var b=qe(i);if(!L(b))return ne(s,b,c)}function $(s,i,c){var f=Ee(i,c,!1);if(!y(f))return f.OrdinaryGetOwnMetadata(s,i,c)}function ce(s,i,c,f){var b=Ee(c,f,!0);b.OrdinaryDefineOwnMetadata(s,i,c,f)}function pe(s,i){var c=fe(s,i),f=qe(s);if(f===null)return c;var b=pe(f,i);if(b.length<=0)return c;if(c.length<=0)return b;for(var V=new U,q=[],E=0,m=c;E<m.length;E++){var w=m[E],v=V.has(w);v||(V.add(w),q.push(w))}for(var k=0,O=b;k<O.length;k++){var w=O[k],v=V.has(w);v||(V.add(w),q.push(w))}return q}function fe(s,i){var c=Ee(s,i,!1);return c?c.OrdinaryOwnMetadataKeys(s,i):[]}function I(s){if(s===null)return 1;switch(typeof s){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return s===null?1:6;default:return 6}}function y(s){return s===void 0}function L(s){return s===null}function C(s){return typeof s=="symbol"}function R(s){return typeof s=="object"?s!==null:typeof s=="function"}function se(s,i){switch(I(s)){case 0:return s;case 1:return s;case 2:return s;case 3:return s;case 4:return s;case 5:return s}var c=i===3?"string":i===5?"number":"default",f=lt(s,u);if(f!==void 0){var b=f.call(s,c);if(R(b))throw new TypeError;return b}return he(s,c==="default"?"number":c)}function he(s,i){if(i==="string"){var c=s.toString;if(_e(c)){var f=c.call(s);if(!R(f))return f}var b=s.valueOf;if(_e(b)){var f=b.call(s);if(!R(f))return f}}else{var b=s.valueOf;if(_e(b)){var f=b.call(s);if(!R(f))return f}var V=s.toString;if(_e(V)){var f=V.call(s);if(!R(f))return f}}throw new TypeError}function ge(s){return!!s}function Re(s){return""+s}function Z(s){var i=se(s,3);return C(i)?i:Re(i)}function ut(s){return Array.isArray?Array.isArray(s):s instanceof Object?s instanceof Array:Object.prototype.toString.call(s)==="[object Array]"}function _e(s){return typeof s=="function"}function ct(s){return typeof s=="function"}function Yt(s){switch(I(s)){case 3:return!0;case 4:return!0;default:return!1}}function Ge(s,i){return s===i||s!==s&&i!==i}function lt(s,i){var c=s[i];if(c!=null){if(!_e(c))throw new TypeError;return c}}function dt(s){var i=lt(s,a);if(!_e(i))throw new TypeError;var c=i.call(s);if(!R(c))throw new TypeError;return c}function pt(s){return s.value}function ft(s){var i=s.next();return i.done?!1:i}function mt(s){var i=s.return;i&&i.call(s)}function qe(s){var i=Object.getPrototypeOf(s);if(typeof s!="function"||s===x||i!==x)return i;var c=s.prototype,f=c&&Object.getPrototypeOf(c);if(f==null||f===Object.prototype)return i;var b=f.constructor;return typeof b!="function"||b===s?i:b}function Xt(){var s;!y(T)&&typeof e.Reflect<"u"&&!(T in e.Reflect)&&typeof e.Reflect.defineMetadata=="function"&&(s=en(e.Reflect));var i,c,f,b=new P,V={registerProvider:q,getProvider:m,setProvider:v};return V;function q(k){if(!Object.isExtensible(V))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case s===k:break;case y(i):i=k;break;case i===k:break;case y(c):c=k;break;case c===k:break;default:f===void 0&&(f=new U),f.add(k);break}}function E(k,O){if(!y(i)){if(i.isProviderFor(k,O))return i;if(!y(c)){if(c.isProviderFor(k,O))return i;if(!y(f))for(var M=dt(f);;){var H=ft(M);if(!H)return;var oe=pt(H);if(oe.isProviderFor(k,O))return mt(M),oe}}}if(!y(s)&&s.isProviderFor(k,O))return s}function m(k,O){var M=b.get(k),H;return y(M)||(H=M.get(O)),y(H)&&(H=E(k,O),y(H)||(y(M)&&(M=new A,b.set(k,M)),M.set(O,H))),H}function w(k){if(y(k))throw new TypeError;return i===k||c===k||!y(f)&&f.has(k)}function v(k,O,M){if(!w(M))throw new Error("Metadata provider not registered.");var H=m(k,O);if(H!==M){if(!y(H))return!1;var oe=b.get(k);y(oe)&&(oe=new A,b.set(k,oe)),oe.set(O,M)}return!0}}function Qt(){var s;return!y(T)&&R(e.Reflect)&&Object.isExtensible(e.Reflect)&&(s=e.Reflect[T]),y(s)&&(s=Xt()),!y(T)&&R(e.Reflect)&&Object.isExtensible(e.Reflect)&&Object.defineProperty(e.Reflect,T,{enumerable:!1,configurable:!1,writable:!1,value:s}),s}function Zt(s){var i=new P,c={isProviderFor:function(w,v){var k=i.get(w);return y(k)?!1:k.has(v)},OrdinaryDefineOwnMetadata:q,OrdinaryHasOwnMetadata:b,OrdinaryGetOwnMetadata:V,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:m};return g.registerProvider(c),c;function f(w,v,k){var O=i.get(w),M=!1;if(y(O)){if(!k)return;O=new A,i.set(w,O),M=!0}var H=O.get(v);if(y(H)){if(!k)return;if(H=new A,O.set(v,H),!s.setProvider(w,v,c))throw O.delete(v),M&&i.delete(w),new Error("Wrong provider for target.")}return H}function b(w,v,k){var O=f(v,k,!1);return y(O)?!1:ge(O.has(w))}function V(w,v,k){var O=f(v,k,!1);if(!y(O))return O.get(w)}function q(w,v,k,O){var M=f(k,O,!0);M.set(w,v)}function E(w,v){var k=[],O=f(w,v,!1);if(y(O))return k;for(var M=O.keys(),H=dt(M),oe=0;;){var ht=ft(H);if(!ht)return k.length=oe,k;var on=pt(ht);try{k[oe]=on}catch(sn){try{mt(H)}finally{throw sn}}oe++}}function m(w,v,k){var O=f(v,k,!1);if(y(O)||!O.delete(w))return!1;if(O.size===0){var M=i.get(v);y(M)||(M.delete(k),M.size===0&&i.delete(M))}return!0}}function en(s){var i=s.defineMetadata,c=s.hasOwnMetadata,f=s.getOwnMetadata,b=s.getOwnMetadataKeys,V=s.deleteMetadata,q=new P,E={isProviderFor:function(m,w){var v=q.get(m);return!y(v)&&v.has(w)?!0:b(m,w).length?(y(v)&&(v=new U,q.set(m,v)),v.add(w),!0):!1},OrdinaryDefineOwnMetadata:i,OrdinaryHasOwnMetadata:c,OrdinaryGetOwnMetadata:f,OrdinaryOwnMetadataKeys:b,OrdinaryDeleteMetadata:V};return E}function Ee(s,i,c){var f=g.getProvider(s,i);if(!y(f))return f;if(c){if(g.setProvider(s,i,F))return F;throw new Error("Illegal state.")}}function tn(){var s={},i=[],c=(function(){function E(m,w,v){this._index=0,this._keys=m,this._values=w,this._selector=v}return E.prototype["@@iterator"]=function(){return this},E.prototype[a]=function(){return this},E.prototype.next=function(){var m=this._index;if(m>=0&&m<this._keys.length){var w=this._selector(this._keys[m],this._values[m]);return m+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}},E.prototype.throw=function(m){throw this._index>=0&&(this._index=-1,this._keys=i,this._values=i),m},E.prototype.return=function(m){return this._index>=0&&(this._index=-1,this._keys=i,this._values=i),{value:m,done:!0}},E})(),f=(function(){function E(){this._keys=[],this._values=[],this._cacheKey=s,this._cacheIndex=-2}return Object.defineProperty(E.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),E.prototype.has=function(m){return this._find(m,!1)>=0},E.prototype.get=function(m){var w=this._find(m,!1);return w>=0?this._values[w]:void 0},E.prototype.set=function(m,w){var v=this._find(m,!0);return this._values[v]=w,this},E.prototype.delete=function(m){var w=this._find(m,!1);if(w>=0){for(var v=this._keys.length,k=w+1;k<v;k++)this._keys[k-1]=this._keys[k],this._values[k-1]=this._values[k];return this._keys.length--,this._values.length--,Ge(m,this._cacheKey)&&(this._cacheKey=s,this._cacheIndex=-2),!0}return!1},E.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=s,this._cacheIndex=-2},E.prototype.keys=function(){return new c(this._keys,this._values,b)},E.prototype.values=function(){return new c(this._keys,this._values,V)},E.prototype.entries=function(){return new c(this._keys,this._values,q)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[a]=function(){return this.entries()},E.prototype._find=function(m,w){if(!Ge(this._cacheKey,m)){this._cacheIndex=-1;for(var v=0;v<this._keys.length;v++)if(Ge(this._keys[v],m)){this._cacheIndex=v;break}}return this._cacheIndex<0&&w&&(this._cacheIndex=this._keys.length,this._keys.push(m),this._values.push(void 0)),this._cacheIndex},E})();return f;function b(E,m){return E}function V(E,m){return m}function q(E,m){return[E,m]}}function nn(){var s=(function(){function i(){this._map=new A}return Object.defineProperty(i.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),i.prototype.has=function(c){return this._map.has(c)},i.prototype.add=function(c){return this._map.set(c,c),this},i.prototype.delete=function(c){return this._map.delete(c)},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[a]=function(){return this.keys()},i})();return s}function rn(){var s=16,i=h.create(),c=f();return(function(){function m(){this._key=f()}return m.prototype.has=function(w){var v=b(w,!1);return v!==void 0?h.has(v,this._key):!1},m.prototype.get=function(w){var v=b(w,!1);return v!==void 0?h.get(v,this._key):void 0},m.prototype.set=function(w,v){var k=b(w,!0);return k[this._key]=v,this},m.prototype.delete=function(w){var v=b(w,!1);return v!==void 0?delete v[this._key]:!1},m.prototype.clear=function(){this._key=f()},m})();function f(){var m;do m="@@WeakMap@@"+E();while(h.has(i,m));return i[m]=!0,m}function b(m,w){if(!r.call(m,c)){if(!w)return;Object.defineProperty(m,c,{value:h.create()})}return m[c]}function V(m,w){for(var v=0;v<w;++v)m[v]=Math.random()*255|0;return m}function q(m){if(typeof Uint8Array=="function"){var w=new Uint8Array(m);return typeof crypto<"u"?crypto.getRandomValues(w):typeof msCrypto<"u"?msCrypto.getRandomValues(w):V(w,m),w}return V(new Array(m),m)}function E(){var m=q(s);m[6]=m[6]&79|64,m[8]=m[8]&191|128;for(var w="",v=0;v<s;++v){var k=m[v];(v===4||v===6||v===8)&&(w+="-"),k<16&&(w+="0"),w+=k.toString(16).toLowerCase()}return w}}function Je(s){return s.__=void 0,delete s.__,s}})})(yt||(yt={}))});S();var cs=ve(wt(),1),de=ve(require("process"),1);S();S();var wn=ve(require("os"),1),_n=ve(require("path"),1),vn=require("url"),kn=require("util");S();function We(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var re=class extends Error{},ie=class extends Error{},ze="urs1.";function hn(t,n){return ze+Buffer.from(JSON.stringify([t,n]),"utf8").toString("base64url")}function gn(t){if(!t.startsWith(ze))return null;try{let n=JSON.parse(Buffer.from(t.slice(ze.length),"base64url").toString("utf8"));if(Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string")return{app:n[0],key:n[1]}}catch{}return null}async function _t(t){let n=t.fetchImpl??fetch,e=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await n(e,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${e} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${e})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${e} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}var yn=6e4,Ce=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;seed(n,e){this.pool.set(n,Promise.resolve(e))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??yn;if(this.appsCache&&Date.now()-this.appsCache.at<n)return this.appsCache.apps;let e=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:e},e}servable(n){return n.filter(e=>e.function_name===this.opts.fnName&&e.deployment_status==="active").map(e=>e.app_slug)}async availableIds(){let n=this.opts.defaultApp,e=new Set(n===null?[]:[n]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))e.add(o);for(let o of this.pool.keys())e.add(o);let r=[...e].filter(o=>o!==n).sort();return n===null?r:[n,...r]}async noDefaultApp(n){let e=await this.availableIds(),r=e.length>0?e.join(", "):"(none deployed)";throw new re(n===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${r}`:`model "${n}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveApp(n){let e=(n??"").trim(),r=this.opts.defaultApp;if(!e||e==="urun")return r===null?this.noDefaultApp(e):r;let o=We(e);if(o===r)return r;if(this.pool.has(o))return o;if(this.opts.listApps){let u=await this.deployedApps(),a=this.servable(u);if(a.includes(o))return o;let l=a.filter(p=>p.startsWith(`${o}-`));if(l.length===1)return l[0];if(l.length>1)throw new re(`model "${e}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let d=u.find(p=>p.app_slug===o||p.app_slug.startsWith(`${o}-`));if(d)throw new re(`model "${e}" maps to app "${d.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${e}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let a=(await this.opts.listCatalog()).find(l=>e===l.model_id||e===`${l.model_id}:${l.variant}`||o===We(l.model_id)||o===We(`${l.model_id}-${l.variant}`));if(a)throw new re(`model "${e}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(e):r}async sessionFor(n){let e=await this.resolveApp(n),r=this.pool.get(e);return r||(r=Promise.resolve(this.opts.openSession(e)),this.pool.set(e,r),r.catch(()=>this.pool.delete(e))),{app:e,entry:await r}}keyOf(n){let e=this.opts.sessionKey;if(!e)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=e(n);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(n){let{app:e,entry:r}=await this.sessionFor(n);return{app:e,handle:hn(e,this.keyOf(r))}}async sessionForHandle(n){let e=gn(n);if(!e)throw new ie(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:r,key:o}=e,u=this.pool.get(r),a=u?await u.then(l=>l,()=>null):null;if(a===null)throw new ie(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(a)!==o)throw new ie(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:a}}async evict(n,e){let r=this.pool.get(n);!r||await r.then(u=>u,()=>null)!==e||this.pool.get(n)!==r||(this.pool.delete(n),await this.opts.closeSession(e).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(e=>({id:e,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let n=[...this.pool.values()];this.pool.clear();let e=[];if(await Promise.all(n.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){e.push(String(o instanceof Error?o.message:o))}})),e.length>0)throw new Error(`failed to close ${e.length} pooled session(s): ${e.join("; ")}`)}};function vt(t,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function Ue(t,n="URUN_GATEWAY_URL"){let e=new URL(t),r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!r)throw new Error(`${n} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var bn=8080,kt="serve",Ke="0.0.0.0";function xn(t,n,e){let r=(t[n]??"").trim();if(!r)throw new Error(`${n} is not set \u2014 ${e}`);return r}function bt(t=process.env){let n=(t.PORT??"").trim(),e=n===""?bn:Number(n);if(!Number.isInteger(e)||e<0||e>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(n)}`);let r=vt(Ue(xn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),u=o?Ue(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,a=(t.URUN_CATALOG_URL??"").trim(),l=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!l)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let d=a?{catalogUrl:Ue(a,"URUN_CATALOG_URL"),anonKey:l}:null;return{port:e,baseUrl:r,apiUrl:u,catalog:d}}S();var Wt=require("http");S();var $n=require("http");S();var Mn=require("crypto"),Nn=require("ws");S();S();var Ye=class{constructor(n,e){this.backend=n;this.opts=e}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let e=Buffer.from(n,"base64"),r=Math.floor(e.byteLength/2),o=new Int16Array(r);for(let u=0;u<r;u++)o[u]=e.readInt16LE(u*2);this.source.onData(o)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=e=>{let r=Buffer.from(e.samples.buffer,e.samples.byteOffset,e.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function Rt(t,n,e=1e4){let r=new Ye(n,{sampleRate:24e3}),o=await r.startOutbound();await t.stream("rt-audio-in").attach(o);let u=await Sn(t,e);return await r.startInbound(u),r}function Sn(t,n){let e=t.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((r,o)=>{let u,a=setTimeout(()=>{u?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),l=d=>{d!=null&&(clearTimeout(a),u?.(),r(d))};u=e.on?.("track",l),e.track!=null&&l(e.track)})}var xt="rt-video-in",St=256e3;function Et(t){let n=t.stream(xt),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${xt}') 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>St)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${St}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await e.call(n,r)}}}var Rn=24e3,Ae=480,En=111;async function An(){let t=await import("opusscript"),n=t.default??t;return new n(Rn,1,2048)}async function At(){let t=await import("werift"),n=await An();return{createSource:()=>{let e=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,u=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:e,onData:l=>{let d=new Int16Array(a.length+l.length);d.set(a,0),d.set(l,a.length);let p=0;for(;d.length-p>=Ae;){let h=d.subarray(p,p+Ae);p+=Ae;let x=Buffer.from(h.buffer,h.byteOffset,h.byteLength),A=n.encode(x,Ae);o=o+1&65535,u=u+Ae>>>0;let U=new t.RtpHeader({version:2,payloadType:En,sequenceNumber:o,timestamp:u,ssrc:r,marker:!1}),P=new t.RtpPacket(U,A);e.writeRtp(P)}a=d.slice(p)}}},createSink:e=>{let r={onframe:null};return e.onReceiveRtp.subscribe(u=>{let a;try{a=n.decode(u.payload)}catch{return}let l=new Int16Array(a.length/2);for(let d=0;d<l.length;d++)l[d]=a.readInt16LE(d*2);r.onframe?.({samples:l})}),r}}}S();var Me=require("@urun-sh/core"),Xe="rt-video-out";var On="h264";function In(t,n){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${n}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${n}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${n}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${n}: header key must be a boolean`)}function Tn(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let n=t[0]|t[1]<<8;if(t.byteLength<2+n)throw new Error(`decodeVideoOutRecord: truncated record (header says ${n} bytes, ${t.byteLength-2} present)`);let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(2,2+n)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let r=e;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;In(o,"decodeVideoOutRecord");let u=t.subarray(2+n);if(u.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:u.slice()}}function Ot(t){let n=t.stream(Xe);if(typeof n.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Xe}') 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 e=new Set,r=new Set,o=new Set,u=d=>{for(let p of r)p(d)},a=!1,l=async()=>{for await(let d of n.messages()){if(!(d instanceof Uint8Array)){u(new Error(`openSessionVideoOutLane: "${Xe}" delivered a non-BINARY \xA75 payload (${typeof d}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let p;try{p=Tn(d)}catch(h){u(h instanceof Error?h:new Error(String(h)));continue}for(let h of e)h(p)}for(let d of o)d()};return{codec:On,onOutputFrame:d=>(e.add(d),a||(a=!0,l().catch(p=>u(p instanceof Error?p:new Error(String(p))))),()=>e.delete(d)),onLaneError:d=>(r.add(d),()=>r.delete(d)),onEnd:d=>(o.add(d),()=>o.delete(d))}}var Cn=24e3,Gr=`audio/pcm;rate=${Cn}`,Un=Buffer.alloc(960).toString("base64");var et=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,r){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=r}modelEntry(n){let e=this.models[n];if(e)return e;let r=Object.keys(this.models).length>=Ln?"(other)":n;return this.models[r]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let r=this,o=performance.now(),u=null,a=0;return(async function*(){for await(let d of n)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(u===null&&(u=performance.now(),r.ttftMs.push(u-o),r.ttftMs.length>512&&r.ttftMs.shift()),a+=1,r.tokensOut+=1,r.charsOut+=d.delta.length,e!==void 0&&(r.modelEntry(e).tokens_out+=1)),yield d;let l=(performance.now()-(u??o))/1e3;a>0&&l>0&&(r.tokRates.push(a/l),r.tokRates.length>512&&r.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((r,o)=>r-o);return e[Math.floor(e.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((e,r)=>e+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}};function nt(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ue(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function le(t,n,e,r="invalid_request_error"){ue(t,n,{error:{message:e,type:r}})}function ae(t,n,e,r){ue(t,n,{type:"error",error:{type:e,message:r}})}function rt(t,n,e){if(n==="anthropic"){ue(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}ue(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var Ln=256,Dn=128;function ot(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Dn)}var It=64*1024*1024,Ne=class extends Error{};async function jn(t){let n=[],e=0;for await(let o of t){if(e+=o.length,e>It)throw new Ne(`request body exceeds ${It} bytes`);n.push(o)}let r=Buffer.concat(n).toString("utf8");return r?JSON.parse(r):{}}function ke(t,n,e,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:r}]}}var Vn=256;function Hn(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var tt=class{conversations=new Map;thread(n,e){let r=Hn(e);if(n==null)return r;let o=this.conversations.get(String(n));if(!o)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(n,e,r){this.conversations.set(n,[...e,{role:"assistant",content:r}]);for(let o of this.conversations.keys()){if(this.conversations.size<=Vn)break;this.conversations.delete(o)}}};function Oe(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function ye(t){return t.find(n=>n.type==="response.completed")?.response??null}function $e(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,r=e(n.input_tokens),o=e(n.output_tokens);if(r===0&&o===0)return null;let u=e(n.total_tokens)||r+o;return{input_tokens:r,output_tokens:o,total_tokens:u}}function Tt(t){let n=$e(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Ct(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let r of n)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(e+=String(o.text??""));return e}function Ie(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var we=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),r=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},Bn=["<tool_call>","<function="];function Fn(t){return Bn.find(n=>t.includes(n))}function be(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function xe(t,n,e){if(!(!t||n>0))return Fn(e)}function Gn(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var Le=class extends Error{};function qn(t,n){return Array.isArray(n)?n.map(e=>{let r=e;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Le(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function Jn(t){let n=[];for(let e of t){if(e.role==="tool"){n.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&n.push({role:"assistant",content:e.content});for(let r of e.tool_calls){let o=r.function??{};n.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}n.push({...e,content:qn(e.role,e.content)})}return n}function Qe(t){return Oe(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function Pt(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}async function Wn(t,n,e,r,o){let u=t.stream===!0,a;try{a=e.thread(t.previous_response_id,t.input)}catch(g){le(r,400,String(g instanceof Error?g.message:g));return}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(t.input)));let l=`resp_${Math.random().toString(36).slice(2,14)}`,d=t.store!==!1,p=ot(t);o.model(p);let h=Array.isArray(t.tools)&&t.tools.length>0,x;try{x=await n.createResponse({model:t.model,input:a,stream:u,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(g){if(g instanceof re){rt(r,"openai",g);return}throw g}let A=[];if(u){nt(r);let g=I=>{r.write(`event: ${String(I.type??"message")}
|
|
2
|
+
"use strict";var hn=Object.create;var yt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty;var vn=(t,n,e)=>()=>{if(e)throw e[0];try{return t&&(n=t(t=0)),n}catch(r){throw e=[r],r}};var kn=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var bn=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of yn(n))!_n.call(t,o)&&o!==e&&yt(t,o,{get:()=>n[o],enumerable:!(r=gn(n,o))||r.enumerable});return t};var ke=(t,n,e)=>(e=t!=null?hn(wn(t)):{},bn(n||!t||!t.__esModule?yt(e,"default",{value:t,enumerable:!0}):e,t));var S=vn(()=>{"use strict"});var _t=kn(()=>{"use strict";S();var wt;(function(t){(function(n){var e=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:l(),r=o(t);typeof e.Reflect<"u"&&(r=o(e.Reflect,r)),n(r,e),typeof e.Reflect>"u"&&(e.Reflect=t);function o(d,p){return function(h,x){Object.defineProperty(d,h,{configurable:!0,writable:!0,value:x}),p&&p(h,x)}}function u(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return u()||i()}})(function(n,e){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",u=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",d={__proto__:[]}instanceof Array,p=!l&&!d,h={create:l?function(){return We(Object.create(null))}:d?function(){return We({__proto__:null})}:function(){return We({})},has:p?function(s,a){return r.call(s,a)}:function(s,a){return a in s},get:p?function(s,a){return r.call(s,a)?s[a]:void 0}:function(s,a){return s[a]}},x=Object.getPrototypeOf(Function),A=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ln(),C=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:dn(),T=typeof WeakMap=="function"?WeakMap:pn(),P=o?Symbol.for("@reflect-metadata:registry"):void 0,g=an(),V=un(g);function G(s,a,c,f){if(y(c)){if(!ct(s))throw new TypeError;if(!lt(a))throw new TypeError;return z(s,a)}else{if(!ct(s))throw new TypeError;if(!R(a))throw new TypeError;if(!R(f)&&!y(f)&&!L(f))throw new TypeError;return L(f)&&(f=void 0),c=Z(c),N(s,a,c,f)}}n("decorate",G);function K(s,a){function c(f,b){if(!R(f))throw new TypeError;if(!y(b)&&!on(b))throw new TypeError;ce(s,a,f,b)}return c}n("metadata",K);function W(s,a,c,f){if(!R(c))throw new TypeError;return y(f)||(f=Z(f)),ce(s,a,c,f)}n("defineMetadata",W);function Y(s,a,c){if(!R(a))throw new TypeError;return y(c)||(c=Z(c)),H(s,a,c)}n("hasMetadata",Y);function _(s,a,c){if(!R(a))throw new TypeError;return y(c)||(c=Z(c)),Q(s,a,c)}n("hasOwnMetadata",_);function D(s,a,c){if(!R(a))throw new TypeError;return y(c)||(c=Z(c)),ne(s,a,c)}n("getMetadata",D);function ee(s,a,c){if(!R(a))throw new TypeError;return y(c)||(c=Z(c)),$(s,a,c)}n("getOwnMetadata",ee);function J(s,a){if(!R(s))throw new TypeError;return y(a)||(a=Z(a)),pe(s,a)}n("getMetadataKeys",J);function X(s,a){if(!R(s))throw new TypeError;return y(a)||(a=Z(a)),fe(s,a)}n("getOwnMetadataKeys",X);function te(s,a,c){if(!R(a))throw new TypeError;if(y(c)||(c=Z(c)),!R(a))throw new TypeError;y(c)||(c=Z(c));var f=Ae(a,c,!1);return y(f)?!1:f.OrdinaryDeleteMetadata(s,a,c)}n("deleteMetadata",te);function z(s,a){for(var c=s.length-1;c>=0;--c){var f=s[c],b=f(a);if(!y(b)&&!L(b)){if(!lt(b))throw new TypeError;a=b}}return a}function N(s,a,c,f){for(var b=s.length-1;b>=0;--b){var B=s[b],q=B(a,c,f);if(!y(q)&&!L(q)){if(!R(q))throw new TypeError;f=q}}return f}function H(s,a,c){var f=Q(s,a,c);if(f)return!0;var b=Je(a);return L(b)?!1:H(s,b,c)}function Q(s,a,c){var f=Ae(a,c,!1);return y(f)?!1:ge(f.OrdinaryHasOwnMetadata(s,a,c))}function ne(s,a,c){var f=Q(s,a,c);if(f)return $(s,a,c);var b=Je(a);if(!L(b))return ne(s,b,c)}function $(s,a,c){var f=Ae(a,c,!1);if(!y(f))return f.OrdinaryGetOwnMetadata(s,a,c)}function ce(s,a,c,f){var b=Ae(c,f,!0);b.OrdinaryDefineOwnMetadata(s,a,c,f)}function pe(s,a){var c=fe(s,a),f=Je(s);if(f===null)return c;var b=pe(f,a);if(b.length<=0)return c;if(c.length<=0)return b;for(var B=new C,q=[],E=0,m=c;E<m.length;E++){var w=m[E],v=B.has(w);v||(B.add(w),q.push(w))}for(var k=0,O=b;k<O.length;k++){var w=O[k],v=B.has(w);v||(B.add(w),q.push(w))}return q}function fe(s,a){var c=Ae(s,a,!1);return c?c.OrdinaryOwnMetadataKeys(s,a):[]}function I(s){if(s===null)return 1;switch(typeof s){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return s===null?1:6;default:return 6}}function y(s){return s===void 0}function L(s){return s===null}function U(s){return typeof s=="symbol"}function R(s){return typeof s=="object"?s!==null:typeof s=="function"}function ie(s,a){switch(I(s)){case 0:return s;case 1:return s;case 2:return s;case 3:return s;case 4:return s;case 5:return s}var c=a===3?"string":a===5?"number":"default",f=dt(s,u);if(f!==void 0){var b=f.call(s,c);if(R(b))throw new TypeError;return b}return he(s,c==="default"?"number":c)}function he(s,a){if(a==="string"){var c=s.toString;if(ve(c)){var f=c.call(s);if(!R(f))return f}var b=s.valueOf;if(ve(b)){var f=b.call(s);if(!R(f))return f}}else{var b=s.valueOf;if(ve(b)){var f=b.call(s);if(!R(f))return f}var B=s.toString;if(ve(B)){var f=B.call(s);if(!R(f))return f}}throw new TypeError}function ge(s){return!!s}function Ee(s){return""+s}function Z(s){var a=ie(s,3);return U(a)?a:Ee(a)}function ct(s){return Array.isArray?Array.isArray(s):s instanceof Object?s instanceof Array:Object.prototype.toString.call(s)==="[object Array]"}function ve(s){return typeof s=="function"}function lt(s){return typeof s=="function"}function on(s){switch(I(s)){case 3:return!0;case 4:return!0;default:return!1}}function qe(s,a){return s===a||s!==s&&a!==a}function dt(s,a){var c=s[a];if(c!=null){if(!ve(c))throw new TypeError;return c}}function pt(s){var a=dt(s,i);if(!ve(a))throw new TypeError;var c=a.call(s);if(!R(c))throw new TypeError;return c}function ft(s){return s.value}function mt(s){var a=s.next();return a.done?!1:a}function ht(s){var a=s.return;a&&a.call(s)}function Je(s){var a=Object.getPrototypeOf(s);if(typeof s!="function"||s===x||a!==x)return a;var c=s.prototype,f=c&&Object.getPrototypeOf(c);if(f==null||f===Object.prototype)return a;var b=f.constructor;return typeof b!="function"||b===s?a:b}function sn(){var s;!y(P)&&typeof e.Reflect<"u"&&!(P in e.Reflect)&&typeof e.Reflect.defineMetadata=="function"&&(s=cn(e.Reflect));var a,c,f,b=new T,B={registerProvider:q,getProvider:m,setProvider:v};return B;function q(k){if(!Object.isExtensible(B))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case s===k:break;case y(a):a=k;break;case a===k:break;case y(c):c=k;break;case c===k:break;default:f===void 0&&(f=new C),f.add(k);break}}function E(k,O){if(!y(a)){if(a.isProviderFor(k,O))return a;if(!y(c)){if(c.isProviderFor(k,O))return a;if(!y(f))for(var M=pt(f);;){var F=mt(M);if(!F)return;var oe=ft(F);if(oe.isProviderFor(k,O))return ht(M),oe}}}if(!y(s)&&s.isProviderFor(k,O))return s}function m(k,O){var M=b.get(k),F;return y(M)||(F=M.get(O)),y(F)&&(F=E(k,O),y(F)||(y(M)&&(M=new A,b.set(k,M)),M.set(O,F))),F}function w(k){if(y(k))throw new TypeError;return a===k||c===k||!y(f)&&f.has(k)}function v(k,O,M){if(!w(M))throw new Error("Metadata provider not registered.");var F=m(k,O);if(F!==M){if(!y(F))return!1;var oe=b.get(k);y(oe)&&(oe=new A,b.set(k,oe)),oe.set(O,M)}return!0}}function an(){var s;return!y(P)&&R(e.Reflect)&&Object.isExtensible(e.Reflect)&&(s=e.Reflect[P]),y(s)&&(s=sn()),!y(P)&&R(e.Reflect)&&Object.isExtensible(e.Reflect)&&Object.defineProperty(e.Reflect,P,{enumerable:!1,configurable:!1,writable:!1,value:s}),s}function un(s){var a=new T,c={isProviderFor:function(w,v){var k=a.get(w);return y(k)?!1:k.has(v)},OrdinaryDefineOwnMetadata:q,OrdinaryHasOwnMetadata:b,OrdinaryGetOwnMetadata:B,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:m};return g.registerProvider(c),c;function f(w,v,k){var O=a.get(w),M=!1;if(y(O)){if(!k)return;O=new A,a.set(w,O),M=!0}var F=O.get(v);if(y(F)){if(!k)return;if(F=new A,O.set(v,F),!s.setProvider(w,v,c))throw O.delete(v),M&&a.delete(w),new Error("Wrong provider for target.")}return F}function b(w,v,k){var O=f(v,k,!1);return y(O)?!1:ge(O.has(w))}function B(w,v,k){var O=f(v,k,!1);if(!y(O))return O.get(w)}function q(w,v,k,O){var M=f(k,O,!0);M.set(w,v)}function E(w,v){var k=[],O=f(w,v,!1);if(y(O))return k;for(var M=O.keys(),F=pt(M),oe=0;;){var gt=mt(F);if(!gt)return k.length=oe,k;var fn=ft(gt);try{k[oe]=fn}catch(mn){try{ht(F)}finally{throw mn}}oe++}}function m(w,v,k){var O=f(v,k,!1);if(y(O)||!O.delete(w))return!1;if(O.size===0){var M=a.get(v);y(M)||(M.delete(k),M.size===0&&a.delete(M))}return!0}}function cn(s){var a=s.defineMetadata,c=s.hasOwnMetadata,f=s.getOwnMetadata,b=s.getOwnMetadataKeys,B=s.deleteMetadata,q=new T,E={isProviderFor:function(m,w){var v=q.get(m);return!y(v)&&v.has(w)?!0:b(m,w).length?(y(v)&&(v=new C,q.set(m,v)),v.add(w),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:c,OrdinaryGetOwnMetadata:f,OrdinaryOwnMetadataKeys:b,OrdinaryDeleteMetadata:B};return E}function Ae(s,a,c){var f=g.getProvider(s,a);if(!y(f))return f;if(c){if(g.setProvider(s,a,V))return V;throw new Error("Illegal state.")}}function ln(){var s={},a=[],c=(function(){function E(m,w,v){this._index=0,this._keys=m,this._values=w,this._selector=v}return E.prototype["@@iterator"]=function(){return this},E.prototype[i]=function(){return this},E.prototype.next=function(){var m=this._index;if(m>=0&&m<this._keys.length){var w=this._selector(this._keys[m],this._values[m]);return m+1>=this._keys.length?(this._index=-1,this._keys=a,this._values=a):this._index++,{value:w,done:!1}}return{value:void 0,done:!0}},E.prototype.throw=function(m){throw this._index>=0&&(this._index=-1,this._keys=a,this._values=a),m},E.prototype.return=function(m){return this._index>=0&&(this._index=-1,this._keys=a,this._values=a),{value:m,done:!0}},E})(),f=(function(){function E(){this._keys=[],this._values=[],this._cacheKey=s,this._cacheIndex=-2}return Object.defineProperty(E.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),E.prototype.has=function(m){return this._find(m,!1)>=0},E.prototype.get=function(m){var w=this._find(m,!1);return w>=0?this._values[w]:void 0},E.prototype.set=function(m,w){var v=this._find(m,!0);return this._values[v]=w,this},E.prototype.delete=function(m){var w=this._find(m,!1);if(w>=0){for(var v=this._keys.length,k=w+1;k<v;k++)this._keys[k-1]=this._keys[k],this._values[k-1]=this._values[k];return this._keys.length--,this._values.length--,qe(m,this._cacheKey)&&(this._cacheKey=s,this._cacheIndex=-2),!0}return!1},E.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=s,this._cacheIndex=-2},E.prototype.keys=function(){return new c(this._keys,this._values,b)},E.prototype.values=function(){return new c(this._keys,this._values,B)},E.prototype.entries=function(){return new c(this._keys,this._values,q)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[i]=function(){return this.entries()},E.prototype._find=function(m,w){if(!qe(this._cacheKey,m)){this._cacheIndex=-1;for(var v=0;v<this._keys.length;v++)if(qe(this._keys[v],m)){this._cacheIndex=v;break}}return this._cacheIndex<0&&w&&(this._cacheIndex=this._keys.length,this._keys.push(m),this._values.push(void 0)),this._cacheIndex},E})();return f;function b(E,m){return E}function B(E,m){return m}function q(E,m){return[E,m]}}function dn(){var s=(function(){function a(){this._map=new A}return Object.defineProperty(a.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),a.prototype.has=function(c){return this._map.has(c)},a.prototype.add=function(c){return this._map.set(c,c),this},a.prototype.delete=function(c){return this._map.delete(c)},a.prototype.clear=function(){this._map.clear()},a.prototype.keys=function(){return this._map.keys()},a.prototype.values=function(){return this._map.keys()},a.prototype.entries=function(){return this._map.entries()},a.prototype["@@iterator"]=function(){return this.keys()},a.prototype[i]=function(){return this.keys()},a})();return s}function pn(){var s=16,a=h.create(),c=f();return(function(){function m(){this._key=f()}return m.prototype.has=function(w){var v=b(w,!1);return v!==void 0?h.has(v,this._key):!1},m.prototype.get=function(w){var v=b(w,!1);return v!==void 0?h.get(v,this._key):void 0},m.prototype.set=function(w,v){var k=b(w,!0);return k[this._key]=v,this},m.prototype.delete=function(w){var v=b(w,!1);return v!==void 0?delete v[this._key]:!1},m.prototype.clear=function(){this._key=f()},m})();function f(){var m;do m="@@WeakMap@@"+E();while(h.has(a,m));return a[m]=!0,m}function b(m,w){if(!r.call(m,c)){if(!w)return;Object.defineProperty(m,c,{value:h.create()})}return m[c]}function B(m,w){for(var v=0;v<w;++v)m[v]=Math.random()*255|0;return m}function q(m){if(typeof Uint8Array=="function"){var w=new Uint8Array(m);return typeof crypto<"u"?crypto.getRandomValues(w):typeof msCrypto<"u"?msCrypto.getRandomValues(w):B(w,m),w}return B(new Array(m),m)}function E(){var m=q(s);m[6]=m[6]&79|64,m[8]=m[8]&191|128;for(var w="",v=0;v<s;++v){var k=m[v];(v===4||v===6||v===8)&&(w+="-"),k<16&&(w+="0"),w+=k.toString(16).toLowerCase()}return w}}function We(s){return s.__=void 0,delete s.__,s}})})(wt||(wt={}))});S();var Rs=ke(_t(),1),de=ke(require("process"),1);S();S();var An=ke(require("os"),1),On=ke(require("path"),1),In=require("url"),Tn=require("util");S();S();function ye(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}S();var xn={chat:!0,code:!0,agent:!0,vl:!0},vt={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Sn(t){let n=t.toLowerCase();return Object.hasOwn(vt,n)?vt[n]:null}function ze(t){let n=t.engine_args?.context_length;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:null}function bt(t,n){let e=n.filter(u=>ye(`${u.model_id}-${u.variant}`)===t);if(e.length===1)return e[0];if(e.length>1)return kt(e);let r=n.filter(u=>ye(u.model_id)===t),o=new Set(r.map(u=>u.variant));return r.length>0&&o.size===1?kt(r):null}function kt(t){let n=t[0],e=i=>t.every(l=>(l[i]??void 0)===(n[i]??void 0))?n[i]:void 0,r=t.map(ze),o=r[0],u=o!=null&&r.every(i=>i===o)?o:null;return{model_id:n.model_id,variant:n.variant,gpu_spec:e("gpu_spec"),engine:e("engine"),task:e("task"),description:e("description"),size_gb:e("size_gb"),hf_repo:e("hf_repo"),engine_args:u!==null?{context_length:u}:{},updated_at:e("updated_at")}}function xt(t){let n=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(n)?Math.floor(n/1e3):0}function St(t,n){let e=bt(t,n);if(!e)return{id:t,object:"model",created:0,owned_by:"urun"};let r=ze(e);return{id:t,object:"model",created:xt(e),owned_by:"urun",name:`${e.model_id}:${e.variant}`,...e.description?{description:e.description}:{},...e.task?{task:e.task}:{},...e.engine?{engine:e.engine}:{},...e.gpu_spec?{gpu_spec:e.gpu_spec}:{},...r!==null?{context_length:r}:{}}}function Rt(t,n){let e=[];for(let r of t){let o=bt(r,n);if(!o||!o.task||xn[o.task]!==!0)continue;let u=ze(o),i={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};u!==null&&(i.max_tokens={type:"integer",min:1,max:u,unit:"token"}),e.push({schema_version:"2.4",id:r,name:`${o.model_id}:${o.variant}`,created:xt(o),quantization:Sn(o.variant),description:o.description??"",hugging_face_id:o.hf_repo?o.hf_repo.split("@")[0]??o.hf_repo:"",input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{}},...o.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:i}]})}return{data:e}}var re=class extends Error{},ae=class extends Error{},Ke="urs1.";function Rn(t,n){return Ke+Buffer.from(JSON.stringify([t,n]),"utf8").toString("base64url")}function En(t){if(!t.startsWith(Ke))return null;try{let n=JSON.parse(Buffer.from(t.slice(Ke.length),"base64url").toString("utf8"));if(Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string")return{app:n[0],key:n[1]}}catch{}return null}async function At(t){let n=t.fetchImpl??fetch,e=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await n(e,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${e} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${e})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${e} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}var Et=6e4,Ue=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;rowsCache=null;seed(n,e){this.pool.set(n,Promise.resolve(e))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??Et;if(this.appsCache&&Date.now()-this.appsCache.at<n)return this.appsCache.apps;let e=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:e},e}async catalogRows(){if(!this.opts.listCatalog)return[];let n=this.opts.appsTtlMs??Et;if(this.rowsCache&&Date.now()-this.rowsCache.at<n)return this.rowsCache.rows;let e=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:e},e}servable(n){return n.filter(e=>e.function_name===this.opts.fnName&&e.deployment_status==="active").map(e=>e.app_slug)}async availableIds(){let n=this.opts.defaultApp,e=new Set(n===null?[]:[n]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))e.add(o);for(let o of this.pool.keys())e.add(o);let r=[...e].filter(o=>o!==n).sort();return n===null?r:[n,...r]}async noDefaultApp(n){let e=await this.availableIds(),r=e.length>0?e.join(", "):"(none deployed)";throw new re(n===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${r}`:`model "${n}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveApp(n){let e=(n??"").trim(),r=this.opts.defaultApp;if(!e||e==="urun")return r===null?this.noDefaultApp(e):r;let o=ye(e);if(o===r)return r;if(this.pool.has(o))return o;if(this.opts.listApps){let u=await this.deployedApps(),i=this.servable(u);if(i.includes(o))return o;let l=i.filter(p=>p.startsWith(`${o}-`));if(l.length===1)return l[0];if(l.length>1)throw new re(`model "${e}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let d=u.find(p=>p.app_slug===o||p.app_slug.startsWith(`${o}-`));if(d)throw new re(`model "${e}" maps to app "${d.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${e}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(l=>e===l.model_id||e===`${l.model_id}:${l.variant}`||o===ye(l.model_id)||o===ye(`${l.model_id}-${l.variant}`));if(i)throw new re(`model "${e}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(e):r}async sessionFor(n){let e=await this.resolveApp(n),r=this.pool.get(e);return r||(r=Promise.resolve(this.opts.openSession(e)),this.pool.set(e,r),r.catch(()=>this.pool.delete(e))),{app:e,entry:await r}}keyOf(n){let e=this.opts.sessionKey;if(!e)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=e(n);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(n){let{app:e,entry:r}=await this.sessionFor(n);return{app:e,handle:Rn(e,this.keyOf(r))}}async sessionForHandle(n){let e=En(n);if(!e)throw new ae(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:r,key:o}=e,u=this.pool.get(r),i=u?await u.then(l=>l,()=>null):null;if(i===null)throw new ae(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new ae(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(n,e){let r=this.pool.get(n);!r||await r.then(u=>u,()=>null)!==e||this.pool.get(n)!==r||(this.pool.delete(n),await this.opts.closeSession(e).catch(()=>{}))}async modelList(){let n=await this.availableIds(),e=await this.catalogRows().catch(()=>[]);return{object:"list",data:n.map(r=>St(r,e))}}async openRouterModels(){let n=await this.availableIds(),e=await this.catalogRows();return Rt(n,e)}async closeAll(){let n=[...this.pool.values()];this.pool.clear();let e=[];if(await Promise.all(n.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){e.push(String(o instanceof Error?o.message:o))}})),e.length>0)throw new Error(`failed to close ${e.length} pooled session(s): ${e.join("; ")}`)}};function Ot(t,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function Me(t,n="URUN_GATEWAY_URL"){let e=new URL(t),r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!r)throw new Error(`${n} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Pn=8080,It="serve",Ye="0.0.0.0";function Cn(t,n,e){let r=(t[n]??"").trim();if(!r)throw new Error(`${n} is not set \u2014 ${e}`);return r}function Tt(t=process.env){let n=(t.PORT??"").trim(),e=n===""?Pn:Number(n);if(!Number.isInteger(e)||e<0||e>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(n)}`);let r=Ot(Me(Cn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),u=o?Me(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),l=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!l)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let d=i?{catalogUrl:Me(i,"URUN_CATALOG_URL"),anonKey:l}:null;return{port:e,baseUrl:r,apiUrl:u,catalog:d}}S();var tn=require("http");S();var qn=require("http");S();var Fn=require("crypto"),Gn=require("ws");S();S();var Xe=class{constructor(n,e){this.backend=n;this.opts=e}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let e=Buffer.from(n,"base64"),r=Math.floor(e.byteLength/2),o=new Int16Array(r);for(let u=0;u<r;u++)o[u]=e.readInt16LE(u*2);this.source.onData(o)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=e=>{let r=Buffer.from(e.samples.buffer,e.samples.byteOffset,e.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function Ut(t,n,e=1e4){let r=new Xe(n,{sampleRate:24e3}),o=await r.startOutbound();await t.stream("rt-audio-in").attach(o);let u=await Un(t,e);return await r.startInbound(u),r}function Un(t,n){let e=t.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((r,o)=>{let u,i=setTimeout(()=>{u?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),l=d=>{d!=null&&(clearTimeout(i),u?.(),r(d))};u=e.on?.("track",l),e.track!=null&&l(e.track)})}var Pt="rt-video-in",Ct=256e3;function Mt(t){let n=t.stream(Pt),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${Pt}') 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>Ct)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Ct}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await e.call(n,r)}}}var Mn=24e3,Oe=480,Nn=111;async function $n(){let t=await import("opusscript"),n=t.default??t;return new n(Mn,1,2048)}async function Nt(){let t=await import("werift"),n=await $n();return{createSource:()=>{let e=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,u=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:e,onData:l=>{let d=new Int16Array(i.length+l.length);d.set(i,0),d.set(l,i.length);let p=0;for(;d.length-p>=Oe;){let h=d.subarray(p,p+Oe);p+=Oe;let x=Buffer.from(h.buffer,h.byteOffset,h.byteLength),A=n.encode(x,Oe);o=o+1&65535,u=u+Oe>>>0;let C=new t.RtpHeader({version:2,payloadType:Nn,sequenceNumber:o,timestamp:u,ssrc:r,marker:!1}),T=new t.RtpPacket(C,A);e.writeRtp(T)}i=d.slice(p)}}},createSink:e=>{let r={onframe:null};return e.onReceiveRtp.subscribe(u=>{let i;try{i=n.decode(u.payload)}catch{return}let l=new Int16Array(i.length/2);for(let d=0;d<l.length;d++)l[d]=i.readInt16LE(d*2);r.onframe?.({samples:l})}),r}}}S();var Ne=require("@urun-sh/core"),Qe="rt-video-out";var Ln="h264";function Dn(t,n){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${n}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${n}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${n}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${n}: header key must be a boolean`)}function jn(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let n=t[0]|t[1]<<8;if(t.byteLength<2+n)throw new Error(`decodeVideoOutRecord: truncated record (header says ${n} bytes, ${t.byteLength-2} present)`);let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(2,2+n)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=e;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;Dn(o,"decodeVideoOutRecord");let u=t.subarray(2+n);if(u.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:u.slice()}}function $t(t){let n=t.stream(Qe);if(typeof n.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Qe}') 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 e=new Set,r=new Set,o=new Set,u=d=>{for(let p of r)p(d)},i=!1,l=async()=>{for await(let d of n.messages()){if(!(d instanceof Uint8Array)){u(new Error(`openSessionVideoOutLane: "${Qe}" delivered a non-BINARY \xA75 payload (${typeof d}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let p;try{p=jn(d)}catch(h){u(h instanceof Error?h:new Error(String(h)));continue}for(let h of e)h(p)}for(let d of o)d()};return{codec:Ln,onOutputFrame:d=>(e.add(d),i||(i=!0,l().catch(p=>u(p instanceof Error?p:new Error(String(p))))),()=>e.delete(d)),onLaneError:d=>(r.add(d),()=>r.delete(d)),onEnd:d=>(o.add(d),()=>o.delete(d))}}var Hn=24e3,io=`audio/pcm;rate=${Hn}`,Bn=Buffer.alloc(960).toString("base64");var tt=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,r){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=r}modelEntry(n){let e=this.models[n];if(e)return e;let r=Object.keys(this.models).length>=Jn?"(other)":n;return this.models[r]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let r=this,o=performance.now(),u=null,i=0;return(async function*(){for await(let d of n)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(u===null&&(u=performance.now(),r.ttftMs.push(u-o),r.ttftMs.length>512&&r.ttftMs.shift()),i+=1,r.tokensOut+=1,r.charsOut+=d.delta.length,e!==void 0&&(r.modelEntry(e).tokens_out+=1)),yield d;let l=(performance.now()-(u??o))/1e3;i>0&&l>0&&(r.tokRates.push(i/l),r.tokRates.length>512&&r.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((r,o)=>r-o);return e[Math.floor(e.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((e,r)=>e+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}};function rt(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function se(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function le(t,n,e,r="invalid_request_error"){se(t,n,{error:{message:e,type:r}})}function ue(t,n,e,r){se(t,n,{type:"error",error:{type:e,message:r}})}function ot(t,n,e){if(n==="anthropic"){se(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}se(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var Jn=256,Wn=128;function st(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Wn)}var Lt=64*1024*1024,$e=class extends Error{};async function zn(t){let n=[],e=0;for await(let o of t){if(e+=o.length,e>Lt)throw new $e(`request body exceeds ${Lt} bytes`);n.push(o)}let r=Buffer.concat(n).toString("utf8");return r?JSON.parse(r):{}}function be(t,n,e,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:r}]}}var Kn=256;function Yn(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var nt=class{conversations=new Map;thread(n,e){let r=Yn(e);if(n==null)return r;let o=this.conversations.get(String(n));if(!o)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(n,e,r){this.conversations.set(n,[...e,{role:"assistant",content:r}]);for(let o of this.conversations.keys()){if(this.conversations.size<=Kn)break;this.conversations.delete(o)}}};function Ie(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function we(t){return t.find(n=>n.type==="response.completed")?.response??null}function Le(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,r=e(n.input_tokens),o=e(n.output_tokens);if(r===0&&o===0)return null;let u=e(n.total_tokens)||r+o;return{input_tokens:r,output_tokens:o,total_tokens:u}}function Dt(t){let n=Le(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Vt(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let r of n)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(e+=String(o.text??""));return e}function Te(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var _e=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),r=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},Xn=["<tool_call>","<function="];function Qn(t){return Xn.find(n=>t.includes(n))}function xe(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Se(t,n,e){if(!(!t||n>0))return Qn(e)}function Zn(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var De=class extends Error{};function er(t,n){return Array.isArray(n)?n.map(e=>{let r=e;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new De(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function tr(t){let n=[];for(let e of t){if(e.role==="tool"){n.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&n.push({role:"assistant",content:e.content});for(let r of e.tool_calls){let o=r.function??{};n.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}n.push({...e,content:er(e.role,e.content)})}return n}function Ze(t){return Ie(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function jt(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}async function nr(t,n,e,r,o){let u=t.stream===!0,i;try{i=e.thread(t.previous_response_id,t.input)}catch(g){le(r,400,String(g instanceof Error?g.message:g));return}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(t.input)));let l=`resp_${Math.random().toString(36).slice(2,14)}`,d=t.store!==!1,p=st(t);o.model(p);let h=Array.isArray(t.tools)&&t.tools.length>0,x;try{x=await n.createResponse({model:t.model,input:i,stream:u,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(g){if(g instanceof re){ot(r,"openai",g);return}throw g}let A=[];if(u){rt(r);let g=I=>{r.write(`event: ${String(I.type??"message")}
|
|
3
3
|
data: ${JSON.stringify(I)}
|
|
4
4
|
|
|
5
|
-
`)},
|
|
5
|
+
`)},V=I=>I.response&&typeof I.response=="object"?{...I,response:{...I.response,id:l}}:I,G=`item_${l.slice(5)}`,K=`rs_${l.slice(5)}`,W=!1,Y=!1,_=0,D=()=>{W||(W=!0,g({type:"response.created",response:{id:l,object:"response",status:"in_progress"}}))},ee=!1,J=0,X="",te=()=>{ee&&(ee=!1,g({type:"response.reasoning_text.done",item_id:K,output_index:J,content_index:0,text:X}),g({type:"response.output_item.done",output_index:J,item:{id:K,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:X}],status:"completed"}}))},z=!1,N=0,H="",Q=I=>{z&&(z=!1,g({type:"response.output_text.done",item_id:G,output_index:N,content_index:0,text:H}),g({type:"response.content_part.done",item_id:G,output_index:N,content_index:0,part:{type:"output_text",text:H}}),g({type:"response.output_item.done",output_index:N,item:{id:G,type:"message",role:"assistant",status:I,content:[{type:"output_text",text:H}]}}))},ne=new _e,$=null,ce=-1,pe=I=>{if(!$)return;let y=$;$=null,g({type:"response.function_call_arguments.done",item_id:y.fcId,output_index:y.outputIndex,arguments:y.args}),g({type:"response.output_item.done",output_index:y.outputIndex,item:{id:y.fcId,type:"function_call",call_id:y.callId??y.fcId,name:y.name??"",arguments:y.args,status:I}})},fe=!1;for await(let I of o.track(x,p)){A.push(I);let y=String(I.type??"");if(y==="response.created"||y==="response.in_progress"){W=!0,g(V(I));continue}if(y==="response.output_item.added"){Y=!0,g(V(I));continue}if(y==="response.reasoning_text.delta"&&!Y){D(),ee||(ee=!0,J=_++,g({type:"response.output_item.added",output_index:J,item:{id:K,type:"reasoning",summary:[],content:[],status:"in_progress"}})),X+=String(I.delta??""),g({type:"response.reasoning_text.delta",item_id:K,output_index:J,content_index:0,delta:I.delta});continue}if(y==="response.output_text.delta"&&!Y){D(),te(),z||(z=!0,N=_++,g({type:"response.output_item.added",output_index:N,item:{id:G,type:"message",role:"assistant",status:"in_progress",content:[]}}),g({type:"response.content_part.added",item_id:G,output_index:N,content_index:0,part:{type:"output_text",text:""}})),H+=String(I.delta??""),g({type:y,item_id:G,output_index:N,content_index:0,delta:I.delta});continue}let L=Y?null:Te(I);if(L){if(D(),te(),Q("completed"),ne.add(L),L.tool_index!==ce){pe("completed"),ce=L.tool_index;let U=_++;$={fcId:`fc_${l.slice(5)}_${L.tool_index}`,outputIndex:U,callId:L.call_id,name:L.name,args:""},g({type:"response.output_item.added",output_index:U,item:{id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:"",status:"in_progress"}})}$&&(L.call_id&&($.callId=L.call_id),L.name&&($.name=L.name),$.args+=L.delta,g({type:"response.function_call_arguments.delta",item_id:$.fcId,output_index:$.outputIndex,delta:L.delta}));continue}if(y==="response.completed"&&!Y){let U=Ie(I.response),R=Se(h,ne.size+U.length,H);if(R){fe=!0,g({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:xe(p,R)}});break}te(),Q("completed"),pe("completed"),ne.size===0&&U.forEach(ie=>{let he=_++,ge=ie.id??ie.call_id??`fc_${he}`,Ee=ie.arguments??"",Z={id:ge,type:"function_call",call_id:ie.call_id??ge,name:ie.name??""};g({type:"response.output_item.added",output_index:he,item:{...Z,arguments:"",status:"in_progress"}}),g({type:"response.function_call_arguments.delta",item_id:ge,output_index:he,delta:Ee}),g({type:"response.function_call_arguments.done",item_id:ge,output_index:he,arguments:Ee}),g({type:"response.output_item.done",output_index:he,item:{...Z,arguments:Ee,status:"completed"}})}),g(V(I));continue}g(V(I))}te(),Q("incomplete"),pe("incomplete"),d&&!fe&&e.remember(l,i,jt(A,we(A))),r.write(`data: [DONE]
|
|
6
6
|
|
|
7
|
-
`),r.end();return}let
|
|
7
|
+
`),r.end();return}let C=null;for await(let g of o.track(x,p)){if(A.push(g),g.type==="error"){le(r,502,JSON.stringify(g),"upstream_error");return}g.type==="response.completed"&&(C=g.response)}if(C==null){le(r,502,"upstream produced no response.completed event","upstream_error");return}let T=jt(A,C),P=Se(h,Ie(C).length,T);if(P){le(r,502,xe(p,P),"upstream_error");return}d&&e.remember(l,i,T),se(r,200,{...C,id:l})}async function rr(t,n,e,r){let o=t.messages;if(!Array.isArray(o)){le(e,400,"chat/completions requires a messages array");return}let u=String(t.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,l;try{l=tr(o)}catch(_){if(_ instanceof De){le(e,400,_.message);return}throw _}let d=st(t);r.model(d);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await n.createResponse({model:t.model,input:l,stream:!0,tools:Zn(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(_){if(_ instanceof re){ot(e,"openai",_);return}throw _}if(t.stream===!0){rt(e);let _=[],D=new _e,ee="";e.write(`data: ${JSON.stringify(be(i,u,{role:"assistant"},null))}
|
|
8
8
|
|
|
9
|
-
`);for await(let N of r.track(h,d)){_.push(N);let
|
|
9
|
+
`);for await(let N of r.track(h,d)){_.push(N);let H=Te(N);if(N.type==="response.output_text.delta"&&typeof N.delta=="string")ee+=N.delta,e.write(`data: ${JSON.stringify(be(i,u,{content:N.delta},null))}
|
|
10
10
|
|
|
11
|
-
`);else if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")e.write(`data: ${JSON.stringify(
|
|
11
|
+
`);else if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")e.write(`data: ${JSON.stringify(be(i,u,{reasoning_content:N.delta},null))}
|
|
12
12
|
|
|
13
|
-
`);else if(
|
|
13
|
+
`);else if(H){let{call:Q,isNew:ne}=D.add(H),$=ne?{index:H.tool_index,id:Q.id??`call_${H.tool_index}`,type:"function",function:{name:Q.name??"",arguments:H.delta}}:{index:H.tool_index,function:{arguments:H.delta}};e.write(`data: ${JSON.stringify(be(i,u,{tool_calls:[$]},null))}
|
|
14
14
|
|
|
15
15
|
`)}else if(N.type==="error"){e.write(`data: ${JSON.stringify({error:N})}
|
|
16
16
|
|
|
17
|
-
`),e.end();return}}let J=
|
|
17
|
+
`),e.end();return}}let J=Ze(we(_)),X=Se(p,D.size+J.length,ee);if(X){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:xe(d,X)}})}
|
|
18
18
|
|
|
19
|
-
`),e.end();return}D.size===0&&J.length>0&&e.write(`data: ${JSON.stringify(
|
|
19
|
+
`),e.end();return}D.size===0&&J.length>0&&e.write(`data: ${JSON.stringify(be(i,u,{tool_calls:J},null))}
|
|
20
20
|
|
|
21
|
-
`);let te=D.size>0||J.length>0;e.write(`data: ${JSON.stringify(
|
|
21
|
+
`);let te=D.size>0||J.length>0;e.write(`data: ${JSON.stringify(be(i,u,{},te?"tool_calls":"stop"))}
|
|
22
22
|
|
|
23
|
-
`)
|
|
23
|
+
`),Le(we(_))&&e.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Dt(we(_))})}
|
|
24
24
|
|
|
25
25
|
`),e.write(`data: [DONE]
|
|
26
26
|
|
|
27
|
-
`),e.end();return}let x="",A="",
|
|
27
|
+
`),e.end();return}let x="",A="",C=[],T=new _e;for await(let _ of r.track(h,d)){C.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(x+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(A+=_.delta);let D=Te(_);if(D&&T.add(D),_.type==="error"){le(e,502,JSON.stringify(_),"upstream_error");return}}let P=we(C),g=Ze(P),V=g.length>0?g:Ze({output:T.items()}),G=Se(p,V.length,x);if(G){le(e,502,xe(d,G),"upstream_error");return}let K=V.map(({index:_,...D})=>D),W={role:"assistant",content:x||null},Y=A||Vt(P);Y&&(W.reasoning_content=Y),K.length>0&&(W.tool_calls=K),se(e,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:W,finish_reason:K.length>0?"tool_calls":"stop"}],usage:Dt(P)})}function or(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var Pe=class extends Error{};function je(t){return new Pe(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function sr(t){if(Array.isArray(t))return t.map(n=>{let e=n;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema}})}function ir(t){if(t==null)return;let n=t.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:t.name};throw new Pe(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function ar(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw je(typeof t);let n="";for(let e of t){let r=String(e.type??"");if(r!=="text")throw je(`tool_result > ${r}`);n+=String(e.text??"")}return n}function ur(t){let{role:n,content:e}=t;if(typeof e=="string")return[{role:n,content:e}];if(e==null)return[];if(!Array.isArray(e))throw je(typeof e);let r=[],o="",u=()=>{o&&(r.push({role:n,content:o}),o="")};for(let i of e){let l=String(i.type??"");if(l==="text")o+=String(i.text??"");else if(l==="tool_use")u(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(l==="tool_result")u(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:ar(i.content)});else{if(l==="thinking"||l==="redacted_thinking")continue;throw je(l)}}return u(),r}function et(t){return Ie(t).map((n,e)=>{let r;try{r=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${e}`,name:n.name??"",input:r}})}async function cr(t,n,e,r){let o=t.messages;if(!Array.isArray(o)){ue(e,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){ue(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ue(e,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(_=>typeof _!="string"))){ue(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,l=[],d;try{t.system&&l.push({role:"system",content:or(t.system)});for(let _ of o)l.push(...ur(_));d=ir(t.tool_choice)}catch(_){if(_ instanceof Pe){ue(e,400,"invalid_request_error",_.message);return}throw _}let p=st(t);r.model(p);let h=Array.isArray(t.tools)&&t.tools.length>0,x;try{x=await n.createResponse({model:t.model,input:l,stream:!0,tools:sr(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences})}catch(_){if(_ instanceof re){ot(e,"anthropic",_);return}throw _}let A=(_,D)=>{e.destroyed||e.write(`event: ${_}
|
|
28
28
|
data: ${JSON.stringify({type:_,...D})}
|
|
29
29
|
|
|
30
|
-
`)};if(t.stream===!0){let _=r.track(x,p);
|
|
31
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
30
|
+
`)};if(t.stream===!0){let _=r.track(x,p);rt(e),A("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let D=0,ee="",J=0,X="none",te=()=>X,z=-1,N=-1,H=new _e,Q=[],ne=()=>{X!=="none"&&(X="none",A("content_block_stop",{index:z}))},$=(U,R)=>{ne(),X=U,z=J++,A("content_block_start",{index:z,content_block:R})};for await(let U of _){if(e.destroyed)break;Q.push(U);let R=Te(U);if(U.type==="response.reasoning_text.delta"&&typeof U.delta=="string")te()!=="thinking"&&$("thinking",{type:"thinking",thinking:""}),A("content_block_delta",{index:z,delta:{type:"thinking_delta",thinking:U.delta}});else if(U.type==="response.output_text.delta"&&typeof U.delta=="string")te()!=="text"&&$("text",{type:"text",text:""}),D+=1,ee+=U.delta,A("content_block_delta",{index:z,delta:{type:"text_delta",text:U.delta}});else if(R){let{call:ie}=H.add(R);(te()!=="tool"||R.tool_index!==N)&&(N=R.tool_index,$("tool",{type:"tool_use",id:ie.id??`call_${R.tool_index}`,name:ie.name??"",input:{}})),R.delta&&A("content_block_delta",{index:z,delta:{type:"input_json_delta",partial_json:R.delta}})}else if(U.type==="error"){A("error",{error:{type:"api_error",message:JSON.stringify(U)}}),e.end();return}}if(e.destroyed)return;let ce=we(Q),pe=Ie(ce),fe=Se(h,H.size+pe.length,ee);if(fe){A("error",{error:{type:"api_error",message:xe(p,fe)}}),e.end();return}ne();let I=[];if(H.size===0)try{I=et(ce)}catch(U){A("error",{error:{type:"api_error",message:String(U instanceof Error?U.message:U)}}),e.end();return}J===0&&I.length===0&&($("text",{type:"text",text:""}),ne()),I.forEach(U=>{let R=J++;A("content_block_start",{index:R,content_block:{...U,input:{}}}),A("content_block_delta",{index:R,delta:{type:"input_json_delta",partial_json:JSON.stringify(U.input??{})}}),A("content_block_stop",{index:R})});let y=H.size>0||I.length>0,L=Le(ce);A("message_delta",{delta:{stop_reason:y?"tool_use":"end_turn"},usage:L?{input_tokens:L.input_tokens,output_tokens:L.output_tokens}:{output_tokens:D}}),A("message_stop",{}),e.end();return}let C="",T="",P=[],g=new _e;for await(let _ of r.track(x,p)){P.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(C+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(T+=_.delta);let D=Te(_);if(D&&g.add(D),_.type==="error"){ue(e,502,"api_error",JSON.stringify(_));return}if(e.destroyed)break}if(e.destroyed)return;let V=we(P),G;try{G=et(V),G.length===0&&g.size>0&&(G=et({output:g.items()}))}catch(_){ue(e,502,"api_error",String(_ instanceof Error?_.message:_));return}let K=Se(h,G.length,C);if(K){ue(e,502,"api_error",xe(p,K));return}let W=[],Y=T||Vt(V);Y&&W.push({type:"thinking",thinking:Y}),(C||G.length===0)&&W.push({type:"text",text:C}),W.push(...G),se(e,200,{id:i,type:"message",role:"assistant",content:W,model:u,stop_reason:G.length>0?"tool_use":"end_turn",usage:Le(V)??{input_tokens:0,output_tokens:0}})}function Ht(t){let{clients:n,apiKey:e,identity:r,statusOf:o}=t,u=typeof n=="function"?n:()=>n,i=new WeakMap,l=p=>{let h=i.get(p);return h||(h=new nt,i.set(p,h)),h},d=new tt;return(p,h)=>{let x=new URL(p.url??"/","http://localhost"),A=x.pathname==="/v1/messages"||x.pathname.startsWith("/v1/messages/"),C=(T,P,g,V)=>A?ue(h,T,V,P):le(h,T,P,g);(async()=>{if(p.method==="GET"&&x.pathname==="/healthz"){se(h,200,{ok:!0});return}if(p.method==="GET"&&x.pathname==="/stats"){se(h,200,r?{identity:r,...d.snapshot()}:d.snapshot());return}if(e&&(p.headers.authorization??"")!==`Bearer ${e}`){C(401,"invalid local proxy api key","authentication_error","authentication_error");return}let T=await u(p);if(p.method==="GET"&&x.pathname==="/v1/models"){if(x.searchParams.get("format")==="openrouter"){if(!T.openRouterModels){C(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}se(h,200,await T.openRouterModels());return}se(h,200,await T.listModels());return}if(p.method!=="POST"){C(404,`no route for ${p.method} ${x.pathname}`,"invalid_request_error","not_found_error");return}let P;try{P=await zn(p)}catch(V){if(V instanceof $e){C(413,V.message,"request_too_large","request_too_large");return}C(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=Buffer.byteLength(JSON.stringify(P));if(x.pathname==="/v1/responses"){d.request("responses",g,g),await nr(P,T,l(T),h,d);return}if(x.pathname==="/v1/chat/completions"){d.request("chat_completions",g,g),await rr(P,T,h,d);return}if(x.pathname==="/v1/messages"){d.request("messages",g,g),await cr(P,T,h,d);return}if(x.pathname==="/v1/messages/count_tokens"){d.request("count_tokens",g,g),ue(h,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}C(404,`no route for POST ${x.pathname}`,"invalid_request_error","not_found_error")})().catch(T=>{let P=String(T instanceof Error?T.message:T);if(!h.headersSent){let g=o?.(T)??null;if(g){C(g.status,P,g.openaiType,g.anthropicType);return}C(500,P,"proxy_error","api_error");return}h.destroyed||(A?h.write(`event: error
|
|
31
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:P}})}
|
|
32
32
|
|
|
33
|
-
`):h.write(`data: ${JSON.stringify({error:{message:
|
|
33
|
+
`):h.write(`data: ${JSON.stringify({error:{message:P,type:"upstream_error"}})}
|
|
34
34
|
|
|
35
|
-
`)),h.end()})}}S();var Ve=require("@urun-sh/core"),me=class extends Error{constructor(e,r=401){super(e);this.status=r;this.name="ProxyAuthError"}status},Se=class extends Error{constructor(n){super(n),this.name="ControlPlaneUnavailableError"}};function Mt(t){let n=(t??"").trim();if(n==="")throw new me("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let e=/^Bearer[ \t]+(\S.*)$/i.exec(n);if(!e)throw new me("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return e[1].trim()}var tr=60,nr=6e4,rr=4096;function or(t){return t===401||t===403}var je=class{constructor(n){this.opts=n;this.mint=n.mint??Ve.createClientToken,this.now=n.now??Date.now}opts;cache=new Map;mint;now;async resolve(n){if(n==="")throw new me("empty Authorization bearer token");let e=this.cache.get(n);if(e&&this.now()-e.at<nr)return{apiKey:n,orgId:e.orgId};let r;try{r=(await this.mint(n,{baseUrl:this.opts.gatewayUrl,expiresIn:tr})).orgId}catch(o){throw o instanceof Ve.ClientTokenError&&or(o.status)?(this.cache.delete(n),new me("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Se(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Se("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=rr){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(n,{orgId:r,at:this.now()}),{apiKey:n,orgId:r}}clear(){this.cache.clear()}};S();var qt=require("crypto");S();var Pe=require("@urun-sh/core");S();async function Nt(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}S();S();S();function $t(t,n,e,r){let o=t.response??{},u={request_id:e,consumer_id:r,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(u.instructions=o.instructions),Array.isArray(o.modalities)&&(u.modalities=o.modalities),typeof o.temperature=="number"&&(u.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(u.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(u.tools=o.tools),u}function Lt(t,n,e){let r={request_id:n,consumer_id:e,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),r}S();S();function Dt(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let n=t,e=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:e.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var sr="llm-resp";async function*st(t,n){let e=`${sr}:${n}`,r=`resp_${n}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;for await(let u of t.stream(e).messages()){let a=u;if(a.t==="delta"){if(typeof a.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:a.delta}),typeof a.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:a.reasoning}),Array.isArray(a.tool_calls))for(let l of a.tool_calls){let d=typeof l.index=="number"?l.index:0,p=o.get(d)??{};l.id&&(p.id=l.id),l.function?.name&&(p.name=l.function.name),o.set(d,p),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${d}`,tool_index:d,call_id:p.id,name:p.name,delta:l.function?.arguments??""}}}else if(a.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...a.body}};return}else if(a.t==="error"){yield Dt(a);return}}}var ir="llm",He=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(ir).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,e){let r=Lt(n,e,this.consumerId);return this.write(r),st(this.session,e)}sendResponseCreate(n,e,r){let o=$t(n,e,r,this.consumerId);return this.write(o),st(this.session,r)}};var jt=0;function ar(){return jt+=1,`req_${Date.now().toString(36)}_${jt.toString(36)}`}var Be=class{transport;constructor(n){this.transport=new He(n)}responses={create:async n=>{let e=ar(),r=this.transport.sendResponses(n,e);return Object.assign((async function*(){yield*r})(),{requestId:e})}}};S();function ur(t){let n=t?.type;return n==="response.created"||n==="response.in_progress"}function cr(t){let n=t?.type;return n==="response.completed"||n==="error"}function Vt(t){return async function(e){return(async function*(){for(let o=1;o<=2;o++){let{app:u,entry:a}=await t.sessionFor(e.model),l=!1,d=!1;try{let p=await t.createStream(a,e);for await(let h of p){if(cr(h)&&(l=!0),ur(h)){if(o>1)continue}else d=!0;yield h}}catch(p){if(o<2&&!d){await t.evict(u,a);continue}throw p}if(l)return;if(o<2&&!d){await t.evict(u,a);continue}return}})()}}S();var lr=3,dr="llm",pr=new Set(["paused","error"]);function Ht(t,n){let e=t.doc(dr),r=typeof e.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let u=null,a=new Set,l=[],d=p=>{if(!u){u=p;for(let h of[...a])h(p);a.clear()}};return r&&l.push(e.onConnectionState(p=>{p.consecutiveFailures<lr||d(new ie(`the pooled session for app "${n}" is gone: its doc backhaul failed ${p.consecutiveFailures} consecutive times (last close ${p.lastCloseCode===null?"by provider liveness reap":`code ${p.lastCloseCode}`}${p.lastCloseReason?`, reason ${JSON.stringify(p.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),o&&l.push(t.onPhase(p=>{pr.has(p.name)&&d(new ie(`the pooled session for app "${n}" lost its compute binding (phase "${p.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>u,onGone(p){return u?(p(u),()=>{}):(a.add(p),()=>a.delete(p))},dispose(){a.clear();for(let p of l.splice(0))p()}}}async function*it(t,n){let e=n.gone();if(e)throw e;let r=t[Symbol.asyncIterator](),o,u=new Promise((a,l)=>{o=n.onGone(d=>l(d))});u.catch(()=>{});try{for(;;){let a=await Promise.race([r.next(),u]);if(a.done)return;yield a.value}}finally{o?.(),r.return?.(void 0)}}function Bt(t,n,e){let r=t[e];if(typeof r!="function")throw new Error(`app "${n}" has no function "${e}" (set URUN_FUNCTION)`);let o=r();if(typeof o.end!="function")throw new Error(`app "${n}" function "${e}" returned a session without end()`);return o}function fr(t,n){let{baseUrl:e,orgId:r,fnName:o,auth:u,subject:a}=t,l=x=>({session:x,responses:new Be(x),gone:Ht(x,n)});if(u.lane==="jwt"){let x=(0,Pe.App)(n,{baseUrl:e,orgId:r,jwt:u.jwt});return l(Bt(x,n,o))}let{apiKey:d,gatewayUrl:p}=u,h=(0,Pe.App)(n,{baseUrl:e,orgId:r,getAccessToken:async()=>(await(0,Pe.createClientToken)(d,{baseUrl:p,expiresIn:300,allowedFunctions:[`${n}/${o}`],...a===void 0?{}:{subject:a}})).token});return l(Bt(h,n,o))}function mr(t){let n=t.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var hr=new Set(["error","paused"]);function Ft(t){let{auth:n,catalog:e}=t,r=null,o=a=>{let l=fr(t,a);return l.gone.onGone(()=>{r?.evict(a,l)}),l},u=new Ce({defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async a=>{a.gone.dispose(),await a.session.end()},listApps:n.lane==="api-key"?()=>_t({apiUrl:t.apiUrl,apiKey:n.apiKey}):null,listCatalog:e?()=>Nt(e):null,sessionKey:mr});return r=u,t.defaultApp!==null&&u.seed(t.defaultApp,o(t.defaultApp)),u}function Gt(t,n=At){let e=new WeakMap,r=new WeakMap,o=new WeakMap;return{createResponse:Vt({sessionFor:u=>t.sessionFor(u),evict:(u,a)=>t.evict(u,a),createStream:async(u,a)=>it(await u.responses.responses.create(a),u.gone)}),listModels:()=>t.modelList(),openAudio:async u=>{let{entry:a}=await t.sessionFor(u),l=e.get(a);return l||(l=(async()=>Rt(a.session,await n()))(),e.set(a,l),l.catch(()=>e.delete(a))),l},openVideo:async u=>{let{entry:a}=await t.sessionFor(u),l=r.get(a);return l||(l=Et(a.session),r.set(a,l)),l},openVideoOut:async u=>{let{entry:a}=await t.sessionFor(u),l=o.get(a);return l||(l=Ot(a.session),o.set(a,l)),l},sessionHandle:async u=>(await t.handleFor(u)).handle,createResponseOn:async(u,a)=>{let{entry:l}=await t.sessionForHandle(u);return it(await l.responses.responses.create(a),l.gone)},onSessionEnd:async(u,a)=>{let{entry:l}=await t.sessionForHandle(u),d=l.session;if(typeof d.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let p=!1;return d.onPhase(h=>{if(p||!hr.has(h.name))return;p=!0;let x=d.endsAt??null;a({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})}}}var gr=512;function yr(t){return`urun-inference-proxy-${(0,qt.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Fe=class{constructor(n){this.opts=n}opts;tenants=new Map;build(n){if(this.opts.build)return this.opts.build(n);let e=Ft({baseUrl:this.opts.baseUrl,orgId:n.orgId,defaultApp:null,fnName:kt,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:n.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:yr(n.apiKey)});return{router:e,clients:Gt(e)}}clientsFor(n){let e=this.tenants.get(n.apiKey);if(e)return this.tenants.delete(n.apiKey),this.tenants.set(n.apiKey,e),e.clients;for(;this.tenants.size>=gr;){let o=this.tenants.entries().next();if(o.done)break;let[u,a]=o.value;this.tenants.delete(u),a.router.closeAll().catch(()=>{})}let r=this.build(n);return this.tenants.set(n.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let n=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let e=[];if(await Promise.all(n.map(async r=>{try{await r.closeAll()}catch(o){e.push(String(o instanceof Error?o.message:o))}})),e.length>0)throw new Error(`failed to close ${e.length} tenant backhaul(s): ${e.join("; ")}`)}};var wr=5e3,_r=3e3,vr="/api/client-tokens";function at(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function Jt(t,n,e,r){at(t,n,{error:{message:e,type:r}})}async function kr(t,n=fetch){let e=`${t.replace(/\/+$/,"")}${vr}`;try{let r=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(_r)});return r.status===404?{ready:!1,detail:`${e} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${e} answered HTTP ${r.status}`}:{ready:!0,detail:`${e} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${e} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function zt(t){let n=t.resolver??new je({gatewayUrl:t.baseUrl}),e=t.registry??new Fe({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>kr(t.baseUrl)),o=async d=>n.resolve(Mt(d.headers.authorization)),u=Ut({clients:async d=>e.clientsFor(await o(d)),statusOf:d=>d instanceof me?{status:d.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:d instanceof Se?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null}),a=null;return{server:(0,Wt.createServer)((d,p)=>{let h=new URL(d.url??"/","http://localhost");(async()=>{if(d.method==="GET"&&h.pathname==="/healthz"){at(p,200,{ok:!0});return}if(d.method==="GET"&&h.pathname==="/readyz"){let x=Date.now();if(!a||x-a.at>=wr){let A=await r();a={at:x,...A}}at(p,a.ready?200:503,{ok:a.ready,control_plane:a.detail});return}if(h.pathname!=="/v1"&&!h.pathname.startsWith("/v1/")){Jt(p,404,`no route for ${d.method} ${h.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface plus /healthz and /readyz`,"invalid_request_error");return}u(d,p)})().catch(x=>{if(!p.headersSent){Jt(p,500,String(x instanceof Error?x.message:x),"proxy_error");return}p.end()})}),closeAll:()=>e.closeAll()}}async function Kt(t,n){let e=new Promise(r=>t.close(()=>r()));t.closeAllConnections(),await e,await n()}async function br(){let t=bt(de.default.env),{server:n,closeAll:e}=zt(t);await new Promise((o,u)=>{n.once("error",u),n.listen(t.port,Ke,o)}),de.default.stdout.write(`inference-proxy listening on http://${Ke}:${t.port}/v1 (control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
|
|
35
|
+
`)),h.end()})}}S();var He=require("@urun-sh/core"),me=class extends Error{constructor(e,r=401){super(e);this.status=r;this.name="ProxyAuthError"}status},Re=class extends Error{constructor(n){super(n),this.name="ControlPlaneUnavailableError"}};function Bt(t){let n=(t??"").trim();if(n==="")throw new me("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let e=/^Bearer[ \t]+(\S.*)$/i.exec(n);if(!e)throw new me("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return e[1].trim()}var lr=60,dr=6e4,pr=4096;function fr(t){return t===401||t===403}var Ve=class{constructor(n){this.opts=n;this.mint=n.mint??He.createClientToken,this.now=n.now??Date.now}opts;cache=new Map;mint;now;async resolve(n){if(n==="")throw new me("empty Authorization bearer token");let e=this.cache.get(n);if(e&&this.now()-e.at<dr)return{apiKey:n,orgId:e.orgId};let r;try{r=(await this.mint(n,{baseUrl:this.opts.gatewayUrl,expiresIn:lr})).orgId}catch(o){throw o instanceof He.ClientTokenError&&fr(o.status)?(this.cache.delete(n),new me("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Re(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Re("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=pr){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(n,{orgId:r,at:this.now()}),{apiKey:n,orgId:r}}clear(){this.cache.clear()}};S();var Zt=require("crypto");S();var Ce=require("@urun-sh/core");S();async function Ft(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}S();S();S();function Gt(t,n,e,r){let o=t.response??{},u={request_id:e,consumer_id:r,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(u.instructions=o.instructions),Array.isArray(o.modalities)&&(u.modalities=o.modalities),typeof o.temperature=="number"&&(u.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(u.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(u.tools=o.tools),u}function qt(t,n,e){let r={request_id:n,consumer_id:e,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),r}S();S();function Jt(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let n=t,e=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:e.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var mr="llm-resp";async function*it(t,n){let e=`${mr}:${n}`,r=`resp_${n}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;for await(let u of t.stream(e).messages()){let i=u;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let l of i.tool_calls){let d=typeof l.index=="number"?l.index:0,p=o.get(d)??{};l.id&&(p.id=l.id),l.function?.name&&(p.name=l.function.name),o.set(d,p),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${d}`,tool_index:d,call_id:p.id,name:p.name,delta:l.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield Jt(i);return}}}var hr="llm",Be=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(hr).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,e){let r=qt(n,e,this.consumerId);return this.write(r),it(this.session,e)}sendResponseCreate(n,e,r){let o=Gt(n,e,r,this.consumerId);return this.write(o),it(this.session,r)}};var Wt=0;function gr(){return Wt+=1,`req_${Date.now().toString(36)}_${Wt.toString(36)}`}var Fe=class{transport;constructor(n){this.transport=new Be(n)}responses={create:async n=>{let e=gr(),r=this.transport.sendResponses(n,e);return Object.assign((async function*(){yield*r})(),{requestId:e})}}};S();function yr(t){let n=t?.type;return n==="response.created"||n==="response.in_progress"}function wr(t){let n=t?.type;return n==="response.completed"||n==="error"}function zt(t){return async function(e){return(async function*(){for(let o=1;o<=2;o++){let{app:u,entry:i}=await t.sessionFor(e.model),l=!1,d=!1;try{let p=await t.createStream(i,e);for await(let h of p){if(wr(h)&&(l=!0),yr(h)){if(o>1)continue}else d=!0;yield h}}catch(p){if(o<2&&!d){await t.evict(u,i);continue}throw p}if(l)return;if(o<2&&!d){await t.evict(u,i);continue}return}})()}}S();var _r=3,vr="llm",kr=new Set(["paused","error"]);function Kt(t,n){let e=t.doc(vr),r=typeof e.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let u=null,i=new Set,l=[],d=p=>{if(!u){u=p;for(let h of[...i])h(p);i.clear()}};return r&&l.push(e.onConnectionState(p=>{p.consecutiveFailures<_r||d(new ae(`the pooled session for app "${n}" is gone: its doc backhaul failed ${p.consecutiveFailures} consecutive times (last close ${p.lastCloseCode===null?"by provider liveness reap":`code ${p.lastCloseCode}`}${p.lastCloseReason?`, reason ${JSON.stringify(p.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),o&&l.push(t.onPhase(p=>{kr.has(p.name)&&d(new ae(`the pooled session for app "${n}" lost its compute binding (phase "${p.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>u,onGone(p){return u?(p(u),()=>{}):(i.add(p),()=>i.delete(p))},dispose(){i.clear();for(let p of l.splice(0))p()}}}async function*at(t,n){let e=n.gone();if(e)throw e;let r=t[Symbol.asyncIterator](),o,u=new Promise((i,l)=>{o=n.onGone(d=>l(d))});u.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),u]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function Yt(t,n,e){let r=t[e];if(typeof r!="function")throw new Error(`app "${n}" has no function "${e}" (set URUN_FUNCTION)`);let o=r();if(typeof o.end!="function")throw new Error(`app "${n}" function "${e}" returned a session without end()`);return o}function br(t,n){let{baseUrl:e,orgId:r,fnName:o,auth:u,subject:i}=t,l=x=>({session:x,responses:new Fe(x),gone:Kt(x,n)});if(u.lane==="jwt"){let x=(0,Ce.App)(n,{baseUrl:e,orgId:r,jwt:u.jwt});return l(Yt(x,n,o))}let{apiKey:d,gatewayUrl:p}=u,h=(0,Ce.App)(n,{baseUrl:e,orgId:r,getAccessToken:async()=>(await(0,Ce.createClientToken)(d,{baseUrl:p,expiresIn:300,allowedFunctions:[`${n}/${o}`],...i===void 0?{}:{subject:i}})).token});return l(Yt(h,n,o))}function xr(t){let n=t.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var Sr=new Set(["error","paused"]);function Xt(t){let{auth:n,catalog:e}=t,r=null,o=i=>{let l=br(t,i);return l.gone.onGone(()=>{r?.evict(i,l)}),l},u=new Ue({defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{i.gone.dispose(),await i.session.end()},listApps:n.lane==="api-key"?()=>At({apiUrl:t.apiUrl,apiKey:n.apiKey}):null,listCatalog:e?()=>Ft(e):null,sessionKey:xr});return r=u,t.defaultApp!==null&&u.seed(t.defaultApp,o(t.defaultApp)),u}function Qt(t,n=Nt){let e=new WeakMap,r=new WeakMap,o=new WeakMap;return{createResponse:zt({sessionFor:u=>t.sessionFor(u),evict:(u,i)=>t.evict(u,i),createStream:async(u,i)=>at(await u.responses.responses.create(i),u.gone)}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),openAudio:async u=>{let{entry:i}=await t.sessionFor(u),l=e.get(i);return l||(l=(async()=>Ut(i.session,await n()))(),e.set(i,l),l.catch(()=>e.delete(i))),l},openVideo:async u=>{let{entry:i}=await t.sessionFor(u),l=r.get(i);return l||(l=Mt(i.session),r.set(i,l)),l},openVideoOut:async u=>{let{entry:i}=await t.sessionFor(u),l=o.get(i);return l||(l=$t(i.session),o.set(i,l)),l},sessionHandle:async u=>(await t.handleFor(u)).handle,createResponseOn:async(u,i)=>{let{entry:l}=await t.sessionForHandle(u);return at(await l.responses.responses.create(i),l.gone)},onSessionEnd:async(u,i)=>{let{entry:l}=await t.sessionForHandle(u),d=l.session;if(typeof d.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let p=!1;return d.onPhase(h=>{if(p||!Sr.has(h.name))return;p=!0;let x=d.endsAt??null;i({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})}}}var Rr=512;function Er(t){return`urun-inference-proxy-${(0,Zt.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Ge=class{constructor(n){this.opts=n}opts;tenants=new Map;build(n){if(this.opts.build)return this.opts.build(n);let e=Xt({baseUrl:this.opts.baseUrl,orgId:n.orgId,defaultApp:null,fnName:It,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:n.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:Er(n.apiKey)});return{router:e,clients:Qt(e)}}clientsFor(n){let e=this.tenants.get(n.apiKey);if(e)return this.tenants.delete(n.apiKey),this.tenants.set(n.apiKey,e),e.clients;for(;this.tenants.size>=Rr;){let o=this.tenants.entries().next();if(o.done)break;let[u,i]=o.value;this.tenants.delete(u),i.router.closeAll().catch(()=>{})}let r=this.build(n);return this.tenants.set(n.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let n=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let e=[];if(await Promise.all(n.map(async r=>{try{await r.closeAll()}catch(o){e.push(String(o instanceof Error?o.message:o))}})),e.length>0)throw new Error(`failed to close ${e.length} tenant backhaul(s): ${e.join("; ")}`)}};var Ar=5e3,Or=3e3,Ir="/api/client-tokens";function ut(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function en(t,n,e,r){ut(t,n,{error:{message:e,type:r}})}async function Tr(t,n=fetch){let e=`${t.replace(/\/+$/,"")}${Ir}`;try{let r=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Or)});return r.status===404?{ready:!1,detail:`${e} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${e} answered HTTP ${r.status}`}:{ready:!0,detail:`${e} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${e} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function nn(t){let n=t.resolver??new Ve({gatewayUrl:t.baseUrl}),e=t.registry??new Ge({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Tr(t.baseUrl)),o=async d=>n.resolve(Bt(d.headers.authorization)),u=Ht({clients:async d=>e.clientsFor(await o(d)),statusOf:d=>d instanceof me?{status:d.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:d instanceof Re?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null}),i=null;return{server:(0,tn.createServer)((d,p)=>{let h=new URL(d.url??"/","http://localhost");(async()=>{if(d.method==="GET"&&h.pathname==="/healthz"){ut(p,200,{ok:!0});return}if(d.method==="GET"&&h.pathname==="/readyz"){let x=Date.now();if(!i||x-i.at>=Ar){let A=await r();i={at:x,...A}}ut(p,i.ready?200:503,{ok:i.ready,control_plane:i.detail});return}if(h.pathname!=="/v1"&&!h.pathname.startsWith("/v1/")){en(p,404,`no route for ${d.method} ${h.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface plus /healthz and /readyz`,"invalid_request_error");return}u(d,p)})().catch(x=>{if(!p.headersSent){en(p,500,String(x instanceof Error?x.message:x),"proxy_error");return}p.end()})}),closeAll:()=>e.closeAll()}}async function rn(t,n){let e=new Promise(r=>t.close(()=>r()));t.closeAllConnections(),await e,await n()}async function Pr(){let t=Tt(de.default.env),{server:n,closeAll:e}=nn(t);await new Promise((o,u)=>{n.once("error",u),n.listen(t.port,Ye,o)}),de.default.stdout.write(`inference-proxy listening on http://${Ye}:${t.port}/v1 (control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
|
|
36
36
|
`);let r=async o=>{de.default.stdout.write(`inference-proxy: ${o} \u2014 draining
|
|
37
|
-
`),await
|
|
37
|
+
`),await rn(n,e)};await new Promise(o=>{de.default.once("SIGINT",()=>{r("SIGINT").finally(o)}),de.default.once("SIGTERM",()=>{r("SIGTERM").finally(o)})})}Pr().then(()=>de.default.exit(0),t=>{de.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
|
|
38
38
|
`),de.default.exit(1)});
|
|
39
39
|
/*! Bundled license information:
|
|
40
40
|
|
package/dist/hosted/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{i as z,j as se,p as ce,q as de}from"../chunk-EWCEZIOX.js";import"../chunk-TE6632EU.js";import"../chunk-F2TEK34X.js";import"../chunk-M6ICU4F5.js";import"../chunk-G3NMGP4N.js";import"../chunk-XHIIEA6Z.js";import"../chunk-5NXM4IO3.js";import"../chunk-CWJRDBDC.js";import"../chunk-UVAY7Q7Z.js";import{a as We,b as $e,c as H}from"../chunk-YSFSRI3D.js";var he=We(()=>{"use strict";H();var le;(function(M){(function(_){var p=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:A(),b=g(M);typeof p.Reflect<"u"&&(b=g(p.Reflect,b)),_(b,p),typeof p.Reflect>"u"&&(p.Reflect=M);function g(P,x){return function(k,C){Object.defineProperty(P,k,{configurable:!0,writable:!0,value:C}),x&&x(k,C)}}function j(){try{return Function("return this;")()}catch{}}function E(){try{return(0,eval)("(function() { return this; })()")}catch{}}function A(){return j()||E()}})(function(_,p){var b=Object.prototype.hasOwnProperty,g=typeof Symbol=="function",j=g&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=g&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",A=typeof Object.create=="function",P={__proto__:[]}instanceof Array,x=!A&&!P,k={create:A?function(){return B(Object.create(null))}:P?function(){return B({__proto__:null})}:function(){return B({})},has:x?function(e,t){return b.call(e,t)}:function(e,t){return t in e},get:x?function(e,t){return b.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},C=Object.getPrototypeOf(Function),G=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:De(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ae(),W=typeof WeakMap=="function"?WeakMap:Fe(),I=g?Symbol.for("@reflect-metadata:registry"):void 0,F=xe(),L=Ce(F);function ve(e,t,r,n){if(s(r)){if(!te(e))throw new TypeError;if(!re(t))throw new TypeError;return ke(e,t)}else{if(!te(e))throw new TypeError;if(!h(t))throw new TypeError;if(!h(n)&&!s(n)&&!S(n))throw new TypeError;return S(n)&&(n=void 0),r=O(r),Te(e,t,r,n)}}_("decorate",ve);function ye(e,t){function r(n,u){if(!h(n))throw new TypeError;if(!s(u)&&!Re(u))throw new TypeError;Q(e,t,n,u)}return r}_("metadata",ye);function we(e,t,r,n){if(!h(r))throw new TypeError;return s(n)||(n=O(n)),Q(e,t,r,n)}_("defineMetadata",we);function pe(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),Z(e,t,r)}_("hasMetadata",pe);function _e(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),$(e,t,r)}_("hasOwnMetadata",_e);function Me(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),q(e,t,r)}_("getMetadata",Me);function ge(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),J(e,t,r)}_("getOwnMetadata",ge);function me(e,t){if(!h(e))throw new TypeError;return s(t)||(t=O(t)),X(e,t)}_("getMetadataKeys",me);function be(e,t){if(!h(e))throw new TypeError;return s(t)||(t=O(t)),Y(e,t)}_("getOwnMetadataKeys",be);function Oe(e,t,r){if(!h(t))throw new TypeError;if(s(r)||(r=O(r)),!h(t))throw new TypeError;s(r)||(r=O(r));var n=D(t,r,!1);return s(n)?!1:n.OrdinaryDeleteMetadata(e,t,r)}_("deleteMetadata",Oe);function ke(e,t){for(var r=e.length-1;r>=0;--r){var n=e[r],u=n(t);if(!s(u)&&!S(u)){if(!re(u))throw new TypeError;t=u}}return t}function Te(e,t,r,n){for(var u=e.length-1;u>=0;--u){var v=e[u],w=v(t,r,n);if(!s(w)&&!S(w)){if(!h(w))throw new TypeError;n=w}}return n}function Z(e,t,r){var n=$(e,t,r);if(n)return!0;var u=V(t);return S(u)?!1:Z(e,u,r)}function $(e,t,r){var n=D(t,r,!1);return s(n)?!1:ee(n.OrdinaryHasOwnMetadata(e,t,r))}function q(e,t,r){var n=$(e,t,r);if(n)return J(e,t,r);var u=V(t);if(!S(u))return q(e,u,r)}function J(e,t,r){var n=D(t,r,!1);if(!s(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function Q(e,t,r,n){var u=D(r,n,!0);u.OrdinaryDefineOwnMetadata(e,t,r,n)}function X(e,t){var r=Y(e,t),n=V(e);if(n===null)return r;var u=X(n,t);if(u.length<=0)return r;if(r.length<=0)return u;for(var v=new U,w=[],c=0,a=r;c<a.length;c++){var i=a[c],o=v.has(i);o||(v.add(i),w.push(i))}for(var f=0,d=u;f<d.length;f++){var i=d[f],o=v.has(i);o||(v.add(i),w.push(i))}return w}function Y(e,t){var r=D(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function K(e){if(e===null)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return e===null?1:6;default:return 6}}function s(e){return e===void 0}function S(e){return e===null}function Ee(e){return typeof e=="symbol"}function h(e){return typeof e=="object"?e!==null:typeof e=="function"}function Pe(e,t){switch(K(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var r=t===3?"string":t===5?"number":"default",n=ne(e,j);if(n!==void 0){var u=n.call(e,r);if(h(u))throw new TypeError;return u}return Ie(e,r==="default"?"number":r)}function Ie(e,t){if(t==="string"){var r=e.toString;if(R(r)){var n=r.call(e);if(!h(n))return n}var u=e.valueOf;if(R(u)){var n=u.call(e);if(!h(n))return n}}else{var u=e.valueOf;if(R(u)){var n=u.call(e);if(!h(n))return n}var v=e.toString;if(R(v)){var n=v.call(e);if(!h(n))return n}}throw new TypeError}function ee(e){return!!e}function Se(e){return""+e}function O(e){var t=Pe(e,3);return Ee(t)?t:Se(t)}function te(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)==="[object Array]"}function R(e){return typeof e=="function"}function re(e){return typeof e=="function"}function Re(e){switch(K(e)){case 3:return!0;case 4:return!0;default:return!1}}function N(e,t){return e===t||e!==e&&t!==t}function ne(e,t){var r=e[t];if(r!=null){if(!R(r))throw new TypeError;return r}}function ae(e){var t=ne(e,E);if(!R(t))throw new TypeError;var r=t.call(e);if(!h(r))throw new TypeError;return r}function ie(e){return e.value}function oe(e){var t=e.next();return t.done?!1:t}function fe(e){var t=e.return;t&&t.call(e)}function V(e){var t=Object.getPrototypeOf(e);if(typeof e!="function"||e===C||t!==C)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(n==null||n===Object.prototype)return t;var u=n.constructor;return typeof u!="function"||u===e?t:u}function je(){var e;!s(I)&&typeof p.Reflect<"u"&&!(I in p.Reflect)&&typeof p.Reflect.defineMetadata=="function"&&(e=Ge(p.Reflect));var t,r,n,u=new W,v={registerProvider:w,getProvider:a,setProvider:o};return v;function w(f){if(!Object.isExtensible(v))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===f:break;case s(t):t=f;break;case t===f:break;case s(r):r=f;break;case r===f:break;default:n===void 0&&(n=new U),n.add(f);break}}function c(f,d){if(!s(t)){if(t.isProviderFor(f,d))return t;if(!s(r)){if(r.isProviderFor(f,d))return t;if(!s(n))for(var l=ae(n);;){var y=oe(l);if(!y)return;var m=ie(y);if(m.isProviderFor(f,d))return fe(l),m}}}if(!s(e)&&e.isProviderFor(f,d))return e}function a(f,d){var l=u.get(f),y;return s(l)||(y=l.get(d)),s(y)&&(y=c(f,d),s(y)||(s(l)&&(l=new G,u.set(f,l)),l.set(d,y))),y}function i(f){if(s(f))throw new TypeError;return t===f||r===f||!s(n)&&n.has(f)}function o(f,d,l){if(!i(l))throw new Error("Metadata provider not registered.");var y=a(f,d);if(y!==l){if(!s(y))return!1;var m=u.get(f);s(m)&&(m=new G,u.set(f,m)),m.set(d,l)}return!0}}function xe(){var e;return!s(I)&&h(p.Reflect)&&Object.isExtensible(p.Reflect)&&(e=p.Reflect[I]),s(e)&&(e=je()),!s(I)&&h(p.Reflect)&&Object.isExtensible(p.Reflect)&&Object.defineProperty(p.Reflect,I,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function Ce(e){var t=new W,r={isProviderFor:function(i,o){var f=t.get(i);return s(f)?!1:f.has(o)},OrdinaryDefineOwnMetadata:w,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:v,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:a};return F.registerProvider(r),r;function n(i,o,f){var d=t.get(i),l=!1;if(s(d)){if(!f)return;d=new G,t.set(i,d),l=!0}var y=d.get(o);if(s(y)){if(!f)return;if(y=new G,d.set(o,y),!e.setProvider(i,o,r))throw d.delete(o),l&&t.delete(i),new Error("Wrong provider for target.")}return y}function u(i,o,f){var d=n(o,f,!1);return s(d)?!1:ee(d.has(i))}function v(i,o,f){var d=n(o,f,!1);if(!s(d))return d.get(i)}function w(i,o,f,d){var l=n(f,d,!0);l.set(i,o)}function c(i,o){var f=[],d=n(i,o,!1);if(s(d))return f;for(var l=d.keys(),y=ae(l),m=0;;){var ue=oe(y);if(!ue)return f.length=m,f;var He=ie(ue);try{f[m]=He}catch(Ue){try{fe(y)}finally{throw Ue}}m++}}function a(i,o,f){var d=n(o,f,!1);if(s(d)||!d.delete(i))return!1;if(d.size===0){var l=t.get(o);s(l)||(l.delete(f),l.size===0&&t.delete(l))}return!0}}function Ge(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,u=e.getOwnMetadataKeys,v=e.deleteMetadata,w=new W,c={isProviderFor:function(a,i){var o=w.get(a);return!s(o)&&o.has(i)?!0:u(a,i).length?(s(o)&&(o=new U,w.set(a,o)),o.add(i),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:u,OrdinaryDeleteMetadata:v};return c}function D(e,t,r){var n=F.getProvider(e,t);if(!s(n))return n;if(r){if(F.setProvider(e,t,L))return L;throw new Error("Illegal state.")}}function De(){var e={},t=[],r=(function(){function c(a,i,o){this._index=0,this._keys=a,this._values=i,this._selector=o}return c.prototype["@@iterator"]=function(){return this},c.prototype[E]=function(){return this},c.prototype.next=function(){var a=this._index;if(a>=0&&a<this._keys.length){var i=this._selector(this._keys[a],this._values[a]);return a+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(a){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),a},c.prototype.return=function(a){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:a,done:!0}},c})(),n=(function(){function c(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(a){return this._find(a,!1)>=0},c.prototype.get=function(a){var i=this._find(a,!1);return i>=0?this._values[i]:void 0},c.prototype.set=function(a,i){var o=this._find(a,!0);return this._values[o]=i,this},c.prototype.delete=function(a){var i=this._find(a,!1);if(i>=0){for(var o=this._keys.length,f=i+1;f<o;f++)this._keys[f-1]=this._keys[f],this._values[f-1]=this._values[f];return this._keys.length--,this._values.length--,N(a,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},c.prototype.keys=function(){return new r(this._keys,this._values,u)},c.prototype.values=function(){return new r(this._keys,this._values,v)},c.prototype.entries=function(){return new r(this._keys,this._values,w)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[E]=function(){return this.entries()},c.prototype._find=function(a,i){if(!N(this._cacheKey,a)){this._cacheIndex=-1;for(var o=0;o<this._keys.length;o++)if(N(this._keys[o],a)){this._cacheIndex=o;break}}return this._cacheIndex<0&&i&&(this._cacheIndex=this._keys.length,this._keys.push(a),this._values.push(void 0)),this._cacheIndex},c})();return n;function u(c,a){return c}function v(c,a){return a}function w(c,a){return[c,a]}}function Ae(){var e=(function(){function t(){this._map=new G}return Object.defineProperty(t.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),t.prototype.has=function(r){return this._map.has(r)},t.prototype.add=function(r){return this._map.set(r,r),this},t.prototype.delete=function(r){return this._map.delete(r)},t.prototype.clear=function(){this._map.clear()},t.prototype.keys=function(){return this._map.keys()},t.prototype.values=function(){return this._map.keys()},t.prototype.entries=function(){return this._map.entries()},t.prototype["@@iterator"]=function(){return this.keys()},t.prototype[E]=function(){return this.keys()},t})();return e}function Fe(){var e=16,t=k.create(),r=n();return(function(){function a(){this._key=n()}return a.prototype.has=function(i){var o=u(i,!1);return o!==void 0?k.has(o,this._key):!1},a.prototype.get=function(i){var o=u(i,!1);return o!==void 0?k.get(o,this._key):void 0},a.prototype.set=function(i,o){var f=u(i,!0);return f[this._key]=o,this},a.prototype.delete=function(i){var o=u(i,!1);return o!==void 0?delete o[this._key]:!1},a.prototype.clear=function(){this._key=n()},a})();function n(){var a;do a="@@WeakMap@@"+c();while(k.has(t,a));return t[a]=!0,a}function u(a,i){if(!b.call(a,r)){if(!i)return;Object.defineProperty(a,r,{value:k.create()})}return a[r]}function v(a,i){for(var o=0;o<i;++o)a[o]=Math.random()*255|0;return a}function w(a){if(typeof Uint8Array=="function"){var i=new Uint8Array(a);return typeof crypto<"u"?crypto.getRandomValues(i):typeof msCrypto<"u"?msCrypto.getRandomValues(i):v(i,a),i}return v(new Array(a),a)}function c(){var a=w(e);a[6]=a[6]&79|64,a[8]=a[8]&191|128;for(var i="",o=0;o<e;++o){var f=a[o];(o===4||o===6||o===8)&&(i+="-"),f<16&&(i+="0"),i+=f.toString(16).toLowerCase()}return i}}function B(e){return e.__=void 0,delete e.__,e}})})(le||(le={}))});H();var qe=$e(he(),1);import T from"process";async function Be(){let M=se(T.env),{server:_,closeAll:p}=ce(M);await new Promise((g,j)=>{_.once("error",j),_.listen(M.port,z,g)}),T.stdout.write(`inference-proxy listening on http://${z}:${M.port}/v1 (control plane ${M.baseUrl}, org API ${M.apiUrl}, catalog oracle ${M.catalog?"on":"off"})
|
|
2
|
+
import{i as z,j as se,p as ce,q as de}from"../chunk-STFRT5OY.js";import"../chunk-RQBD4OAA.js";import"../chunk-K23AZPI4.js";import"../chunk-VNM4M4P3.js";import"../chunk-GBBY3PCZ.js";import"../chunk-4MSBS7M6.js";import"../chunk-5NXM4IO3.js";import"../chunk-CWJRDBDC.js";import"../chunk-OI2OY32M.js";import{a as We,b as $e,c as H}from"../chunk-YSFSRI3D.js";var he=We(()=>{"use strict";H();var le;(function(M){(function(_){var p=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:A(),b=g(M);typeof p.Reflect<"u"&&(b=g(p.Reflect,b)),_(b,p),typeof p.Reflect>"u"&&(p.Reflect=M);function g(P,x){return function(k,C){Object.defineProperty(P,k,{configurable:!0,writable:!0,value:C}),x&&x(k,C)}}function j(){try{return Function("return this;")()}catch{}}function E(){try{return(0,eval)("(function() { return this; })()")}catch{}}function A(){return j()||E()}})(function(_,p){var b=Object.prototype.hasOwnProperty,g=typeof Symbol=="function",j=g&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=g&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",A=typeof Object.create=="function",P={__proto__:[]}instanceof Array,x=!A&&!P,k={create:A?function(){return B(Object.create(null))}:P?function(){return B({__proto__:null})}:function(){return B({})},has:x?function(e,t){return b.call(e,t)}:function(e,t){return t in e},get:x?function(e,t){return b.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},C=Object.getPrototypeOf(Function),G=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:De(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ae(),W=typeof WeakMap=="function"?WeakMap:Fe(),I=g?Symbol.for("@reflect-metadata:registry"):void 0,F=xe(),L=Ce(F);function ve(e,t,r,n){if(s(r)){if(!te(e))throw new TypeError;if(!re(t))throw new TypeError;return ke(e,t)}else{if(!te(e))throw new TypeError;if(!h(t))throw new TypeError;if(!h(n)&&!s(n)&&!S(n))throw new TypeError;return S(n)&&(n=void 0),r=O(r),Te(e,t,r,n)}}_("decorate",ve);function ye(e,t){function r(n,u){if(!h(n))throw new TypeError;if(!s(u)&&!Re(u))throw new TypeError;Q(e,t,n,u)}return r}_("metadata",ye);function we(e,t,r,n){if(!h(r))throw new TypeError;return s(n)||(n=O(n)),Q(e,t,r,n)}_("defineMetadata",we);function pe(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),Z(e,t,r)}_("hasMetadata",pe);function _e(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),$(e,t,r)}_("hasOwnMetadata",_e);function Me(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),q(e,t,r)}_("getMetadata",Me);function ge(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=O(r)),J(e,t,r)}_("getOwnMetadata",ge);function me(e,t){if(!h(e))throw new TypeError;return s(t)||(t=O(t)),X(e,t)}_("getMetadataKeys",me);function be(e,t){if(!h(e))throw new TypeError;return s(t)||(t=O(t)),Y(e,t)}_("getOwnMetadataKeys",be);function Oe(e,t,r){if(!h(t))throw new TypeError;if(s(r)||(r=O(r)),!h(t))throw new TypeError;s(r)||(r=O(r));var n=D(t,r,!1);return s(n)?!1:n.OrdinaryDeleteMetadata(e,t,r)}_("deleteMetadata",Oe);function ke(e,t){for(var r=e.length-1;r>=0;--r){var n=e[r],u=n(t);if(!s(u)&&!S(u)){if(!re(u))throw new TypeError;t=u}}return t}function Te(e,t,r,n){for(var u=e.length-1;u>=0;--u){var v=e[u],w=v(t,r,n);if(!s(w)&&!S(w)){if(!h(w))throw new TypeError;n=w}}return n}function Z(e,t,r){var n=$(e,t,r);if(n)return!0;var u=V(t);return S(u)?!1:Z(e,u,r)}function $(e,t,r){var n=D(t,r,!1);return s(n)?!1:ee(n.OrdinaryHasOwnMetadata(e,t,r))}function q(e,t,r){var n=$(e,t,r);if(n)return J(e,t,r);var u=V(t);if(!S(u))return q(e,u,r)}function J(e,t,r){var n=D(t,r,!1);if(!s(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function Q(e,t,r,n){var u=D(r,n,!0);u.OrdinaryDefineOwnMetadata(e,t,r,n)}function X(e,t){var r=Y(e,t),n=V(e);if(n===null)return r;var u=X(n,t);if(u.length<=0)return r;if(r.length<=0)return u;for(var v=new U,w=[],c=0,a=r;c<a.length;c++){var i=a[c],o=v.has(i);o||(v.add(i),w.push(i))}for(var f=0,d=u;f<d.length;f++){var i=d[f],o=v.has(i);o||(v.add(i),w.push(i))}return w}function Y(e,t){var r=D(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function K(e){if(e===null)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return e===null?1:6;default:return 6}}function s(e){return e===void 0}function S(e){return e===null}function Ee(e){return typeof e=="symbol"}function h(e){return typeof e=="object"?e!==null:typeof e=="function"}function Pe(e,t){switch(K(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var r=t===3?"string":t===5?"number":"default",n=ne(e,j);if(n!==void 0){var u=n.call(e,r);if(h(u))throw new TypeError;return u}return Ie(e,r==="default"?"number":r)}function Ie(e,t){if(t==="string"){var r=e.toString;if(R(r)){var n=r.call(e);if(!h(n))return n}var u=e.valueOf;if(R(u)){var n=u.call(e);if(!h(n))return n}}else{var u=e.valueOf;if(R(u)){var n=u.call(e);if(!h(n))return n}var v=e.toString;if(R(v)){var n=v.call(e);if(!h(n))return n}}throw new TypeError}function ee(e){return!!e}function Se(e){return""+e}function O(e){var t=Pe(e,3);return Ee(t)?t:Se(t)}function te(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)==="[object Array]"}function R(e){return typeof e=="function"}function re(e){return typeof e=="function"}function Re(e){switch(K(e)){case 3:return!0;case 4:return!0;default:return!1}}function N(e,t){return e===t||e!==e&&t!==t}function ne(e,t){var r=e[t];if(r!=null){if(!R(r))throw new TypeError;return r}}function ae(e){var t=ne(e,E);if(!R(t))throw new TypeError;var r=t.call(e);if(!h(r))throw new TypeError;return r}function ie(e){return e.value}function oe(e){var t=e.next();return t.done?!1:t}function fe(e){var t=e.return;t&&t.call(e)}function V(e){var t=Object.getPrototypeOf(e);if(typeof e!="function"||e===C||t!==C)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(n==null||n===Object.prototype)return t;var u=n.constructor;return typeof u!="function"||u===e?t:u}function je(){var e;!s(I)&&typeof p.Reflect<"u"&&!(I in p.Reflect)&&typeof p.Reflect.defineMetadata=="function"&&(e=Ge(p.Reflect));var t,r,n,u=new W,v={registerProvider:w,getProvider:a,setProvider:o};return v;function w(f){if(!Object.isExtensible(v))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===f:break;case s(t):t=f;break;case t===f:break;case s(r):r=f;break;case r===f:break;default:n===void 0&&(n=new U),n.add(f);break}}function c(f,d){if(!s(t)){if(t.isProviderFor(f,d))return t;if(!s(r)){if(r.isProviderFor(f,d))return t;if(!s(n))for(var l=ae(n);;){var y=oe(l);if(!y)return;var m=ie(y);if(m.isProviderFor(f,d))return fe(l),m}}}if(!s(e)&&e.isProviderFor(f,d))return e}function a(f,d){var l=u.get(f),y;return s(l)||(y=l.get(d)),s(y)&&(y=c(f,d),s(y)||(s(l)&&(l=new G,u.set(f,l)),l.set(d,y))),y}function i(f){if(s(f))throw new TypeError;return t===f||r===f||!s(n)&&n.has(f)}function o(f,d,l){if(!i(l))throw new Error("Metadata provider not registered.");var y=a(f,d);if(y!==l){if(!s(y))return!1;var m=u.get(f);s(m)&&(m=new G,u.set(f,m)),m.set(d,l)}return!0}}function xe(){var e;return!s(I)&&h(p.Reflect)&&Object.isExtensible(p.Reflect)&&(e=p.Reflect[I]),s(e)&&(e=je()),!s(I)&&h(p.Reflect)&&Object.isExtensible(p.Reflect)&&Object.defineProperty(p.Reflect,I,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function Ce(e){var t=new W,r={isProviderFor:function(i,o){var f=t.get(i);return s(f)?!1:f.has(o)},OrdinaryDefineOwnMetadata:w,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:v,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:a};return F.registerProvider(r),r;function n(i,o,f){var d=t.get(i),l=!1;if(s(d)){if(!f)return;d=new G,t.set(i,d),l=!0}var y=d.get(o);if(s(y)){if(!f)return;if(y=new G,d.set(o,y),!e.setProvider(i,o,r))throw d.delete(o),l&&t.delete(i),new Error("Wrong provider for target.")}return y}function u(i,o,f){var d=n(o,f,!1);return s(d)?!1:ee(d.has(i))}function v(i,o,f){var d=n(o,f,!1);if(!s(d))return d.get(i)}function w(i,o,f,d){var l=n(f,d,!0);l.set(i,o)}function c(i,o){var f=[],d=n(i,o,!1);if(s(d))return f;for(var l=d.keys(),y=ae(l),m=0;;){var ue=oe(y);if(!ue)return f.length=m,f;var He=ie(ue);try{f[m]=He}catch(Ue){try{fe(y)}finally{throw Ue}}m++}}function a(i,o,f){var d=n(o,f,!1);if(s(d)||!d.delete(i))return!1;if(d.size===0){var l=t.get(o);s(l)||(l.delete(f),l.size===0&&t.delete(l))}return!0}}function Ge(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,u=e.getOwnMetadataKeys,v=e.deleteMetadata,w=new W,c={isProviderFor:function(a,i){var o=w.get(a);return!s(o)&&o.has(i)?!0:u(a,i).length?(s(o)&&(o=new U,w.set(a,o)),o.add(i),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:u,OrdinaryDeleteMetadata:v};return c}function D(e,t,r){var n=F.getProvider(e,t);if(!s(n))return n;if(r){if(F.setProvider(e,t,L))return L;throw new Error("Illegal state.")}}function De(){var e={},t=[],r=(function(){function c(a,i,o){this._index=0,this._keys=a,this._values=i,this._selector=o}return c.prototype["@@iterator"]=function(){return this},c.prototype[E]=function(){return this},c.prototype.next=function(){var a=this._index;if(a>=0&&a<this._keys.length){var i=this._selector(this._keys[a],this._values[a]);return a+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(a){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),a},c.prototype.return=function(a){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:a,done:!0}},c})(),n=(function(){function c(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(a){return this._find(a,!1)>=0},c.prototype.get=function(a){var i=this._find(a,!1);return i>=0?this._values[i]:void 0},c.prototype.set=function(a,i){var o=this._find(a,!0);return this._values[o]=i,this},c.prototype.delete=function(a){var i=this._find(a,!1);if(i>=0){for(var o=this._keys.length,f=i+1;f<o;f++)this._keys[f-1]=this._keys[f],this._values[f-1]=this._values[f];return this._keys.length--,this._values.length--,N(a,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},c.prototype.keys=function(){return new r(this._keys,this._values,u)},c.prototype.values=function(){return new r(this._keys,this._values,v)},c.prototype.entries=function(){return new r(this._keys,this._values,w)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[E]=function(){return this.entries()},c.prototype._find=function(a,i){if(!N(this._cacheKey,a)){this._cacheIndex=-1;for(var o=0;o<this._keys.length;o++)if(N(this._keys[o],a)){this._cacheIndex=o;break}}return this._cacheIndex<0&&i&&(this._cacheIndex=this._keys.length,this._keys.push(a),this._values.push(void 0)),this._cacheIndex},c})();return n;function u(c,a){return c}function v(c,a){return a}function w(c,a){return[c,a]}}function Ae(){var e=(function(){function t(){this._map=new G}return Object.defineProperty(t.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),t.prototype.has=function(r){return this._map.has(r)},t.prototype.add=function(r){return this._map.set(r,r),this},t.prototype.delete=function(r){return this._map.delete(r)},t.prototype.clear=function(){this._map.clear()},t.prototype.keys=function(){return this._map.keys()},t.prototype.values=function(){return this._map.keys()},t.prototype.entries=function(){return this._map.entries()},t.prototype["@@iterator"]=function(){return this.keys()},t.prototype[E]=function(){return this.keys()},t})();return e}function Fe(){var e=16,t=k.create(),r=n();return(function(){function a(){this._key=n()}return a.prototype.has=function(i){var o=u(i,!1);return o!==void 0?k.has(o,this._key):!1},a.prototype.get=function(i){var o=u(i,!1);return o!==void 0?k.get(o,this._key):void 0},a.prototype.set=function(i,o){var f=u(i,!0);return f[this._key]=o,this},a.prototype.delete=function(i){var o=u(i,!1);return o!==void 0?delete o[this._key]:!1},a.prototype.clear=function(){this._key=n()},a})();function n(){var a;do a="@@WeakMap@@"+c();while(k.has(t,a));return t[a]=!0,a}function u(a,i){if(!b.call(a,r)){if(!i)return;Object.defineProperty(a,r,{value:k.create()})}return a[r]}function v(a,i){for(var o=0;o<i;++o)a[o]=Math.random()*255|0;return a}function w(a){if(typeof Uint8Array=="function"){var i=new Uint8Array(a);return typeof crypto<"u"?crypto.getRandomValues(i):typeof msCrypto<"u"?msCrypto.getRandomValues(i):v(i,a),i}return v(new Array(a),a)}function c(){var a=w(e);a[6]=a[6]&79|64,a[8]=a[8]&191|128;for(var i="",o=0;o<e;++o){var f=a[o];(o===4||o===6||o===8)&&(i+="-"),f<16&&(i+="0"),i+=f.toString(16).toLowerCase()}return i}}function B(e){return e.__=void 0,delete e.__,e}})})(le||(le={}))});H();var qe=$e(he(),1);import T from"process";async function Be(){let M=se(T.env),{server:_,closeAll:p}=ce(M);await new Promise((g,j)=>{_.once("error",j),_.listen(M.port,z,g)}),T.stdout.write(`inference-proxy listening on http://${z}:${M.port}/v1 (control plane ${M.baseUrl}, org API ${M.apiUrl}, catalog oracle ${M.catalog?"on":"off"})
|
|
3
3
|
`);let b=async g=>{T.stdout.write(`inference-proxy: ${g} \u2014 draining
|
|
4
4
|
`),await de(_,p)};await new Promise(g=>{T.once("SIGINT",()=>{b("SIGINT").finally(g)}),T.once("SIGTERM",()=>{b("SIGTERM").finally(g)})})}Be().then(()=>T.exit(0),M=>{T.stderr.write(`inference-proxy: ${String(M instanceof Error?M.stack??M.message:M)}
|
|
5
5
|
`),T.exit(1)});
|