@urun-sh/openai 0.3.0 → 0.3.1
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/ResponsesClient-BYx3YLGo.d.ts +26 -0
- package/dist/ResponsesClient-Dft3bg3b.d.cts +26 -0
- package/dist/chunk-54VWZJU7.js +6 -0
- package/dist/chunk-5NXM4IO3.js +2 -0
- package/dist/chunk-CWJRDBDC.js +1 -0
- package/dist/chunk-G3NMGP4N.js +1 -0
- package/dist/chunk-M6ICU4F5.js +40 -0
- package/dist/chunk-UVAY7Q7Z.js +1 -0
- package/dist/{chunk-3ED25N7E.js → chunk-ZW6ENXZY.js} +1 -1
- package/dist/gemini-live.cjs +2 -0
- package/dist/gemini-live.d.cts +120 -0
- package/dist/gemini-live.d.ts +79 -0
- package/dist/gemini-live.js +1 -0
- package/dist/hosted/bin.cjs +18 -18
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +17 -17
- package/dist/hosted/index.d.cts +4 -3
- package/dist/hosted/index.d.ts +4 -3
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.d.cts +2 -1
- package/dist/pi-extension/index.d.ts +2 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +53 -53
- package/dist/proxy/cli.cjs +37 -37
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +21 -21
- package/dist/proxy/index.d.cts +4 -31
- package/dist/proxy/index.d.ts +4 -6
- package/dist/proxy/index.js +1 -1
- package/dist/{server-DiQUIDDg.d.cts → server-BfME37pQ.d.cts} +20 -2
- package/dist/{server-BBKNv7hV.d.ts → server-l1himPxc.d.ts} +6 -2
- package/dist/translator-C9uPKypK.d.ts +130 -0
- package/dist/translator-CcDBEfvm.d.cts +227 -0
- package/dist/{ResponsesClient-y8g6OfNN.d.cts → types-lsVTbNcH.d.cts} +16 -24
- package/dist/{ResponsesClient-y8g6OfNN.d.ts → types-lsVTbNcH.d.ts} +8 -24
- package/dist/video-out-CWesbk12.d.ts +155 -0
- package/dist/video-out-D20UuJ8G.d.cts +298 -0
- package/package.json +12 -2
- package/dist/chunk-35LB5OHI.js +0 -1
- package/dist/chunk-EFBD3CGZ.js +0 -1
- package/dist/chunk-VG3X2LVG.js +0 -41
- package/dist/chunk-XHRPJIEK.js +0 -6
- package/dist/media-DCHTX3Ez.d.cts +0 -68
- package/dist/media-DCHTX3Ez.d.ts +0 -42
package/dist/hosted/bin.cjs
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var rn=Object.create;var mt=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,un=Object.prototype.hasOwnProperty;var ln=(t,n,e)=>()=>{if(e)throw e[0];try{return t&&(n=t(t=0)),n}catch(r){throw e=[r],r}};var cn=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var dn=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of sn(n))!un.call(t,o)&&o!==e&&mt(t,o,{get:()=>n[o],enumerable:!(r=on(n,o))||r.enumerable});return t};var ve=(t,n,e)=>(e=t!=null?rn(an(t)):{},dn(n||!t||!t.__esModule?mt(e,"default",{value:t,enumerable:!0}):e,t));var S=ln(()=>{"use strict"});var gt=cn(()=>{"use strict";S();var ht;(function(t){(function(n){var e=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:c(),r=o(t);typeof e.Reflect<"u"&&(r=o(e.Reflect,r)),n(r,e),typeof e.Reflect>"u"&&(e.Reflect=t);function o(p,d){return function(k,b){Object.defineProperty(p,k,{configurable:!0,writable:!0,value:b}),d&&d(k,b)}}function l(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function c(){return l()||a()}})(function(n,e){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",l=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",c=typeof Object.create=="function",p={__proto__:[]}instanceof Array,d=!c&&!p,k={create:c?function(){return Je(Object.create(null))}:p?function(){return Je({__proto__:null})}:function(){return Je({})},has:d?function(s,i){return r.call(s,i)}:function(s,i){return i in s},get:d?function(s,i){return r.call(s,i)?s[i]:void 0}:function(s,i){return s[i]}},b=Object.getPrototypeOf(Function),E=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Zt(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Qt(),T=typeof WeakMap=="function"?WeakMap:en(),P=o?Symbol.for("@reflect-metadata:registry"):void 0,h=Kt(),H=Yt(h);function q(s,i,u,f){if(g(u)){if(!it(s))throw new TypeError;if(!at(i))throw new TypeError;return z(s,i)}else{if(!it(s))throw new TypeError;if(!A(i))throw new TypeError;if(!A(f)&&!g(f)&&!L(f))throw new TypeError;return L(f)&&(f=void 0),u=Q(u),N(s,i,u,f)}}n("decorate",q);function K(s,i){function u(f,x){if(!A(f))throw new TypeError;if(!g(x)&&!Wt(x))throw new TypeError;le(s,i,f,x)}return u}n("metadata",K);function W(s,i,u,f){if(!A(u))throw new TypeError;return g(f)||(f=Q(f)),le(s,i,u,f)}n("defineMetadata",W);function Y(s,i,u){if(!A(i))throw new TypeError;return g(u)||(u=Q(u)),j(s,i,u)}n("hasMetadata",Y);function w(s,i,u){if(!A(i))throw new TypeError;return g(u)||(u=Q(u)),Z(s,i,u)}n("hasOwnMetadata",w);function D(s,i,u){if(!A(i))throw new TypeError;return g(u)||(u=Q(u)),ne(s,i,u)}n("getMetadata",D);function ee(s,i,u){if(!A(i))throw new TypeError;return g(u)||(u=Q(u)),$(s,i,u)}n("getOwnMetadata",ee);function V(s,i){if(!A(s))throw new TypeError;return g(i)||(i=Q(i)),pe(s,i)}n("getMetadataKeys",V);function X(s,i){if(!A(s))throw new TypeError;return g(i)||(i=Q(i)),fe(s,i)}n("getOwnMetadataKeys",X);function te(s,i,u){if(!A(i))throw new TypeError;if(g(u)||(u=Q(u)),!A(i))throw new TypeError;g(u)||(u=Q(u));var f=Re(i,u,!1);return g(f)?!1:f.OrdinaryDeleteMetadata(s,i,u)}n("deleteMetadata",te);function z(s,i){for(var u=s.length-1;u>=0;--u){var f=s[u],x=f(i);if(!g(x)&&!L(x)){if(!at(x))throw new TypeError;i=x}}return i}function N(s,i,u,f){for(var x=s.length-1;x>=0;--x){var B=s[x],J=B(i,u,f);if(!g(J)&&!L(J)){if(!A(J))throw new TypeError;f=J}}return f}function j(s,i,u){var f=Z(s,i,u);if(f)return!0;var x=qe(i);return L(x)?!1:j(s,x,u)}function Z(s,i,u){var f=Re(i,u,!1);return g(f)?!1:ge(f.OrdinaryHasOwnMetadata(s,i,u))}function ne(s,i,u){var f=Z(s,i,u);if(f)return $(s,i,u);var x=qe(i);if(!L(x))return ne(s,x,u)}function $(s,i,u){var f=Re(i,u,!1);if(!g(f))return f.OrdinaryGetOwnMetadata(s,i,u)}function le(s,i,u,f){var x=Re(u,f,!0);x.OrdinaryDefineOwnMetadata(s,i,u,f)}function pe(s,i){var u=fe(s,i),f=qe(s);if(f===null)return u;var x=pe(f,i);if(x.length<=0)return u;if(u.length<=0)return x;for(var B=new U,J=[],R=0,m=u;R<m.length;R++){var y=m[R],_=B.has(y);_||(B.add(y),J.push(y))}for(var v=0,I=x;v<I.length;v++){var y=I[v],_=B.has(y);_||(B.add(y),J.push(y))}return J}function fe(s,i){var u=Re(s,i,!1);return u?u.OrdinaryOwnMetadataKeys(s,i):[]}function O(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 g(s){return s===void 0}function L(s){return s===null}function C(s){return typeof s=="symbol"}function A(s){return typeof s=="object"?s!==null:typeof s=="function"}function se(s,i){switch(O(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 u=i===3?"string":i===5?"number":"default",f=ut(s,l);if(f!==void 0){var x=f.call(s,u);if(A(x))throw new TypeError;return x}return he(s,u==="default"?"number":u)}function he(s,i){if(i==="string"){var u=s.toString;if(_e(u)){var f=u.call(s);if(!A(f))return f}var x=s.valueOf;if(_e(x)){var f=x.call(s);if(!A(f))return f}}else{var x=s.valueOf;if(_e(x)){var f=x.call(s);if(!A(f))return f}var B=s.toString;if(_e(B)){var f=B.call(s);if(!A(f))return f}}throw new TypeError}function ge(s){return!!s}function Ae(s){return""+s}function Q(s){var i=se(s,3);return C(i)?i:Ae(i)}function it(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 at(s){return typeof s=="function"}function Wt(s){switch(O(s)){case 3:return!0;case 4:return!0;default:return!1}}function Fe(s,i){return s===i||s!==s&&i!==i}function ut(s,i){var u=s[i];if(u!=null){if(!_e(u))throw new TypeError;return u}}function lt(s){var i=ut(s,a);if(!_e(i))throw new TypeError;var u=i.call(s);if(!A(u))throw new TypeError;return u}function ct(s){return s.value}function dt(s){var i=s.next();return i.done?!1:i}function pt(s){var i=s.return;i&&i.call(s)}function qe(s){var i=Object.getPrototypeOf(s);if(typeof s!="function"||s===b||i!==b)return i;var u=s.prototype,f=u&&Object.getPrototypeOf(u);if(f==null||f===Object.prototype)return i;var x=f.constructor;return typeof x!="function"||x===s?i:x}function zt(){var s;!g(P)&&typeof e.Reflect<"u"&&!(P in e.Reflect)&&typeof e.Reflect.defineMetadata=="function"&&(s=Xt(e.Reflect));var i,u,f,x=new T,B={registerProvider:J,getProvider:m,setProvider:_};return B;function J(v){if(!Object.isExtensible(B))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case s===v:break;case g(i):i=v;break;case i===v:break;case g(u):u=v;break;case u===v:break;default:f===void 0&&(f=new U),f.add(v);break}}function R(v,I){if(!g(i)){if(i.isProviderFor(v,I))return i;if(!g(u)){if(u.isProviderFor(v,I))return i;if(!g(f))for(var M=lt(f);;){var G=dt(M);if(!G)return;var oe=ct(G);if(oe.isProviderFor(v,I))return pt(M),oe}}}if(!g(s)&&s.isProviderFor(v,I))return s}function m(v,I){var M=x.get(v),G;return g(M)||(G=M.get(I)),g(G)&&(G=R(v,I),g(G)||(g(M)&&(M=new E,x.set(v,M)),M.set(I,G))),G}function y(v){if(g(v))throw new TypeError;return i===v||u===v||!g(f)&&f.has(v)}function _(v,I,M){if(!y(M))throw new Error("Metadata provider not registered.");var G=m(v,I);if(G!==M){if(!g(G))return!1;var oe=x.get(v);g(oe)&&(oe=new E,x.set(v,oe)),oe.set(I,M)}return!0}}function Kt(){var s;return!g(P)&&A(e.Reflect)&&Object.isExtensible(e.Reflect)&&(s=e.Reflect[P]),g(s)&&(s=zt()),!g(P)&&A(e.Reflect)&&Object.isExtensible(e.Reflect)&&Object.defineProperty(e.Reflect,P,{enumerable:!1,configurable:!1,writable:!1,value:s}),s}function Yt(s){var i=new T,u={isProviderFor:function(y,_){var v=i.get(y);return g(v)?!1:v.has(_)},OrdinaryDefineOwnMetadata:J,OrdinaryHasOwnMetadata:x,OrdinaryGetOwnMetadata:B,OrdinaryOwnMetadataKeys:R,OrdinaryDeleteMetadata:m};return h.registerProvider(u),u;function f(y,_,v){var I=i.get(y),M=!1;if(g(I)){if(!v)return;I=new E,i.set(y,I),M=!0}var G=I.get(_);if(g(G)){if(!v)return;if(G=new E,I.set(_,G),!s.setProvider(y,_,u))throw I.delete(_),M&&i.delete(y),new Error("Wrong provider for target.")}return G}function x(y,_,v){var I=f(_,v,!1);return g(I)?!1:ge(I.has(y))}function B(y,_,v){var I=f(_,v,!1);if(!g(I))return I.get(y)}function J(y,_,v,I){var M=f(v,I,!0);M.set(y,_)}function R(y,_){var v=[],I=f(y,_,!1);if(g(I))return v;for(var M=I.keys(),G=lt(M),oe=0;;){var ft=dt(G);if(!ft)return v.length=oe,v;var tn=ct(ft);try{v[oe]=tn}catch(nn){try{pt(G)}finally{throw nn}}oe++}}function m(y,_,v){var I=f(_,v,!1);if(g(I)||!I.delete(y))return!1;if(I.size===0){var M=i.get(_);g(M)||(M.delete(v),M.size===0&&i.delete(M))}return!0}}function Xt(s){var i=s.defineMetadata,u=s.hasOwnMetadata,f=s.getOwnMetadata,x=s.getOwnMetadataKeys,B=s.deleteMetadata,J=new T,R={isProviderFor:function(m,y){var _=J.get(m);return!g(_)&&_.has(y)?!0:x(m,y).length?(g(_)&&(_=new U,J.set(m,_)),_.add(y),!0):!1},OrdinaryDefineOwnMetadata:i,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:f,OrdinaryOwnMetadataKeys:x,OrdinaryDeleteMetadata:B};return R}function Re(s,i,u){var f=h.getProvider(s,i);if(!g(f))return f;if(u){if(h.setProvider(s,i,H))return H;throw new Error("Illegal state.")}}function Zt(){var s={},i=[],u=(function(){function R(m,y,_){this._index=0,this._keys=m,this._values=y,this._selector=_}return R.prototype["@@iterator"]=function(){return this},R.prototype[a]=function(){return this},R.prototype.next=function(){var m=this._index;if(m>=0&&m<this._keys.length){var y=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:y,done:!1}}return{value:void 0,done:!0}},R.prototype.throw=function(m){throw this._index>=0&&(this._index=-1,this._keys=i,this._values=i),m},R.prototype.return=function(m){return this._index>=0&&(this._index=-1,this._keys=i,this._values=i),{value:m,done:!0}},R})(),f=(function(){function R(){this._keys=[],this._values=[],this._cacheKey=s,this._cacheIndex=-2}return Object.defineProperty(R.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),R.prototype.has=function(m){return this._find(m,!1)>=0},R.prototype.get=function(m){var y=this._find(m,!1);return y>=0?this._values[y]:void 0},R.prototype.set=function(m,y){var _=this._find(m,!0);return this._values[_]=y,this},R.prototype.delete=function(m){var y=this._find(m,!1);if(y>=0){for(var _=this._keys.length,v=y+1;v<_;v++)this._keys[v-1]=this._keys[v],this._values[v-1]=this._values[v];return this._keys.length--,this._values.length--,Fe(m,this._cacheKey)&&(this._cacheKey=s,this._cacheIndex=-2),!0}return!1},R.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=s,this._cacheIndex=-2},R.prototype.keys=function(){return new u(this._keys,this._values,x)},R.prototype.values=function(){return new u(this._keys,this._values,B)},R.prototype.entries=function(){return new u(this._keys,this._values,J)},R.prototype["@@iterator"]=function(){return this.entries()},R.prototype[a]=function(){return this.entries()},R.prototype._find=function(m,y){if(!Fe(this._cacheKey,m)){this._cacheIndex=-1;for(var _=0;_<this._keys.length;_++)if(Fe(this._keys[_],m)){this._cacheIndex=_;break}}return this._cacheIndex<0&&y&&(this._cacheIndex=this._keys.length,this._keys.push(m),this._values.push(void 0)),this._cacheIndex},R})();return f;function x(R,m){return R}function B(R,m){return m}function J(R,m){return[R,m]}}function Qt(){var s=(function(){function i(){this._map=new E}return Object.defineProperty(i.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),i.prototype.has=function(u){return this._map.has(u)},i.prototype.add=function(u){return this._map.set(u,u),this},i.prototype.delete=function(u){return this._map.delete(u)},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 en(){var s=16,i=k.create(),u=f();return(function(){function m(){this._key=f()}return m.prototype.has=function(y){var _=x(y,!1);return _!==void 0?k.has(_,this._key):!1},m.prototype.get=function(y){var _=x(y,!1);return _!==void 0?k.get(_,this._key):void 0},m.prototype.set=function(y,_){var v=x(y,!0);return v[this._key]=_,this},m.prototype.delete=function(y){var _=x(y,!1);return _!==void 0?delete _[this._key]:!1},m.prototype.clear=function(){this._key=f()},m})();function f(){var m;do m="@@WeakMap@@"+R();while(k.has(i,m));return i[m]=!0,m}function x(m,y){if(!r.call(m,u)){if(!y)return;Object.defineProperty(m,u,{value:k.create()})}return m[u]}function B(m,y){for(var _=0;_<y;++_)m[_]=Math.random()*255|0;return m}function J(m){if(typeof Uint8Array=="function"){var y=new Uint8Array(m);return typeof crypto<"u"?crypto.getRandomValues(y):typeof msCrypto<"u"?msCrypto.getRandomValues(y):B(y,m),y}return B(new Array(m),m)}function R(){var m=J(s);m[6]=m[6]&79|64,m[8]=m[8]&191|128;for(var y="",_=0;_<s;++_){var v=m[_];(_===4||_===6||_===8)&&(y+="-"),v<16&&(y+="0"),y+=v.toString(16).toLowerCase()}return y}}function Je(s){return s.__=void 0,delete s.__,s}})})(ht||(ht={}))});S();var Ko=ve(gt(),1),de=ve(require("process"),1);S();S();var hn=ve(require("os"),1),gn=ve(require("path"),1),yn=require("url"),wn=require("util");S();function Ve(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var re=class extends Error{},ie=class extends Error{},We="urs1.";function pn(t,n){return We+Buffer.from(JSON.stringify([t,n]),"utf8").toString("base64url")}function fn(t){if(!t.startsWith(We))return null;try{let n=JSON.parse(Buffer.from(t.slice(We.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 yt(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 mn=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??mn;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=Ve(e);if(o===r)return r;if(this.pool.has(o))return o;if(this.opts.listApps){let l=await this.deployedApps(),a=this.servable(l);if(a.includes(o))return o;let c=a.filter(d=>d.startsWith(`${o}-`));if(c.length===1)return c[0];if(c.length>1)throw new re(`model "${e}" is ambiguous across deployed apps ${c.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let p=l.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(p)throw new re(`model "${e}" maps to app "${p.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(c=>e===c.model_id||e===`${c.model_id}:${c.variant}`||o===Ve(c.model_id)||o===Ve(`${c.model_id}-${c.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:pn(e,this.keyOf(r))}}async sessionForHandle(n){let e=fn(n);if(!e)throw new ie(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:r,key:o}=e,l=this.pool.get(r),a=l?await l.then(c=>c,()=>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(l=>l,()=>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 wt(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 _n=8080,_t="serve",ze="0.0.0.0";function vn(t,n,e){let r=(t[n]??"").trim();if(!r)throw new Error(`${n} is not set \u2014 ${e}`);return r}function vt(t=process.env){let n=(t.PORT??"").trim(),e=n===""?_n: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=wt(Ue(vn(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(),l=o?Ue(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,a=(t.URUN_CATALOG_URL??"").trim(),c=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!c)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 p=a?{catalogUrl:Ue(a,"URUN_CATALOG_URL"),anonKey:c}:null;return{port:e,baseUrl:r,apiUrl:l,catalog:p}}S();var qt=require("http");S();var Pn=require("http");S();var In=require("crypto"),On=require("ws");S();S();var Ke=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 l=0;l<r;l++)o[l]=e.readInt16LE(l*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 bt(t,n,e=1e4){let r=new Ke(n,{sampleRate:24e3}),o=await r.startOutbound();await t.stream("rt-audio-in").attach(o);let l=await kn(t,e);return await r.startInbound(l),r}function kn(t,n){let e=t.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((r,o)=>{let l,a=setTimeout(()=>{l?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),c=p=>{p!=null&&(clearTimeout(a),l?.(),r(p))};l=e.on?.("track",c),e.track!=null&&c(e.track)})}var kt="rt-video-in",xt=256e3;function St(t){let n=t.stream(kt),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${kt}') 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>xt)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${xt}-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 xn=24e3,Ee=480,bn=111;async function Sn(){let t=await import("opusscript"),n=t.default??t;return new n(xn,1,2048)}async function At(){let t=await import("werift"),n=await Sn();return{createSource:()=>{let e=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,l=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:e,onData:c=>{let p=new Int16Array(a.length+c.length);p.set(a,0),p.set(c,a.length);let d=0;for(;p.length-d>=Ee;){let k=p.subarray(d,d+Ee);d+=Ee;let b=Buffer.from(k.buffer,k.byteOffset,k.byteLength),E=n.encode(b,Ee);o=o+1&65535,l=l+Ee>>>0;let U=new t.RtpHeader({version:2,payloadType:bn,sequenceNumber:o,timestamp:l,ssrc:r,marker:!1}),T=new t.RtpPacket(U,E);e.writeRtp(T)}a=p.slice(d)}}},createSink:e=>{let r={onframe:null};return e.onReceiveRtp.subscribe(l=>{let a;try{a=n.decode(l.payload)}catch{return}let c=new Int16Array(a.length/2);for(let p=0;p<c.length;p++)c[p]=a.readInt16LE(p*2);r.onframe?.({samples:c})}),r}}}var Rn=24e3,Mr=`audio/pcm;rate=${Rn}`,En=Buffer.alloc(960).toString("base64");var Ze=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>=Tn?"(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(),l=null,a=0;return(async function*(){for await(let p of n)p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(l===null&&(l=performance.now(),r.ttftMs.push(l-o),r.ttftMs.length>512&&r.ttftMs.shift()),a+=1,r.tokensOut+=1,r.charsOut+=p.delta.length,e!==void 0&&(r.modelEntry(e).tokens_out+=1)),yield p;let c=(performance.now()-(l??o))/1e3;a>0&&c>0&&(r.tokRates.push(a/c),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 et(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 ce(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 tt(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 Tn=256,Cn=128;function nt(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Cn)}var Rt=64*1024*1024,Me=class extends Error{};async function Un(t){let n=[],e=0;for await(let o of t){if(e+=o.length,e>Rt)throw new Me(`request body exceeds ${Rt} 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 Mn=256;function Nn(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 Qe=class{conversations=new Map;thread(n,e){let r=Nn(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<=Mn)break;this.conversations.delete(o)}}};function Ie(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 Ne(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 l=e(n.total_tokens)||r+o;return{input_tokens:r,output_tokens:o,total_tokens:l}}function Et(t){let n=Ne(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 Ot(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 Oe(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}))}},$n=["<tool_call>","<function="];function Ln(t){return $n.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 be(t,n,e){if(!(!t||n>0))return Ln(e)}function Dn(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 $e=class extends Error{};function jn(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 $e(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function Bn(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:jn(e.role,e.content)})}return n}function Ye(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 It(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 Gn(t,n,e,r,o){let l=t.stream===!0,a;try{a=e.thread(t.previous_response_id,t.input)}catch(h){ce(r,400,String(h instanceof Error?h.message:h));return}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(t.input)));let c=`resp_${Math.random().toString(36).slice(2,14)}`,p=t.store!==!1,d=nt(t);o.model(d);let k=Array.isArray(t.tools)&&t.tools.length>0,b;try{b=await n.createResponse({model:t.model,input:a,stream:l,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(h){if(h instanceof re){tt(r,"openai",h);return}throw h}let E=[];if(l){et(r);let h=O=>{r.write(`event: ${String(O.type??"message")}
|
|
3
|
-
data: ${JSON.stringify(
|
|
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")}
|
|
3
|
+
data: ${JSON.stringify(I)}
|
|
4
4
|
|
|
5
|
-
`)},
|
|
5
|
+
`)},F=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,j="",Q=I=>{z&&(z=!1,g({type:"response.output_text.done",item_id:G,output_index:N,content_index:0,text:j}),g({type:"response.content_part.done",item_id:G,output_index:N,content_index:0,part:{type:"output_text",text:j}}),g({type:"response.output_item.done",output_index:N,item:{id:G,type:"message",role:"assistant",status:I,content:[{type:"output_text",text:j}]}}))},ne=new we,$=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(F(I));continue}if(y==="response.output_item.added"){Y=!0,g(F(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:""}})),j+=String(I.delta??""),g({type:y,item_id:G,output_index:N,content_index:0,delta:I.delta});continue}let L=Y?null:Ie(I);if(L){if(D(),te(),Q("completed"),ne.add(L),L.tool_index!==ce){pe("completed"),ce=L.tool_index;let C=_++;$={fcId:`fc_${l.slice(5)}_${L.tool_index}`,outputIndex:C,callId:L.call_id,name:L.name,args:""},g({type:"response.output_item.added",output_index:C,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 C=Oe(I.response),R=xe(h,ne.size+C.length,j);if(R){fe=!0,g({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:be(p,R)}});break}te(),Q("completed"),pe("completed"),ne.size===0&&C.forEach(se=>{let he=_++,ge=se.id??se.call_id??`fc_${he}`,Re=se.arguments??"",Z={id:ge,type:"function_call",call_id:se.call_id??ge,name:se.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:Re}),g({type:"response.function_call_arguments.done",item_id:ge,output_index:he,arguments:Re}),g({type:"response.output_item.done",output_index:he,item:{...Z,arguments:Re,status:"completed"}})}),g(F(I));continue}g(F(I))}te(),Q("incomplete"),pe("incomplete"),d&&!fe&&e.remember(l,a,Pt(A,ye(A))),r.write(`data: [DONE]
|
|
6
6
|
|
|
7
|
-
`),r.end();return}let U=null;for await(let
|
|
7
|
+
`),r.end();return}let U=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"&&(U=g.response)}if(U==null){le(r,502,"upstream produced no response.completed event","upstream_error");return}let P=Pt(A,U),T=xe(h,Oe(U).length,P);if(T){le(r,502,be(p,T),"upstream_error");return}d&&e.remember(l,a,P),ue(r,200,{...U,id:l})}async function zn(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"),a=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,l;try{l=Jn(o)}catch(_){if(_ instanceof Le){le(e,400,_.message);return}throw _}let d=ot(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:Gn(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,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){rt(e,"openai",_);return}throw _}if(t.stream===!0){nt(e);let _=[],D=new we,ee="";e.write(`data: ${JSON.stringify(ke(a,u,{role:"assistant"},null))}
|
|
8
8
|
|
|
9
|
-
`);for await(let N of r.track(
|
|
9
|
+
`);for await(let N of r.track(h,d)){_.push(N);let j=Ie(N);if(N.type==="response.output_text.delta"&&typeof N.delta=="string")ee+=N.delta,e.write(`data: ${JSON.stringify(ke(a,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(ke(a,
|
|
11
|
+
`);else if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")e.write(`data: ${JSON.stringify(ke(a,u,{reasoning_content:N.delta},null))}
|
|
12
12
|
|
|
13
|
-
`);else if(j){let{call:
|
|
13
|
+
`);else if(j){let{call:Q,isNew:ne}=D.add(j),$=ne?{index:j.tool_index,id:Q.id??`call_${j.tool_index}`,type:"function",function:{name:Q.name??"",arguments:j.delta}}:{index:j.tool_index,function:{arguments:j.delta}};e.write(`data: ${JSON.stringify(ke(a,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
|
|
17
|
+
`),e.end();return}}let J=Qe(ye(_)),X=xe(p,D.size+J.length,ee);if(X){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:be(d,X)}})}
|
|
18
18
|
|
|
19
|
-
`),e.end();return}D.size===0&&
|
|
19
|
+
`),e.end();return}D.size===0&&J.length>0&&e.write(`data: ${JSON.stringify(ke(a,u,{tool_calls:J},null))}
|
|
20
20
|
|
|
21
|
-
`);let te=D.size>0||
|
|
21
|
+
`);let te=D.size>0||J.length>0;e.write(`data: ${JSON.stringify(ke(a,u,{},te?"tool_calls":"stop"))}
|
|
22
22
|
|
|
23
|
-
`)
|
|
23
|
+
`),$e(ye(_))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Tt(ye(_))})}
|
|
24
24
|
|
|
25
25
|
`),e.write(`data: [DONE]
|
|
26
26
|
|
|
27
|
-
`),e.end();return}let
|
|
28
|
-
data: ${JSON.stringify({type:
|
|
27
|
+
`),e.end();return}let x="",A="",U=[],P=new we;for await(let _ of r.track(h,d)){U.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(x+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(A+=_.delta);let D=Ie(_);if(D&&P.add(D),_.type==="error"){le(e,502,JSON.stringify(_),"upstream_error");return}}let T=ye(U),g=Qe(T),F=g.length>0?g:Qe({output:P.items()}),G=xe(p,F.length,x);if(G){le(e,502,be(d,G),"upstream_error");return}let K=F.map(({index:_,...D})=>D),W={role:"assistant",content:x||null},Y=A||Ct(T);Y&&(W.reasoning_content=Y),K.length>0&&(W.tool_calls=K),ue(e,200,{id:a,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:Tt(T)})}function Kn(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var Te=class extends Error{};function De(t){return new Te(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Yn(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 Xn(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 Te(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function Qn(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw De(typeof t);let n="";for(let e of t){let r=String(e.type??"");if(r!=="text")throw De(`tool_result > ${r}`);n+=String(e.text??"")}return n}function Zn(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 De(typeof e);let r=[],o="",u=()=>{o&&(r.push({role:n,content:o}),o="")};for(let a of e){let l=String(a.type??"");if(l==="text")o+=String(a.text??"");else if(l==="tool_use")u(),r.push({type:"function_call",call_id:a.id,name:a.name,arguments:JSON.stringify(a.input??{})});else if(l==="tool_result")u(),r.push({type:"function_call_output",call_id:a.tool_use_id,output:Qn(a.content)});else{if(l==="thinking"||l==="redacted_thinking")continue;throw De(l)}}return u(),r}function Ze(t){return Oe(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 er(t,n,e,r){let o=t.messages;if(!Array.isArray(o)){ae(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){ae(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ae(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"))){ae(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=`msg_${Math.random().toString(36).slice(2,14)}`,l=[],d;try{t.system&&l.push({role:"system",content:Kn(t.system)});for(let _ of o)l.push(...Zn(_));d=Xn(t.tool_choice)}catch(_){if(_ instanceof Te){ae(e,400,"invalid_request_error",_.message);return}throw _}let p=ot(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:Yn(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){rt(e,"anthropic",_);return}throw _}let A=(_,D)=>{e.destroyed||e.write(`event: ${_}
|
|
28
|
+
data: ${JSON.stringify({type:_,...D})}
|
|
29
29
|
|
|
30
|
-
`)};if(t.stream===!0){let
|
|
31
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
30
|
+
`)};if(t.stream===!0){let _=r.track(x,p);nt(e),A("message_start",{message:{id:a,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,j=new we,Q=[],ne=()=>{X!=="none"&&(X="none",A("content_block_stop",{index:z}))},$=(C,R)=>{ne(),X=C,z=J++,A("content_block_start",{index:z,content_block:R})};for await(let C of _){if(e.destroyed)break;Q.push(C);let R=Ie(C);if(C.type==="response.reasoning_text.delta"&&typeof C.delta=="string")te()!=="thinking"&&$("thinking",{type:"thinking",thinking:""}),A("content_block_delta",{index:z,delta:{type:"thinking_delta",thinking:C.delta}});else if(C.type==="response.output_text.delta"&&typeof C.delta=="string")te()!=="text"&&$("text",{type:"text",text:""}),D+=1,ee+=C.delta,A("content_block_delta",{index:z,delta:{type:"text_delta",text:C.delta}});else if(R){let{call:se}=j.add(R);(te()!=="tool"||R.tool_index!==N)&&(N=R.tool_index,$("tool",{type:"tool_use",id:se.id??`call_${R.tool_index}`,name:se.name??"",input:{}})),R.delta&&A("content_block_delta",{index:z,delta:{type:"input_json_delta",partial_json:R.delta}})}else if(C.type==="error"){A("error",{error:{type:"api_error",message:JSON.stringify(C)}}),e.end();return}}if(e.destroyed)return;let ce=ye(Q),pe=Oe(ce),fe=xe(h,j.size+pe.length,ee);if(fe){A("error",{error:{type:"api_error",message:be(p,fe)}}),e.end();return}ne();let I=[];if(j.size===0)try{I=Ze(ce)}catch(C){A("error",{error:{type:"api_error",message:String(C instanceof Error?C.message:C)}}),e.end();return}J===0&&I.length===0&&($("text",{type:"text",text:""}),ne()),I.forEach(C=>{let R=J++;A("content_block_start",{index:R,content_block:{...C,input:{}}}),A("content_block_delta",{index:R,delta:{type:"input_json_delta",partial_json:JSON.stringify(C.input??{})}}),A("content_block_stop",{index:R})});let y=j.size>0||I.length>0,L=$e(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 U="",P="",T=[],g=new we;for await(let _ of r.track(x,p)){T.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(U+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(P+=_.delta);let D=Ie(_);if(D&&g.add(D),_.type==="error"){ae(e,502,"api_error",JSON.stringify(_));return}if(e.destroyed)break}if(e.destroyed)return;let F=ye(T),G;try{G=Ze(F),G.length===0&&g.size>0&&(G=Ze({output:g.items()}))}catch(_){ae(e,502,"api_error",String(_ instanceof Error?_.message:_));return}let K=xe(h,G.length,U);if(K){ae(e,502,"api_error",be(p,K));return}let W=[],Y=P||Ct(F);Y&&W.push({type:"thinking",thinking:Y}),(U||G.length===0)&&W.push({type:"text",text:U}),W.push(...G),ue(e,200,{id:a,type:"message",role:"assistant",content:W,model:u,stop_reason:G.length>0?"tool_use":"end_turn",usage:$e(F)??{input_tokens:0,output_tokens:0}})}function Ut(t){let{clients:n,apiKey:e,identity:r,statusOf:o}=t,u=typeof n=="function"?n:()=>n,a=new WeakMap,l=p=>{let h=a.get(p);return h||(h=new tt,a.set(p,h)),h},d=new et;return(p,h)=>{let x=new URL(p.url??"/","http://localhost"),A=x.pathname==="/v1/messages"||x.pathname.startsWith("/v1/messages/"),U=(P,T,g,F)=>A?ae(h,P,F,T):le(h,P,T,g);(async()=>{if(p.method==="GET"&&x.pathname==="/healthz"){ue(h,200,{ok:!0});return}if(p.method==="GET"&&x.pathname==="/stats"){ue(h,200,r?{identity:r,...d.snapshot()}:d.snapshot());return}if(e&&(p.headers.authorization??"")!==`Bearer ${e}`){U(401,"invalid local proxy api key","authentication_error","authentication_error");return}let P=await u(p);if(p.method==="GET"&&x.pathname==="/v1/models"){ue(h,200,await P.listModels());return}if(p.method!=="POST"){U(404,`no route for ${p.method} ${x.pathname}`,"invalid_request_error","not_found_error");return}let T;try{T=await jn(p)}catch(F){if(F instanceof Ne){U(413,F.message,"request_too_large","request_too_large");return}U(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=Buffer.byteLength(JSON.stringify(T));if(x.pathname==="/v1/responses"){d.request("responses",g,g),await Wn(T,P,l(P),h,d);return}if(x.pathname==="/v1/chat/completions"){d.request("chat_completions",g,g),await zn(T,P,h,d);return}if(x.pathname==="/v1/messages"){d.request("messages",g,g),await er(T,P,h,d);return}if(x.pathname==="/v1/messages/count_tokens"){d.request("count_tokens",g,g),ae(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}U(404,`no route for POST ${x.pathname}`,"invalid_request_error","not_found_error")})().catch(P=>{let T=String(P instanceof Error?P.message:P);if(!h.headersSent){let g=o?.(P)??null;if(g){U(g.status,T,g.openaiType,g.anthropicType);return}U(500,T,"proxy_error","api_error");return}h.destroyed||(A?h.write(`event: error
|
|
31
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:T}})}
|
|
32
32
|
|
|
33
|
-
`):
|
|
33
|
+
`):h.write(`data: ${JSON.stringify({error:{message:T,type:"upstream_error"}})}
|
|
34
34
|
|
|
35
|
-
`)),k.end()})}}S();var je=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 Tt(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 Kn=60,Yn=6e4,Xn=4096;function Zn(t){return t===401||t===403}var De=class{constructor(n){this.opts=n;this.mint=n.mint??je.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<Yn)return{apiKey:n,orgId:e.orgId};let r;try{r=(await this.mint(n,{baseUrl:this.opts.gatewayUrl,expiresIn:Kn})).orgId}catch(o){throw o instanceof je.ClientTokenError&&Zn(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>=Xn){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 Ht=require("crypto");S();var Te=require("@urun-sh/core");S();async function Ct(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 Ut(t,n,e,r){let o=t.response??{},l={request_id:e,consumer_id:r,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(l.instructions=o.instructions),Array.isArray(o.modalities)&&(l.modalities=o.modalities),typeof o.temperature=="number"&&(l.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(l.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(l.tools=o.tools),l}function Mt(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 Nt(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 Qn="llm-resp";async function*rt(t,n){let e=`${Qn}:${n}`,r=`resp_${n}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;for await(let l of t.stream(e).messages()){let a=l;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 c of a.tool_calls){let p=typeof c.index=="number"?c.index:0,d=o.get(p)??{};c.id&&(d.id=c.id),c.function?.name&&(d.name=c.function.name),o.set(p,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${p}`,tool_index:p,call_id:d.id,name:d.name,delta:c.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 Nt(a);return}}}var er="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(er).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,e){let r=Mt(n,e,this.consumerId);return this.write(r),rt(this.session,e)}sendResponseCreate(n,e,r){let o=Ut(n,e,r,this.consumerId);return this.write(o),rt(this.session,r)}};var $t=0;function tr(){return $t+=1,`req_${Date.now().toString(36)}_${$t.toString(36)}`}var Ge=class{transport;constructor(n){this.transport=new Be(n)}responses={create:async n=>{let e=tr(),r=this.transport.sendResponses(n,e);return Object.assign((async function*(){yield*r})(),{requestId:e})}}};S();function nr(t){let n=t?.type;return n==="response.created"||n==="response.in_progress"}function rr(t){let n=t?.type;return n==="response.completed"||n==="error"}function Lt(t){return async function(e){return(async function*(){for(let o=1;o<=2;o++){let{app:l,entry:a}=await t.sessionFor(e.model),c=!1,p=!1;try{let d=await t.createStream(a,e);for await(let k of d){if(rr(k)&&(c=!0),nr(k)){if(o>1)continue}else p=!0;yield k}}catch(d){if(o<2&&!p){await t.evict(l,a);continue}throw d}if(c)return;if(o<2&&!p){await t.evict(l,a);continue}return}})()}}S();var or=3,sr="llm",ir=new Set(["ended","expired","error"]);function Dt(t,n){let e=t.doc(sr),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 l=null,a=new Set,c=[],p=d=>{if(!l){l=d;for(let k of[...a])k(d);a.clear()}};return r&&c.push(e.onConnectionState(d=>{d.consecutiveFailures<or||p(new ie(`the pooled session for app "${n}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.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&&c.push(t.onPhase(d=>{ir.has(d.name)&&p(new ie(`the pooled session for app "${n}" is gone: it reached terminal phase "${d.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>l,onGone(d){return l?(d(l),()=>{}):(a.add(d),()=>a.delete(d))},dispose(){a.clear();for(let d of c.splice(0))d()}}}async function*ot(t,n){let e=n.gone();if(e)throw e;let r=t[Symbol.asyncIterator](),o,l=new Promise((a,c)=>{o=n.onGone(p=>c(p))});l.catch(()=>{});try{for(;;){let a=await Promise.race([r.next(),l]);if(a.done)return;yield a.value}}finally{o?.(),r.return?.(void 0)}}function jt(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 ar(t,n){let{baseUrl:e,orgId:r,fnName:o,auth:l,subject:a}=t,c=b=>({session:b,responses:new Ge(b),gone:Dt(b,n)});if(l.lane==="jwt"){let b=(0,Te.App)(n,{baseUrl:e,orgId:r,jwt:l.jwt});return c(jt(b,n,o))}let{apiKey:p,gatewayUrl:d}=l,k=(0,Te.App)(n,{baseUrl:e,orgId:r,getAccessToken:async()=>(await(0,Te.createClientToken)(p,{baseUrl:d,expiresIn:300,allowedFunctions:[`${n}/${o}`],...a===void 0?{}:{subject:a}})).token});return c(jt(k,n,o))}function ur(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 lr=new Set(["error","ended","expired"]);function Bt(t){let{auth:n,catalog:e}=t,r=null,o=a=>{let c=ar(t,a);return c.gone.onGone(()=>{r?.evict(a,c)}),c},l=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"?()=>yt({apiUrl:t.apiUrl,apiKey:n.apiKey}):null,listCatalog:e?()=>Ct(e):null,sessionKey:ur});return r=l,t.defaultApp!==null&&l.seed(t.defaultApp,o(t.defaultApp)),l}function Gt(t,n=At){let e=new WeakMap,r=new WeakMap;return{createResponse:Lt({sessionFor:o=>t.sessionFor(o),evict:(o,l)=>t.evict(o,l),createStream:async(o,l)=>ot(await o.responses.responses.create(l),o.gone)}),listModels:()=>t.modelList(),openAudio:async o=>{let{entry:l}=await t.sessionFor(o),a=e.get(l);return a||(a=(async()=>bt(l.session,await n()))(),e.set(l,a),a.catch(()=>e.delete(l))),a},openVideo:async o=>{let{entry:l}=await t.sessionFor(o),a=r.get(l);return a||(a=St(l.session),r.set(l,a)),a},sessionHandle:async o=>(await t.handleFor(o)).handle,createResponseOn:async(o,l)=>{let{entry:a}=await t.sessionForHandle(o);return ot(await a.responses.responses.create(l),a.gone)},onSessionEnd:async(o,l)=>{let{entry:a}=await t.sessionForHandle(o),c=a.session;if(typeof c.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let p=!1;return c.onPhase(d=>{if(p||!lr.has(d.name))return;p=!0;let k=c.endsAt??null;l({timeLeftMs:k?Math.max(0,k.getTime()-Date.now()):null,reason:d.name==="expired"?"session reached its maximum length":`session ${d.name}`})})}}}var cr=512;function dr(t){return`urun-inference-proxy-${(0,Ht.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var He=class{constructor(n){this.opts=n}opts;tenants=new Map;build(n){if(this.opts.build)return this.opts.build(n);let e=Bt({baseUrl:this.opts.baseUrl,orgId:n.orgId,defaultApp:null,fnName:_t,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:n.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:dr(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>=cr;){let o=this.tenants.entries().next();if(o.done)break;let[l,a]=o.value;this.tenants.delete(l),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 pr=5e3,fr=3e3,mr="/api/client-tokens";function st(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function Ft(t,n,e,r){st(t,n,{error:{message:e,type:r}})}async function hr(t,n=fetch){let e=`${t.replace(/\/+$/,"")}${mr}`;try{let r=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(fr)});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 Jt(t){let n=t.resolver??new De({gatewayUrl:t.baseUrl}),e=t.registry??new He({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>hr(t.baseUrl)),o=async p=>n.resolve(Tt(p.headers.authorization)),l=Pt({clients:async p=>e.clientsFor(await o(p)),statusOf:p=>p instanceof me?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof Se?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null}),a=null;return{server:(0,qt.createServer)((p,d)=>{let k=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&k.pathname==="/healthz"){st(d,200,{ok:!0});return}if(p.method==="GET"&&k.pathname==="/readyz"){let b=Date.now();if(!a||b-a.at>=pr){let E=await r();a={at:b,...E}}st(d,a.ready?200:503,{ok:a.ready,control_plane:a.detail});return}if(k.pathname!=="/v1"&&!k.pathname.startsWith("/v1/")){Ft(d,404,`no route for ${p.method} ${k.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface plus /healthz and /readyz`,"invalid_request_error");return}l(p,d)})().catch(b=>{if(!d.headersSent){Ft(d,500,String(b instanceof Error?b.message:b),"proxy_error");return}d.end()})}),closeAll:()=>e.closeAll()}}async function Vt(t,n){let e=new Promise(r=>t.close(()=>r()));t.closeAllConnections(),await e,await n()}async function gr(){let t=vt(de.default.env),{server:n,closeAll:e}=Jt(t);await new Promise((o,l)=>{n.once("error",l),n.listen(t.port,ze,o)}),de.default.stdout.write(`inference-proxy listening on http://${ze}:${t.port}/v1 (control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
|
|
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(["ended","expired","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}" is gone: it reached terminal phase "${p.name}". The entry is evicted; retry to get a fresh session.`))})),{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","ended","expired"]);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.name==="expired"?"session reached its maximum length":`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"})
|
|
36
36
|
`);let r=async o=>{de.default.stdout.write(`inference-proxy: ${o} \u2014 draining
|
|
37
|
-
`),await
|
|
37
|
+
`),await Kt(n,e)};await new Promise(o=>{de.default.once("SIGINT",()=>{r("SIGINT").finally(o)}),de.default.once("SIGTERM",()=>{r("SIGTERM").finally(o)})})}br().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-3ED25N7E.js";import"../chunk-XHRPJIEK.js";import"../chunk-F2TEK34X.js";import"../chunk-VG3X2LVG.js";import"../chunk-35LB5OHI.js";import"../chunk-EFBD3CGZ.js";import"../chunk-XHIIEA6Z.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-ZW6ENXZY.js";import"../chunk-54VWZJU7.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"})
|
|
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)});
|