@urun-sh/openai 0.6.17 → 0.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3U7YQ7LE.js +62 -0
- package/dist/chunk-MLJ66LPI.js +1 -0
- package/dist/chunk-NYSZ3RGB.js +4 -0
- package/dist/chunk-O4TKY7NE.js +7 -0
- package/dist/hosted/bin.cjs +31 -31
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +32 -32
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +33 -33
- package/dist/proxy/cli.cjs +38 -38
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +25 -25
- package/dist/proxy/index.d.cts +89 -5
- package/dist/proxy/index.d.ts +18 -4
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-Dd-h46sQ.d.cts → responses-turn-B91w2YKn.d.cts} +125 -25
- package/dist/{responses-turn-B0zlsQGn.d.ts → responses-turn-FcEDaymF.d.ts} +18 -12
- package/package.json +2 -2
- package/dist/chunk-6SN4EJ7Q.js +0 -7
- package/dist/chunk-TMQJY56F.js +0 -4
- package/dist/chunk-U7EJSC2N.js +0 -62
- package/dist/chunk-VRCCLQ5P.js +0 -1
package/dist/hosted/bin.cjs
CHANGED
|
@@ -1,74 +1,74 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var ga=Object.create;var fo=Object.defineProperty;var ya=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var _a=Object.getPrototypeOf,va=Object.prototype.hasOwnProperty;var ba=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ka=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Sa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wa(e))!va.call(t,o)&&o!==n&&fo(t,o,{get:()=>e[o],enumerable:!(r=ya(e,o))||r.enumerable});return t};var Ye=(t,e,n)=>(n=t!=null?ga(_a(t)):{},Sa(e||!t||!t.__esModule?fo(n,"default",{value:t,enumerable:!0}):n,t));var k=ba(()=>{"use strict"});var ho=ka(()=>{"use strict";k();var mo;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,d){return function(l,p){Object.defineProperty(u,l,{configurable:!0,writable:!0,value:p}),d&&d(l,p)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!a&&!u,l={create:a?function(){return nr(Object.create(null))}:u?function(){return nr({__proto__:null})}:function(){return nr({})},has:d?function(f,h){return r.call(f,h)}:function(f,h){return h in f},get:d?function(f,h){return r.call(f,h)?f[h]:void 0}:function(f,h){return f[h]}},p=Object.getPrototypeOf(Function),y=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ca(),c=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:pa(),m=typeof WeakMap=="function"?WeakMap:fa(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,R=ua(),g=da(R);function v(f,h,_,E){if(O(_)){if(!St(f))throw new TypeError;if(!so(h))throw new TypeError;return Y(f,h)}else{if(!St(f))throw new TypeError;if(!B(h))throw new TypeError;if(!B(E)&&!O(E)&&!X(E))throw new TypeError;return X(E)&&(E=void 0),_=be(_),de(f,h,_,E)}}e("decorate",v);function b(f,h){function _(E,N){if(!B(E))throw new TypeError;if(!O(N)&&!ia(N))throw new TypeError;te(f,h,E,N)}return _}e("metadata",b);function L(f,h,_,E){if(!B(_))throw new TypeError;return O(E)||(E=be(E)),te(f,h,_,E)}e("defineMetadata",L);function S(f,h,_){if(!B(h))throw new TypeError;return O(_)||(_=be(_)),ge(f,h,_)}e("hasMetadata",S);function x(f,h,_){if(!B(h))throw new TypeError;return O(_)||(_=be(_)),ve(f,h,_)}e("hasOwnMetadata",x);function C(f,h,_){if(!B(h))throw new TypeError;return O(_)||(_=be(_)),Ie(f,h,_)}e("getMetadata",C);function J(f,h,_){if(!B(h))throw new TypeError;return O(_)||(_=be(_)),ee(f,h,_)}e("getOwnMetadata",J);function I(f,h){if(!B(f))throw new TypeError;return O(h)||(h=be(h)),le(f,h)}e("getMetadataKeys",I);function M(f,h){if(!B(f))throw new TypeError;return O(h)||(h=be(h)),Me(f,h)}e("getOwnMetadataKeys",M);function G(f,h,_){if(!B(h))throw new TypeError;if(O(_)||(_=be(_)),!B(h))throw new TypeError;O(_)||(_=be(_));var E=Rt(h,_,!1);return O(E)?!1:E.OrdinaryDeleteMetadata(f,h,_)}e("deleteMetadata",G);function Y(f,h){for(var _=f.length-1;_>=0;--_){var E=f[_],N=E(h);if(!O(N)&&!X(N)){if(!so(N))throw new TypeError;h=N}}return h}function de(f,h,_,E){for(var N=f.length-1;N>=0;--N){var oe=f[N],ce=oe(h,_,E);if(!O(ce)&&!X(ce)){if(!B(ce))throw new TypeError;E=ce}}return E}function ge(f,h,_){var E=ve(f,h,_);if(E)return!0;var N=tr(h);return X(N)?!1:ge(f,N,_)}function ve(f,h,_){var E=Rt(h,_,!1);return O(E)?!1:Be(E.OrdinaryHasOwnMetadata(f,h,_))}function Ie(f,h,_){var E=ve(f,h,_);if(E)return ee(f,h,_);var N=tr(h);if(!X(N))return Ie(f,N,_)}function ee(f,h,_){var E=Rt(h,_,!1);if(!O(E))return E.OrdinaryGetOwnMetadata(f,h,_)}function te(f,h,_,E){var N=Rt(_,E,!0);N.OrdinaryDefineOwnMetadata(f,h,_,E)}function le(f,h){var _=Me(f,h),E=tr(f);if(E===null)return _;var N=le(E,h);if(N.length<=0)return _;if(_.length<=0)return N;for(var oe=new c,ce=[],V=0,T=_;V<T.length;V++){var P=T[V],$=oe.has(P);$||(oe.add(P),ce.push(P))}for(var U=0,W=N;U<W.length;U++){var P=W[U],$=oe.has(P);$||(oe.add(P),ce.push(P))}return ce}function Me(f,h){var _=Rt(f,h,!1);return _?_.OrdinaryOwnMetadataKeys(f,h):[]}function H(f){if(f===null)return 1;switch(typeof f){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return f===null?1:6;default:return 6}}function O(f){return f===void 0}function X(f){return f===null}function Te(f){return typeof f=="symbol"}function B(f){return typeof f=="object"?f!==null:typeof f=="function"}function he(f,h){switch(H(f)){case 0:return f;case 1:return f;case 2:return f;case 3:return f;case 4:return f;case 5:return f}var _=h===3?"string":h===5?"number":"default",E=io(f,s);if(E!==void 0){var N=E.call(f,_);if(B(N))throw new TypeError;return N}return $e(f,_==="default"?"number":_)}function $e(f,h){if(h==="string"){var _=f.toString;if(je(_)){var E=_.call(f);if(!B(E))return E}var N=f.valueOf;if(je(N)){var E=N.call(f);if(!B(E))return E}}else{var N=f.valueOf;if(je(N)){var E=N.call(f);if(!B(E))return E}var oe=f.toString;if(je(oe)){var E=oe.call(f);if(!B(E))return E}}throw new TypeError}function Be(f){return!!f}function lt(f){return""+f}function be(f){var h=he(f,3);return Te(h)?h:lt(h)}function St(f){return Array.isArray?Array.isArray(f):f instanceof Object?f instanceof Array:Object.prototype.toString.call(f)==="[object Array]"}function je(f){return typeof f=="function"}function so(f){return typeof f=="function"}function ia(f){switch(H(f)){case 3:return!0;case 4:return!0;default:return!1}}function er(f,h){return f===h||f!==f&&h!==h}function io(f,h){var _=f[h];if(_!=null){if(!je(_))throw new TypeError;return _}}function ao(f){var h=io(f,i);if(!je(h))throw new TypeError;var _=h.call(f);if(!B(_))throw new TypeError;return _}function uo(f){return f.value}function lo(f){var h=f.next();return h.done?!1:h}function co(f){var h=f.return;h&&h.call(f)}function tr(f){var h=Object.getPrototypeOf(f);if(typeof f!="function"||f===p||h!==p)return h;var _=f.prototype,E=_&&Object.getPrototypeOf(_);if(E==null||E===Object.prototype)return h;var N=E.constructor;return typeof N!="function"||N===f?h:N}function aa(){var f;!O(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(f=la(n.Reflect));var h,_,E,N=new m,oe={registerProvider:ce,getProvider:T,setProvider:$};return oe;function ce(U){if(!Object.isExtensible(oe))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case f===U:break;case O(h):h=U;break;case h===U:break;case O(_):_=U;break;case _===U:break;default:E===void 0&&(E=new c),E.add(U);break}}function V(U,W){if(!O(h)){if(h.isProviderFor(U,W))return h;if(!O(_)){if(_.isProviderFor(U,W))return h;if(!O(E))for(var Q=ao(E);;){var se=lo(Q);if(!se)return;var Pe=uo(se);if(Pe.isProviderFor(U,W))return co(Q),Pe}}}if(!O(f)&&f.isProviderFor(U,W))return f}function T(U,W){var Q=N.get(U),se;return O(Q)||(se=Q.get(W)),O(se)&&(se=V(U,W),O(se)||(O(Q)&&(Q=new y,N.set(U,Q)),Q.set(W,se))),se}function P(U){if(O(U))throw new TypeError;return h===U||_===U||!O(E)&&E.has(U)}function $(U,W,Q){if(!P(Q))throw new Error("Metadata provider not registered.");var se=T(U,W);if(se!==Q){if(!O(se))return!1;var Pe=N.get(U);O(Pe)&&(Pe=new y,N.set(U,Pe)),Pe.set(W,Q)}return!0}}function ua(){var f;return!O(w)&&B(n.Reflect)&&Object.isExtensible(n.Reflect)&&(f=n.Reflect[w]),O(f)&&(f=aa()),!O(w)&&B(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:f}),f}function da(f){var h=new m,_={isProviderFor:function(P,$){var U=h.get(P);return O(U)?!1:U.has($)},OrdinaryDefineOwnMetadata:ce,OrdinaryHasOwnMetadata:N,OrdinaryGetOwnMetadata:oe,OrdinaryOwnMetadataKeys:V,OrdinaryDeleteMetadata:T};return R.registerProvider(_),_;function E(P,$,U){var W=h.get(P),Q=!1;if(O(W)){if(!U)return;W=new y,h.set(P,W),Q=!0}var se=W.get($);if(O(se)){if(!U)return;if(se=new y,W.set($,se),!f.setProvider(P,$,_))throw W.delete($),Q&&h.delete(P),new Error("Wrong provider for target.")}return se}function N(P,$,U){var W=E($,U,!1);return O(W)?!1:Be(W.has(P))}function oe(P,$,U){var W=E($,U,!1);if(!O(W))return W.get(P)}function ce(P,$,U,W){var Q=E(U,W,!0);Q.set(P,$)}function V(P,$){var U=[],W=E(P,$,!1);if(O(W))return U;for(var Q=W.keys(),se=ao(Q),Pe=0;;){var po=lo(se);if(!po)return U.length=Pe,U;var ma=uo(po);try{U[Pe]=ma}catch(ha){try{co(se)}finally{throw ha}}Pe++}}function T(P,$,U){var W=E($,U,!1);if(O(W)||!W.delete(P))return!1;if(W.size===0){var Q=h.get($);O(Q)||(Q.delete(U),Q.size===0&&h.delete(Q))}return!0}}function la(f){var h=f.defineMetadata,_=f.hasOwnMetadata,E=f.getOwnMetadata,N=f.getOwnMetadataKeys,oe=f.deleteMetadata,ce=new m,V={isProviderFor:function(T,P){var $=ce.get(T);return!O($)&&$.has(P)?!0:N(T,P).length?(O($)&&($=new c,ce.set(T,$)),$.add(P),!0):!1},OrdinaryDefineOwnMetadata:h,OrdinaryHasOwnMetadata:_,OrdinaryGetOwnMetadata:E,OrdinaryOwnMetadataKeys:N,OrdinaryDeleteMetadata:oe};return V}function Rt(f,h,_){var E=R.getProvider(f,h);if(!O(E))return E;if(_){if(R.setProvider(f,h,g))return g;throw new Error("Illegal state.")}}function ca(){var f={},h=[],_=(function(){function V(T,P,$){this._index=0,this._keys=T,this._values=P,this._selector=$}return V.prototype["@@iterator"]=function(){return this},V.prototype[i]=function(){return this},V.prototype.next=function(){var T=this._index;if(T>=0&&T<this._keys.length){var P=this._selector(this._keys[T],this._values[T]);return T+1>=this._keys.length?(this._index=-1,this._keys=h,this._values=h):this._index++,{value:P,done:!1}}return{value:void 0,done:!0}},V.prototype.throw=function(T){throw this._index>=0&&(this._index=-1,this._keys=h,this._values=h),T},V.prototype.return=function(T){return this._index>=0&&(this._index=-1,this._keys=h,this._values=h),{value:T,done:!0}},V})(),E=(function(){function V(){this._keys=[],this._values=[],this._cacheKey=f,this._cacheIndex=-2}return Object.defineProperty(V.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),V.prototype.has=function(T){return this._find(T,!1)>=0},V.prototype.get=function(T){var P=this._find(T,!1);return P>=0?this._values[P]:void 0},V.prototype.set=function(T,P){var $=this._find(T,!0);return this._values[$]=P,this},V.prototype.delete=function(T){var P=this._find(T,!1);if(P>=0){for(var $=this._keys.length,U=P+1;U<$;U++)this._keys[U-1]=this._keys[U],this._values[U-1]=this._values[U];return this._keys.length--,this._values.length--,er(T,this._cacheKey)&&(this._cacheKey=f,this._cacheIndex=-2),!0}return!1},V.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=f,this._cacheIndex=-2},V.prototype.keys=function(){return new _(this._keys,this._values,N)},V.prototype.values=function(){return new _(this._keys,this._values,oe)},V.prototype.entries=function(){return new _(this._keys,this._values,ce)},V.prototype["@@iterator"]=function(){return this.entries()},V.prototype[i]=function(){return this.entries()},V.prototype._find=function(T,P){if(!er(this._cacheKey,T)){this._cacheIndex=-1;for(var $=0;$<this._keys.length;$++)if(er(this._keys[$],T)){this._cacheIndex=$;break}}return this._cacheIndex<0&&P&&(this._cacheIndex=this._keys.length,this._keys.push(T),this._values.push(void 0)),this._cacheIndex},V})();return E;function N(V,T){return V}function oe(V,T){return T}function ce(V,T){return[V,T]}}function pa(){var f=(function(){function h(){this._map=new y}return Object.defineProperty(h.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),h.prototype.has=function(_){return this._map.has(_)},h.prototype.add=function(_){return this._map.set(_,_),this},h.prototype.delete=function(_){return this._map.delete(_)},h.prototype.clear=function(){this._map.clear()},h.prototype.keys=function(){return this._map.keys()},h.prototype.values=function(){return this._map.keys()},h.prototype.entries=function(){return this._map.entries()},h.prototype["@@iterator"]=function(){return this.keys()},h.prototype[i]=function(){return this.keys()},h})();return f}function fa(){var f=16,h=l.create(),_=E();return(function(){function T(){this._key=E()}return T.prototype.has=function(P){var $=N(P,!1);return $!==void 0?l.has($,this._key):!1},T.prototype.get=function(P){var $=N(P,!1);return $!==void 0?l.get($,this._key):void 0},T.prototype.set=function(P,$){var U=N(P,!0);return U[this._key]=$,this},T.prototype.delete=function(P){var $=N(P,!1);return $!==void 0?delete $[this._key]:!1},T.prototype.clear=function(){this._key=E()},T})();function E(){var T;do T="@@WeakMap@@"+V();while(l.has(h,T));return h[T]=!0,T}function N(T,P){if(!r.call(T,_)){if(!P)return;Object.defineProperty(T,_,{value:l.create()})}return T[_]}function oe(T,P){for(var $=0;$<P;++$)T[$]=Math.random()*255|0;return T}function ce(T){if(typeof Uint8Array=="function"){var P=new Uint8Array(T);return typeof crypto<"u"?crypto.getRandomValues(P):typeof msCrypto<"u"?msCrypto.getRandomValues(P):oe(P,T),P}return oe(new Array(T),T)}function V(){var T=ce(f);T[6]=T[6]&79|64,T[8]=T[8]&191|128;for(var P="",$=0;$<f;++$){var U=T[$];($===4||$===6||$===8)&&(P+="-"),U<16&&(P+="0"),P+=U.toString(16).toLowerCase()}return P}}function nr(f){return f.__=void 0,delete f.__,f}})})(mo||(mo={}))});k();var wh=Ye(ho(),1),Ce=Ye(require("process"),1);k();var Ja=Ye(require("os"),1),Ka=Ye(require("path"),1),za=require("url"),Ya=require("util");k();k();var pe=class extends Error{},Ra=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function xa(t){if(typeof t!="string")return!1;let e=Ra.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function Ea(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new pe(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new pe(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new pe(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new pe(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let p of["model_id","variant","app_slug","function"])if(typeof d[p]!="string"||d[p].length===0)throw new pe(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${p}"`);let l=(p,y)=>{if(d[p]!==void 0&&d[p]!==null&&!y)throw new pe(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${p}": ${JSON.stringify(d[p])}`)};l("ready",typeof d.ready=="boolean"),l("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),l("ready_since",xa(d.ready_since));for(let p of["model_id","variant"]){let y=d[p];if(y.includes(":"))throw new pe(`catalog shared endpoints[${u}] has "${p}" containing ":" (${JSON.stringify(y)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return l("output_free",typeof d.output_free=="boolean"),d});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new pe(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new pe(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new pe(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function ct(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function go(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new pe(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function yo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new pe(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Ea(await r.json())}k();function He(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}k();var xe=class extends Error{name="ModelPriceError"},rr="per_million_input_tokens",or="per_million_output_tokens",_o="model_id,variant,unit,price_usd,effective_at,expires_at",wo={per_request:!0,per_minute:!0,per_output_unit:!0},Oa=5e3;function Aa(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new xe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function vo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new xe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ia(t,e,n){return t===null?null:vo(t,e,n)}function Ta(t,e){if(t===rr)return"input";if(t===or)return"output";if(typeof t=="string"&&Object.hasOwn(wo,t))return null;throw new xe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${rr} | ${or}) nor a known GPU-time unit (${Object.keys(wo).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Pa(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function sr(t,e){return`${t}\0${e}`}function Ca(t){if(!Array.isArray(t))throw new xe(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new xe(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of _o.split(","))if(!Object.hasOwn(s,d))throw new xe(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=Ta(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new xe(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new xe(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Aa(s.price_usd,o),effective_at:vo(s.effective_at,o,"effective_at"),expires_at:Ia(s.expires_at,o,"expires_at")})}return e}function bo(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let d=r.get(u.model_id);d||(d=new Map,r.set(u.model_id,d),o.set(u.model_id,new Map));let l=u.variant??"",p=d.get(l);p||(p={input:[],output:[]},d.set(l,p),o.get(u.model_id).set(l,u.variant)),p[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let l=d.get(""),p=(y,c,m)=>{let w=y&&y.length>0?y:l?.[c];if(!w||w.length===0)return null;let R=Pa(w,c);return"reason"in R?R:R.rate.usd===0?c==="output"&&m!==null&&n?.has(sr(u,m))?R.rate:{reason:`the ${c} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:R.rate};for(let[y,c]of o.get(u)){let m=d.get(y),w=p(m?.input,"input",c),R=p(m?.output,"output",c);if(w!==null&&"reason"in w){i.push({model_id:u,variant:c,reason:w.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:u,variant:c,reason:R.reason});continue}w===null||R===null||s.push({model_id:u,variant:c,pricing:{input:w.usd,output:R.usd}})}}let a=(u,d)=>u.model_id.localeCompare(d.model_id)||(u.variant===null?1:0)-(d.variant===null?1:0)||(u.variant??"").localeCompare(d.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function xt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Et={prices:[],refusals:[]};async function ko(t){let e=t.fetchImpl??fetch,n=`${rr},${or}`,r=await e(`${t.catalogUrl}/model_prices?select=${_o}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Oa)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Ca(await r.json())}k();var Ma={chat:!0,code:!0,agent:!0,vl:!0},So={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function $a(t){let e=t.toLowerCase();return Object.hasOwn(So,e)?So[e]:null}var Ro={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function La(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ro,o)?Ro[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Eo={2:"Llama2",3:"Llama3"};function Ua(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xo,s))return xo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Eo,i))return Eo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Na=["context_length","max_model_len"];function Da(t){let e=Na.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function zt(t){let e=t.map(Da),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Fa(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function ir(t){if(t.length===0)return null;let e=t.map(Fa),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ba(t,e){let n=e.filter(o=>He(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return Kt(n);let r=e.filter(o=>He(o.model_id)===t);return r.length>0?Kt(r):null}function Kt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ja(t),matches:t}:null}function ja(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Io(t){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function Yt(t,e,n){let r=Ba(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=zt(s),a=xt(o.model_id,o.variant,n),u=To(o,s),d=ir(s);return{id:t,object:"model",created:Io(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}}}var Ha=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function To(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...Ha],defect:o}:{published:[],defect:o}}function ar(t){let e=t.length>0?Kt(t):null;return e===null?{published:[],defect:null}:To(e.row,e.matches)}function Oo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ao(t){return{input:[{type:"prompt",unit:"token",cost_usd:Oo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Oo(t.output)}]}}function qa(t,e,n,r){if(e.length===0)return null;let o=Kt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ma[s.task]!==!0)return null;let a=zt(i),u=xt(s.model_id,s.variant,n),d=Ua(s.hf_repo),l={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(l.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Io(s),quantization:$a(s.variant),...d!==null?{tokenizer:d}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Ao(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...u?{pricing:Ao(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Po(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?ct(t):[];if(s.length>0){let d=s.filter(l=>l.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let l=d.map(p=>`${p.model_id}:${p.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${l} carry no ready field and are declared not ready`)}}let i={datacenters:La(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let l=`${d.model_id}:${d.variant}`;if(u.has(l))continue;u.add(l);let p=qa(d,e.filter(y=>y.model_id===d.model_id&&y.variant===d.variant),n,i);p&&a.push(p)}return{data:a}}var z=class extends Error{},fe=class extends Error{},dr="urs1.";function Co(t,e){return dr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ga(t){if(!t.startsWith(dr))return null;try{let e=JSON.parse(Buffer.from(t.slice(dr.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Uo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Mo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Wa(t);return e===null?[]:[e]}function ur(t,e,n,r,o){if(!o)throw new pe(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new pe(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new pe(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function $o(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new pe(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var No="shared:",Qe="speech:";function Ot(t){return t.sharedApp?No+t.appSlug:t.appSlug}function At(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Xe(t,e){let n=e.filter(s=>He(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>He(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Va(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Wa(t){let e=t.map(Va),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Lo={stt:"stt",tts:"tts"};function We(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Lo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Lo[e]:null}var Xt=6e4,Qt=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Xt;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Xt;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Xt;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Xt;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof xe)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
3
|
-
`),
|
|
4
|
-
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(
|
|
5
|
-
`);let u=(n?
|
|
6
|
-
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}k();var we=require("@prometheus-io/client"),
|
|
7
|
-
`}function
|
|
8
|
-
`)}function
|
|
2
|
+
"use strict";var xa=Object.create;var yo=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var Aa=Object.getPrototypeOf,Ia=Object.prototype.hasOwnProperty;var Ta=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Pa=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Ca=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oa(e))!Ia.call(t,o)&&o!==n&&yo(t,o,{get:()=>e[o],enumerable:!(r=Ea(e,o))||r.enumerable});return t};var Qe=(t,e,n)=>(n=t!=null?xa(Aa(t)):{},Ca(e||!t||!t.__esModule?yo(n,"default",{value:t,enumerable:!0}):n,t));var k=Ta(()=>{"use strict"});var _o=Pa(()=>{"use strict";k();var wo;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,d){return function(l,p){Object.defineProperty(u,l,{configurable:!0,writable:!0,value:p}),d&&d(l,p)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!a&&!u,l={create:a?function(){return ar(Object.create(null))}:u?function(){return ar({__proto__:null})}:function(){return ar({})},has:d?function(f,h){return r.call(f,h)}:function(f,h){return h in f},get:d?function(f,h){return r.call(f,h)?f[h]:void 0}:function(f,h){return f[h]}},p=Object.getPrototypeOf(Function),y=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:va(),c=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:ba(),m=typeof WeakMap=="function"?WeakMap:ka(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,S=ya(),g=wa(S);function v(f,h,_,E){if(O(_)){if(!Ot(f))throw new TypeError;if(!lo(h))throw new TypeError;return Y(f,h)}else{if(!Ot(f))throw new TypeError;if(!j(h))throw new TypeError;if(!j(E)&&!O(E)&&!X(E))throw new TypeError;return X(E)&&(E=void 0),_=be(_),de(f,h,_,E)}}e("decorate",v);function b(f,h){function _(E,D){if(!j(E))throw new TypeError;if(!O(D)&&!ha(D))throw new TypeError;te(f,h,E,D)}return _}e("metadata",b);function L(f,h,_,E){if(!j(_))throw new TypeError;return O(E)||(E=be(E)),te(f,h,_,E)}e("defineMetadata",L);function R(f,h,_){if(!j(h))throw new TypeError;return O(_)||(_=be(_)),ge(f,h,_)}e("hasMetadata",R);function x(f,h,_){if(!j(h))throw new TypeError;return O(_)||(_=be(_)),ve(f,h,_)}e("hasOwnMetadata",x);function C(f,h,_){if(!j(h))throw new TypeError;return O(_)||(_=be(_)),Ie(f,h,_)}e("getMetadata",C);function W(f,h,_){if(!j(h))throw new TypeError;return O(_)||(_=be(_)),ee(f,h,_)}e("getOwnMetadata",W);function I(f,h){if(!j(f))throw new TypeError;return O(h)||(h=be(h)),le(f,h)}e("getMetadataKeys",I);function M(f,h){if(!j(f))throw new TypeError;return O(h)||(h=be(h)),Me(f,h)}e("getOwnMetadataKeys",M);function G(f,h,_){if(!j(h))throw new TypeError;if(O(_)||(_=be(_)),!j(h))throw new TypeError;O(_)||(_=be(_));var E=At(h,_,!1);return O(E)?!1:E.OrdinaryDeleteMetadata(f,h,_)}e("deleteMetadata",G);function Y(f,h){for(var _=f.length-1;_>=0;--_){var E=f[_],D=E(h);if(!O(D)&&!X(D)){if(!lo(D))throw new TypeError;h=D}}return h}function de(f,h,_,E){for(var D=f.length-1;D>=0;--D){var oe=f[D],ce=oe(h,_,E);if(!O(ce)&&!X(ce)){if(!j(ce))throw new TypeError;E=ce}}return E}function ge(f,h,_){var E=ve(f,h,_);if(E)return!0;var D=ir(h);return X(D)?!1:ge(f,D,_)}function ve(f,h,_){var E=At(h,_,!1);return O(E)?!1:je(E.OrdinaryHasOwnMetadata(f,h,_))}function Ie(f,h,_){var E=ve(f,h,_);if(E)return ee(f,h,_);var D=ir(h);if(!X(D))return Ie(f,D,_)}function ee(f,h,_){var E=At(h,_,!1);if(!O(E))return E.OrdinaryGetOwnMetadata(f,h,_)}function te(f,h,_,E){var D=At(_,E,!0);D.OrdinaryDefineOwnMetadata(f,h,_,E)}function le(f,h){var _=Me(f,h),E=ir(f);if(E===null)return _;var D=le(E,h);if(D.length<=0)return _;if(_.length<=0)return D;for(var oe=new c,ce=[],V=0,T=_;V<T.length;V++){var P=T[V],$=oe.has(P);$||(oe.add(P),ce.push(P))}for(var N=0,J=D;N<J.length;N++){var P=J[N],$=oe.has(P);$||(oe.add(P),ce.push(P))}return ce}function Me(f,h){var _=At(f,h,!1);return _?_.OrdinaryOwnMetadataKeys(f,h):[]}function H(f){if(f===null)return 1;switch(typeof f){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return f===null?1:6;default:return 6}}function O(f){return f===void 0}function X(f){return f===null}function Te(f){return typeof f=="symbol"}function j(f){return typeof f=="object"?f!==null:typeof f=="function"}function he(f,h){switch(H(f)){case 0:return f;case 1:return f;case 2:return f;case 3:return f;case 4:return f;case 5:return f}var _=h===3?"string":h===5?"number":"default",E=co(f,s);if(E!==void 0){var D=E.call(f,_);if(j(D))throw new TypeError;return D}return $e(f,_==="default"?"number":_)}function $e(f,h){if(h==="string"){var _=f.toString;if(He(_)){var E=_.call(f);if(!j(E))return E}var D=f.valueOf;if(He(D)){var E=D.call(f);if(!j(E))return E}}else{var D=f.valueOf;if(He(D)){var E=D.call(f);if(!j(E))return E}var oe=f.toString;if(He(oe)){var E=oe.call(f);if(!j(E))return E}}throw new TypeError}function je(f){return!!f}function ft(f){return""+f}function be(f){var h=he(f,3);return Te(h)?h:ft(h)}function Ot(f){return Array.isArray?Array.isArray(f):f instanceof Object?f instanceof Array:Object.prototype.toString.call(f)==="[object Array]"}function He(f){return typeof f=="function"}function lo(f){return typeof f=="function"}function ha(f){switch(H(f)){case 3:return!0;case 4:return!0;default:return!1}}function sr(f,h){return f===h||f!==f&&h!==h}function co(f,h){var _=f[h];if(_!=null){if(!He(_))throw new TypeError;return _}}function po(f){var h=co(f,i);if(!He(h))throw new TypeError;var _=h.call(f);if(!j(_))throw new TypeError;return _}function fo(f){return f.value}function mo(f){var h=f.next();return h.done?!1:h}function ho(f){var h=f.return;h&&h.call(f)}function ir(f){var h=Object.getPrototypeOf(f);if(typeof f!="function"||f===p||h!==p)return h;var _=f.prototype,E=_&&Object.getPrototypeOf(_);if(E==null||E===Object.prototype)return h;var D=E.constructor;return typeof D!="function"||D===f?h:D}function ga(){var f;!O(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(f=_a(n.Reflect));var h,_,E,D=new m,oe={registerProvider:ce,getProvider:T,setProvider:$};return oe;function ce(N){if(!Object.isExtensible(oe))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case f===N:break;case O(h):h=N;break;case h===N:break;case O(_):_=N;break;case _===N:break;default:E===void 0&&(E=new c),E.add(N);break}}function V(N,J){if(!O(h)){if(h.isProviderFor(N,J))return h;if(!O(_)){if(_.isProviderFor(N,J))return h;if(!O(E))for(var Q=po(E);;){var se=mo(Q);if(!se)return;var Pe=fo(se);if(Pe.isProviderFor(N,J))return ho(Q),Pe}}}if(!O(f)&&f.isProviderFor(N,J))return f}function T(N,J){var Q=D.get(N),se;return O(Q)||(se=Q.get(J)),O(se)&&(se=V(N,J),O(se)||(O(Q)&&(Q=new y,D.set(N,Q)),Q.set(J,se))),se}function P(N){if(O(N))throw new TypeError;return h===N||_===N||!O(E)&&E.has(N)}function $(N,J,Q){if(!P(Q))throw new Error("Metadata provider not registered.");var se=T(N,J);if(se!==Q){if(!O(se))return!1;var Pe=D.get(N);O(Pe)&&(Pe=new y,D.set(N,Pe)),Pe.set(J,Q)}return!0}}function ya(){var f;return!O(w)&&j(n.Reflect)&&Object.isExtensible(n.Reflect)&&(f=n.Reflect[w]),O(f)&&(f=ga()),!O(w)&&j(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:f}),f}function wa(f){var h=new m,_={isProviderFor:function(P,$){var N=h.get(P);return O(N)?!1:N.has($)},OrdinaryDefineOwnMetadata:ce,OrdinaryHasOwnMetadata:D,OrdinaryGetOwnMetadata:oe,OrdinaryOwnMetadataKeys:V,OrdinaryDeleteMetadata:T};return S.registerProvider(_),_;function E(P,$,N){var J=h.get(P),Q=!1;if(O(J)){if(!N)return;J=new y,h.set(P,J),Q=!0}var se=J.get($);if(O(se)){if(!N)return;if(se=new y,J.set($,se),!f.setProvider(P,$,_))throw J.delete($),Q&&h.delete(P),new Error("Wrong provider for target.")}return se}function D(P,$,N){var J=E($,N,!1);return O(J)?!1:je(J.has(P))}function oe(P,$,N){var J=E($,N,!1);if(!O(J))return J.get(P)}function ce(P,$,N,J){var Q=E(N,J,!0);Q.set(P,$)}function V(P,$){var N=[],J=E(P,$,!1);if(O(J))return N;for(var Q=J.keys(),se=po(Q),Pe=0;;){var go=mo(se);if(!go)return N.length=Pe,N;var Sa=fo(go);try{N[Pe]=Sa}catch(Ra){try{ho(se)}finally{throw Ra}}Pe++}}function T(P,$,N){var J=E($,N,!1);if(O(J)||!J.delete(P))return!1;if(J.size===0){var Q=h.get($);O(Q)||(Q.delete(N),Q.size===0&&h.delete(Q))}return!0}}function _a(f){var h=f.defineMetadata,_=f.hasOwnMetadata,E=f.getOwnMetadata,D=f.getOwnMetadataKeys,oe=f.deleteMetadata,ce=new m,V={isProviderFor:function(T,P){var $=ce.get(T);return!O($)&&$.has(P)?!0:D(T,P).length?(O($)&&($=new c,ce.set(T,$)),$.add(P),!0):!1},OrdinaryDefineOwnMetadata:h,OrdinaryHasOwnMetadata:_,OrdinaryGetOwnMetadata:E,OrdinaryOwnMetadataKeys:D,OrdinaryDeleteMetadata:oe};return V}function At(f,h,_){var E=S.getProvider(f,h);if(!O(E))return E;if(_){if(S.setProvider(f,h,g))return g;throw new Error("Illegal state.")}}function va(){var f={},h=[],_=(function(){function V(T,P,$){this._index=0,this._keys=T,this._values=P,this._selector=$}return V.prototype["@@iterator"]=function(){return this},V.prototype[i]=function(){return this},V.prototype.next=function(){var T=this._index;if(T>=0&&T<this._keys.length){var P=this._selector(this._keys[T],this._values[T]);return T+1>=this._keys.length?(this._index=-1,this._keys=h,this._values=h):this._index++,{value:P,done:!1}}return{value:void 0,done:!0}},V.prototype.throw=function(T){throw this._index>=0&&(this._index=-1,this._keys=h,this._values=h),T},V.prototype.return=function(T){return this._index>=0&&(this._index=-1,this._keys=h,this._values=h),{value:T,done:!0}},V})(),E=(function(){function V(){this._keys=[],this._values=[],this._cacheKey=f,this._cacheIndex=-2}return Object.defineProperty(V.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),V.prototype.has=function(T){return this._find(T,!1)>=0},V.prototype.get=function(T){var P=this._find(T,!1);return P>=0?this._values[P]:void 0},V.prototype.set=function(T,P){var $=this._find(T,!0);return this._values[$]=P,this},V.prototype.delete=function(T){var P=this._find(T,!1);if(P>=0){for(var $=this._keys.length,N=P+1;N<$;N++)this._keys[N-1]=this._keys[N],this._values[N-1]=this._values[N];return this._keys.length--,this._values.length--,sr(T,this._cacheKey)&&(this._cacheKey=f,this._cacheIndex=-2),!0}return!1},V.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=f,this._cacheIndex=-2},V.prototype.keys=function(){return new _(this._keys,this._values,D)},V.prototype.values=function(){return new _(this._keys,this._values,oe)},V.prototype.entries=function(){return new _(this._keys,this._values,ce)},V.prototype["@@iterator"]=function(){return this.entries()},V.prototype[i]=function(){return this.entries()},V.prototype._find=function(T,P){if(!sr(this._cacheKey,T)){this._cacheIndex=-1;for(var $=0;$<this._keys.length;$++)if(sr(this._keys[$],T)){this._cacheIndex=$;break}}return this._cacheIndex<0&&P&&(this._cacheIndex=this._keys.length,this._keys.push(T),this._values.push(void 0)),this._cacheIndex},V})();return E;function D(V,T){return V}function oe(V,T){return T}function ce(V,T){return[V,T]}}function ba(){var f=(function(){function h(){this._map=new y}return Object.defineProperty(h.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),h.prototype.has=function(_){return this._map.has(_)},h.prototype.add=function(_){return this._map.set(_,_),this},h.prototype.delete=function(_){return this._map.delete(_)},h.prototype.clear=function(){this._map.clear()},h.prototype.keys=function(){return this._map.keys()},h.prototype.values=function(){return this._map.keys()},h.prototype.entries=function(){return this._map.entries()},h.prototype["@@iterator"]=function(){return this.keys()},h.prototype[i]=function(){return this.keys()},h})();return f}function ka(){var f=16,h=l.create(),_=E();return(function(){function T(){this._key=E()}return T.prototype.has=function(P){var $=D(P,!1);return $!==void 0?l.has($,this._key):!1},T.prototype.get=function(P){var $=D(P,!1);return $!==void 0?l.get($,this._key):void 0},T.prototype.set=function(P,$){var N=D(P,!0);return N[this._key]=$,this},T.prototype.delete=function(P){var $=D(P,!1);return $!==void 0?delete $[this._key]:!1},T.prototype.clear=function(){this._key=E()},T})();function E(){var T;do T="@@WeakMap@@"+V();while(l.has(h,T));return h[T]=!0,T}function D(T,P){if(!r.call(T,_)){if(!P)return;Object.defineProperty(T,_,{value:l.create()})}return T[_]}function oe(T,P){for(var $=0;$<P;++$)T[$]=Math.random()*255|0;return T}function ce(T){if(typeof Uint8Array=="function"){var P=new Uint8Array(T);return typeof crypto<"u"?crypto.getRandomValues(P):typeof msCrypto<"u"?msCrypto.getRandomValues(P):oe(P,T),P}return oe(new Array(T),T)}function V(){var T=ce(f);T[6]=T[6]&79|64,T[8]=T[8]&191|128;for(var P="",$=0;$<f;++$){var N=T[$];($===4||$===6||$===8)&&(P+="-"),N<16&&(P+="0"),P+=N.toString(16).toLowerCase()}return P}}function ar(f){return f.__=void 0,delete f.__,f}})})(wo||(wo={}))});k();var Dh=Qe(_o(),1),Ce=Qe(require("process"),1);k();var su=Qe(require("os"),1),iu=Qe(require("path"),1),au=require("url"),uu=require("util");k();k();var pe=class extends Error{},Ma=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function $a(t){if(typeof t!="string")return!1;let e=Ma.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function La(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new pe(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new pe(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new pe(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new pe(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let p of["model_id","variant","app_slug","function"])if(typeof d[p]!="string"||d[p].length===0)throw new pe(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${p}"`);let l=(p,y)=>{if(d[p]!==void 0&&d[p]!==null&&!y)throw new pe(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${p}": ${JSON.stringify(d[p])}`)};l("ready",typeof d.ready=="boolean"),l("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),l("ready_since",$a(d.ready_since));for(let p of["model_id","variant"]){let y=d[p];if(y.includes(":"))throw new pe(`catalog shared endpoints[${u}] has "${p}" containing ":" (${JSON.stringify(y)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return l("output_free",typeof d.output_free=="boolean"),d});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new pe(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new pe(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new pe(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function mt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function vo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new pe(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function bo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new pe(`catalog read failed: GET ${n} \u2192 ${r.status}`);return La(await r.json())}k();function qe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}k();var xe=class extends Error{name="ModelPriceError"},ur="per_million_input_tokens",dr="per_million_output_tokens",So="model_id,variant,unit,price_usd,effective_at,expires_at",ko={per_request:!0,per_minute:!0,per_output_unit:!0},Na=5e3;function Ua(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new xe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ro(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new xe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Da(t,e,n){return t===null?null:Ro(t,e,n)}function Fa(t,e){if(t===ur)return"input";if(t===dr)return"output";if(typeof t=="string"&&Object.hasOwn(ko,t))return null;throw new xe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${ur} | ${dr}) nor a known GPU-time unit (${Object.keys(ko).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Ba(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function lr(t,e){return`${t}\0${e}`}function ja(t){if(!Array.isArray(t))throw new xe(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new xe(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of So.split(","))if(!Object.hasOwn(s,d))throw new xe(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=Fa(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new xe(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new xe(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Ua(s.price_usd,o),effective_at:Ro(s.effective_at,o,"effective_at"),expires_at:Da(s.expires_at,o,"expires_at")})}return e}function xo(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let d=r.get(u.model_id);d||(d=new Map,r.set(u.model_id,d),o.set(u.model_id,new Map));let l=u.variant??"",p=d.get(l);p||(p={input:[],output:[]},d.set(l,p),o.get(u.model_id).set(l,u.variant)),p[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let l=d.get(""),p=(y,c,m)=>{let w=y&&y.length>0?y:l?.[c];if(!w||w.length===0)return null;let S=Ba(w,c);return"reason"in S?S:S.rate.usd===0?c==="output"&&m!==null&&n?.has(lr(u,m))?S.rate:{reason:`the ${c} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:S.rate};for(let[y,c]of o.get(u)){let m=d.get(y),w=p(m?.input,"input",c),S=p(m?.output,"output",c);if(w!==null&&"reason"in w){i.push({model_id:u,variant:c,reason:w.reason});continue}if(S!==null&&"reason"in S){i.push({model_id:u,variant:c,reason:S.reason});continue}w===null||S===null||s.push({model_id:u,variant:c,pricing:{input:w.usd,output:S.usd}})}}let a=(u,d)=>u.model_id.localeCompare(d.model_id)||(u.variant===null?1:0)-(d.variant===null?1:0)||(u.variant??"").localeCompare(d.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function It(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Tt={prices:[],refusals:[]};async function Eo(t){let e=t.fetchImpl??fetch,n=`${ur},${dr}`,r=await e(`${t.catalogUrl}/model_prices?select=${So}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Na)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ja(await r.json())}k();var et="/partners/openrouter/models",Ha={chat:!0,code:!0,agent:!0,vl:!0},Oo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function qa(t){let e=t.toLowerCase();return Object.hasOwn(Oo,e)?Oo[e]:null}var Ao={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Ga(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ao,o)?Ao[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Io={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},To={2:"Llama2",3:"Llama3"};function Va(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(Io,s))return Io[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(To,i))return To[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Ja=["context_length","max_model_len"];function Wa(t){let e=Ja.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function Zt(t){let e=t.map(Wa),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ka(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function cr(t){if(t.length===0)return null;let e=t.map(Ka),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function za(t,e){let n=e.filter(o=>qe(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return Qt(n);let r=e.filter(o=>qe(o.model_id)===t);return r.length>0?Qt(r):null}function Qt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Ya(t),matches:t}:null}function Ya(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Mo(t){return 0}function Ze(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function en(t,e,n){let r=za(t,e);if(!r)return Ze({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Zt(s),a=It(o.model_id,o.variant,n),u=$o(o,s),d=cr(s);return Ze({id:t,object:"model",created:Mo(o),owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var Xa=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function $o(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...Xa],defect:o}:{published:[],defect:o}}function pr(t){let e=t.length>0?Qt(t):null;return e===null?{published:[],defect:null}:$o(e.row,e.matches)}function Po(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Co(t){return{input:[{type:"prompt",unit:"token",cost_usd:Po(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Po(t.output)}]}}function Qa(t,e,n,r){if(e.length===0)return null;let o=Qt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ha[s.task]!==!0)return null;let a=Zt(i),u=It(s.model_id,s.variant,n),d=Va(s.hf_repo),l={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(l.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Mo(s),quantization:qa(s.variant),...d!==null?{tokenizer:d}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Co(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...u?{pricing:Co(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Lo(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?mt(t):[];if(s.length>0){let d=s.filter(l=>l.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let l=d.map(p=>`${p.model_id}:${p.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${l} carry no ready field and are declared not ready`)}}let i={datacenters:Ga(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let l=`${d.model_id}:${d.variant}`;if(u.has(l))continue;u.add(l);let p=Qa(d,e.filter(y=>y.model_id===d.model_id&&y.variant===d.variant),n,i);p&&a.push(p)}return{data:a}}k();var No={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ht=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Uo(t){let e=t.t;if(typeof e!="string"||!(e in No))throw new ht(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(No).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Za(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ht(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new ht(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Uo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ht(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Uo(t)}function Do(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function eu(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Fo(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Do(e);let s=o.next();if(e!==void 0&&await eu(s,e)==="aborted")throw s.catch(()=>{}),Do(e);let i=await s;if(i.done)return;yield Za(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var z=class extends Error{},fe=class extends Error{},mr="urs1.";function Bo(t,e){return mr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function tu(t){if(!t.startsWith(mr))return null;try{let e=JSON.parse(Buffer.from(t.slice(mr.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Go(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function jo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ru(t);return e===null?[]:[e]}function fr(t,e,n,r,o){if(!o)throw new pe(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new pe(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new pe(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Ho(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new pe(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Vo="shared:",tt="speech:";function Pt(t){return t.sharedApp?Vo+t.appSlug:t.appSlug}function Ct(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function We(t,e){let n=e.filter(s=>qe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>qe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function nu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ru(t){let e=t.map(nu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var qo={stt:"stt",tts:"tts"};function Ke(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||qo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?qo[e]:null}function ou(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Error(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var tn=6e4,nn=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??tn;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??tn;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??tn;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??tn;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof xe)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
3
|
+
`),Tt}let r=xo(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
|
|
4
|
+
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(lr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Vo)||o.startsWith(tt)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new z(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=qe(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new z(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new z(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let s=await this.sharedBlock();if(s){let i=vo(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:s.shared_org_id}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===qe(a.model_id)||o===qe(`${a.model_id}-${a.variant}`));if(i)throw new z(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Ct(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async targetFor(e){return this.resolveTarget(e)}async resolveApp(e){return Pt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Pt(n))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,tt+Pt(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Ct(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Bo(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Bo(n,this.keyOf(r))}}async sessionForHandle(e){let n=tu(e);if(!n)throw new fe(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new fe(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new fe(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(d=>({ok:!0,rows:d}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Tt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
5
|
+
`);let u=(n?mt(n):[]).map(d=>{let l=s.filter(S=>S.model_id===d.model_id&&S.variant===d.variant),p=Zt(l),y=cr(l),c=It(d.model_id,d.variant,i),m=pr(l);return Ze({id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",...p!==null?{context_length:p}:{},...c!==null?{pricing:c}:{},...m.published.length>0?{voices:[...m.published]}:{},...y!==null?{capabilities:{reasoning:y}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>en(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Lo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=fr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ho(`${r.modelId}:${r.variant}`,s).includes(n)}return jo(We(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ke(We(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ke(We(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ke(We(n.appSlug,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):We(n.appSlug,r);return ou(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):We(n.appSlug,r);return pr(o)}async imageModelList(){let e=await this.catalogRows(),n=Tt,r=[];for(let s of await this.availableIds()){let i=jo(We(s,e));i.length!==0&&r.push(Ze({...en(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of mt(o)){let i=fr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ho(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=Ze({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Tt,r=[];for(let s of await this.availableIds())Ke(We(s,e))==="stt"&&r.push(en(s,e,n));let o=await this.sharedBlock();if(o)for(let s of mt(o)){let i=fr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ke(i)!=="stt")continue;let a=Ze({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};function Jo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} 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 on(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var du=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Wo(t){let e=t?.code;return typeof e=="string"&&du.has(e)}function Le(t,e){try{return t.write(e),!0}catch(n){if(Wo(n))return!1;throw n}}function Ko(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Wo(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
6
|
+
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}k();var we=require("@prometheus-io/client"),ws=require("http");k();var lu={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function cu(t){return lu[t]??null}var Xo=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function pu(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function fu(t){return t==="surface"}function mu(t){let e=t?.ledgerFailureReason;return Xo.includes(e)?e:"unknown"}var hu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],zo=["priced","unpriced"],gu={written:zo,already_written:zo,skipped:hu,failed:Xo},Qo=Object.entries(gu).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function yu(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function wu(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var _u=256,Yo=4096,Mt=12e4,vu=250,bu=8e3,Ge=[],hr=new Set,$t=0,gt=!1;function Zo(){return Ge.length}function es(t=Date.now()){let e=Ge[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var sn=new Set;function ts(){return $t===0&&Ge.length===0}function ns(){if(ts()){gt=!1;for(let t of[...sn])t()}}async function rs(t=ss){return ts()?!0:await new Promise(e=>{let n=null,r=()=>{sn.delete(r),n&&clearTimeout(n),e(!0)};sn.add(r),n=setTimeout(()=>{sn.delete(r),e(!1)},t),n.unref?.()})}function os(){gt=!0;let t=[...Ge.splice(0,Ge.length),...hr];for(let e of t)e.settled||nt(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${ss}ms drain \u2014 the request was served and answered, and its billing row was never written`});return ns(),t.length}var ss=5e3;function is(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
7
|
+
`}function ku(t){Le(process.stdout,t)}function as(t,e){try{t(e)}catch{}}function us(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ku,o=cu(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,p)=>{s({outcome:"skipped",reason:l}),as(r,is("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:p}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:wu(e),completed_at:e.ts,billable_outcome:yu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Ge.length>=Yo){i("queue_full",`${Ge.length} ledger writes are already waiting (capacity ${Yo}, ${$t} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ge.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),$t<_u&&($t+=1,Su())}async function Su(){try{for(;;){let t=Ru();if(t===void 0)return;hr.add(t);try{await xu(t)}finally{hr.delete(t)}}}finally{$t-=1,ns()}}function Ru(){let t=Date.now();for(;;){let e=Ge.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Mt)return e;nt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Mt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function xu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);nt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=pu(o);if(s!==null){nt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=mu(o),a=Date.now()-t.queuedAt;if(gt){nt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(fu(i)&&a<Mt){if(await Ou(Eu(t.attempts)),gt||Date.now()-t.queuedAt>=Mt){let u=Date.now()-t.queuedAt;nt(t,{outcome:"failed",reason:gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${Mt}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}nt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Eu(t){return Math.min(bu,vu*2**Math.max(0,t-1))}function Ou(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function nt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;as(t.report,is(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}k();k();var un="/v1/usage/requests",ds=1e4,Au=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ze=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},re=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},an=class extends re{constructor(e){super(e),this.name="UsageWithholdingError"}},fs=1024*1024;function wr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ze(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ze(`"${e}" must be an array of uuid strings`);if(n.length>ds)throw new ze(`"${e}" carries ${n.length} ids; at most ${ds} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Au.test(s))throw new ze(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ms(t){return wr(t,"inference_ids")}var Iu=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function yt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new re(`${n}: ${e} is not a non-empty string (got ${_t(r)})`);return r}function gr(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new re(`${n}: ${e} is neither null nor a non-empty string (got ${_t(r)})`);return r}function wt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new re(`${n}: ${e} is not a number (got ${_t(o)})`);if(r&&!Number.isSafeInteger(s))throw new re(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new re(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Tu=40,ls=64,cs=600;function hs(t){let e=Object.keys(t).sort(),r=e.slice(0,Tu).map(o=>o.length>ls?`${o.slice(0,ls)}\u2026`:o).join(", ");return r.length>cs&&(r=`${r.slice(0,cs)}\u2026`),`${e.length} keys present: [${r}]`}function _t(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function yr(t){Le(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
|
|
8
|
+
`)}function Pu(t,e){let n;try{n=t(e)}catch{ps(t,e);return}Cu(n)&&Promise.resolve(n).catch(()=>{ps(t,e)})}function Cu(t){return typeof t?.then=="function"}function ps(t,e){if(t!==yr)try{yr(e)}catch{}}function gs(t,e=yr){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?hs(t):_t(t);throw new re(`the usage surface answered without a "requests" array: got ${_t(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Mu(n[o],s))}catch(i){if(i instanceof an||!(i instanceof re))throw i;Pu(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new re(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Mu(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new re(`${e} is not an object: got ${_t(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new an(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Iu)if(!Object.hasOwn(n,o))throw new re(`${e} has no "${o}" column (${hs(n)})`);let r=wt(n,"http_status",e,!0);if(r===null)throw new re(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:yt(n,"inference_id",e),model_id:yt(n,"model_id",e),identity_kind:yt(n,"identity_kind",e),variant:gr(n,"variant",e),task:yt(n,"task",e),http_status:r,started_at:yt(n,"started_at",e),completed_at:yt(n,"completed_at",e),prompt_tokens:wt(n,"prompt_tokens",e,!0),completion_tokens:wt(n,"completion_tokens",e,!0),output_units:wt(n,"output_units",e,!1),output_minutes:wt(n,"output_minutes",e,!1),cost_nano_usd:wt(n,"cost_nano_usd",e,!0),price_version:gr(n,"price_version",e),priced_at:gr(n,"priced_at",e)}}function dn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new re(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new re(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var Lt="/partners/huggingface/v1/billing/requests";function $u(t){return wr(t,"requestIds")}function Lu(t){return t>=200&&t<=399}function Nu(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Lu(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ys(t,e){let n=$u(t),r=await e(n);return dn(r,n),Nu(r)}var _r=9464,ln="/metrics",cn="(other)",Uu="(none)",Du=64,Fu=128,Bu=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",un,Lt,et],ju=new Set(Bu);function Hu(t){return ju.has(t)?t:cn}function qu(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Uu:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,cn):(this.admitted.add(e),e):cn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},fn=class{registry=new we.Registry;modelLabel=new pn(Du);orgLabel=new pn(Fu);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new we.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new we.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new we.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new we.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new we.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new we.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Qo)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new we.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},Zo()),this.ledgerQueue.set({measure:"oldest_age_seconds"},es()/1e3)}}),this.labelCardinality=new we.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new we.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,we.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=Hu(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?cn:e.method,status_class:qu(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function _s(t){return(0,ws.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==ln){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${ln}
|
|
9
9
|
`);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
10
|
-
`);return}n.end()})})}k();var
|
|
11
|
-
`)}var Yu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},tt="urun.videoOut";function As(t){return{framing:ks,codec:t}}function Is(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[tt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Xu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Qu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",tt],Rs=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Zu(t){let e=ie(t);if(!e)throw new A("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new A(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new A("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new A(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new A("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Rs.includes(e.activityHandling))throw new A(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Rs.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var ed=["temperature","maxOutputTokens","responseModalities"];function Ts(t){for(let[p,y]of Object.entries(Xu))if(t[p]!==void 0)throw new A(y);for(let p of Object.keys(t))if(!Qu.includes(p))throw new A(`unsupported setup field "${p}"`);if(typeof t.model!="string"||t.model.length===0)throw new A('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new A("setup.generationConfig must be an object");if(s){for(let p of Object.keys(s))if(!ed.includes(p))throw new A(`unsupported generationConfig field "${p}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new A("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new A("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let p=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let y of p){let c=String(y).toUpperCase();if(c==="AUDIO"){o=!0;continue}if(c!=="TEXT")throw new A(`responseModalities ${JSON.stringify(y)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Os(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new A("setup.tools must be an array");a=[];for(let p of t.tools){let y=ie(p);if(!y)throw new A("setup.tools entries must be objects");for(let c of Object.keys(y))if(c!=="functionDeclarations")throw new A(`unsupported tool "${c}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(y.functionDeclarations))throw new A("tool.functionDeclarations must be an array");for(let c of y.functionDeclarations){let m=ie(c);if(!m||typeof m.name!="string")throw new A("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let p=ie(t.sessionResumption);if(!p)throw new A("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let y of Object.keys(p))if(y!=="handle")throw new A(`unsupported sessionResumption field "${y}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(p.handle!==void 0&&(typeof p.handle!="string"||p.handle.length===0))throw new A("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof p.handle=="string"?p.handle:null}}let d=t.realtimeInputConfig===void 0?Yu:Zu(t.realtimeInputConfig),l=!1;if(t[tt]!==void 0){if(!ie(t[tt]))throw new A(`setup["${tt}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:l}}function Ps(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Cs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ms(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new A(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new A("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new A("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new A(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Os(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var pn=16e3,$s=24e3,td=`audio/pcm;rate=${$s}`,Ls=Buffer.alloc(960).toString("base64");function nd(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let l=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function rd(t){let e=ie(t);if(!e)throw new A("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new A("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function od(t){let e=ie(t);if(!e)throw new A("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==pn)throw new A(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${pn} Hz (audio/pcm;rate=${pn})`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new A(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=nd(o,pn,$s);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Us(t){if(t.mediaChunks!==void 0)throw new A('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new A("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new A(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new A(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new A(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:od(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:rd(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new A("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new A("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Ns(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new A(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new A("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new A("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Ds(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Fs(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:td,data:t}}]}}}}function Bs(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=ie(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let p of l.content){let y=ie(p);y?.type==="output_text"&&typeof y.text=="string"&&(s+=y.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=ie(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new A(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,Ge);let p=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",y;try{y=JSON.parse(p)}catch{throw new A(`upstream function_call arguments are not valid JSON: ${p}`,Ge)}r.push({id:l.call_id,name:l.name,args:y}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:p})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}k();var js=require("crypto"),Hs=require("ws");var sd=256,_r=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>sd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},id="local",Mt=t=>t.slice(0,120),vr=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof z){this.ws.close(xs,Mt(e.message));return}if(e instanceof fe){this.ws.close(hn,Mt(e.message));return}if(e instanceof A){this.ws.close(e.closeCode,Mt(e.message));return}this.ws.close(Ge,Mt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Es(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new A(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Ms(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Us(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Ls);return}this.transcript.push(...Ns(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new A("setup may only be sent once, as the first client message");let n=Ts(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new A("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",hn);if(s.model!==n.model)throw new A(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new A("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new A(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,hn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(Is(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[tt]=As(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new A("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new A("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ge);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Fs(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new A("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new A("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ge);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new A(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new A("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new A("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,js.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Ps(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Cs(e.timeLeftMs)),this.ws.close(Ge,Mt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new A(`upstream error: ${JSON.stringify(d)}`,Ge);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=Ds(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new A("upstream produced no response.completed event",Ge);let{messages:i,assistantItems:a}=Bs(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},nt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ad(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new nt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new nt(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new nt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function br(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Hs.WebSocketServer({noServer:!0}),o=new _r;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===mn&&(a.on("error",()=>{}),(async()=>{let l=ad(i,d,n),p;if(e.authenticate)p=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new nt(401,"invalid local proxy api key");p={clients:e.clients,scope:id}}r.handleUpgrade(i,a,u,y=>{new vr(y,p,o)})})().catch(l=>{let p=502;(l instanceof nt||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(p=l.status);let y=p===401?"Unauthorized":p===403?"Forbidden":p===502?"Bad Gateway":"Internal Server Error",c=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${p} ${y}\r
|
|
10
|
+
`);return}n.end()})})}k();var vr=require("crypto"),bs=require("http"),br=9465,Gu="x-urun-key-id",Vu="x-urun-key-fingerprint",Ju="urun-ratelimit-bucket:",Wu="urun-ratelimit-tier:",vs="anonymous",Ku=/^urun_sk_[A-Za-z0-9_-]{43}$/;function zu(t){return(0,vr.createHash)("sha256").update(`${Ju}${t}`).digest("hex")}function Yu(t){return(0,vr.createHash)("sha256").update(`${Wu}${t}`).digest("hex")}function Xu(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Ku.test(n)?n:null}function ks(){return(0,bs.createServer)((t,e)=>{let n=Xu(t.headers.authorization);e.setHeader(Gu,n===null?vs:zu(n)),e.setHeader(Vu,n===null?vs:Yu(n)),e.writeHead(200),e.end()})}k();var Qu=8080,mn="serve",rt="0.0.0.0";function Zu(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Ss(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Qu:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=Jo(on(Zu(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(),s=o?on(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)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 u=i?{catalogUrl:on(i,"URUN_CATALOG_URL"),anonKey:a}:null,d=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),l=(t.URUN_SHARED_ORG_API_KEY??"").trim(),p=(t.URUN_SHARED_ORG_ID??"").trim();if(!!l!=!!p)throw new Error("URUN_SHARED_ORG_API_KEY and URUN_SHARED_ORG_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would silently leave the shared endpoints on the session lane");return{port:n,baseUrl:r,apiUrl:s,catalog:u,decisionSecret:d,sharedOrgKey:l,sharedOrgId:p}}k();var pa=require("http");k();k();var Es="audio",kr=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function Os(t,e,n=1e4){let r=new kr(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Es).attach(o);let s=await ed(t,n);return await r.startInbound(s),r}function ed(t,e){let n=t.stream(Es);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Rs="rt-video-in",xs=256e3;function As(t){let e=t.stream(Rs),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Rs}') 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>xs)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${xs}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var td=24e3,Nt=480,nd=111;async function rd(){let t=await import("opusscript"),e=t.default??t;return new e(td,1,2048)}async function Is(){let t=await import("werift"),e=await rd();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let d=0;for(;u.length-d>=Nt;){let l=u.subarray(d,d+Nt);d+=Nt;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),y=e.encode(p,Nt);o=o+1&65535,s=s+Nt>>>0;let c=new t.RtpHeader({version:2,payloadType:nd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(c,y);n.writeRtp(m)}i=u.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}k();var hn=require("@urun-sh/core"),Sr="rt-video-out";var od="h264";function sd(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function id(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;sd(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Ts="urun.videoOut.v2-ws";function Ps(t){let e=t.stream(Sr);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Sr}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=u=>{for(let d of r)d(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Sr}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=id(u)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of o)u()};return{codec:od,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var _n="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ad=1007,Ms=1008,Ve=1011,vn=1008,A=class extends Error{constructor(n,r=ad){super(n);this.closeCode=r}closeCode},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,gn=["setup","clientContent","realtimeInput","toolResponse"];function $s(t){let e;try{e=JSON.parse(t)}catch{throw new A("client message is not valid JSON")}let n=ie(e);if(!n)throw new A("client message must be a JSON object");let r=gn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!gn.includes(a));if(o.length>0)throw new A(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${gn.join(", ")}`);if(r.length!==1)throw new A(`client message must contain exactly one of ${gn.join(", ")} (got ${r.length})`);let s=r[0],i=ie(n[s]);if(!i)throw new A(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ls(t,e){if(typeof t=="string")return t;let n=ie(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new A(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ie(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new A(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new A(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new A(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
11
|
+
`)}var ud={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},ot="urun.videoOut";function Ns(t){return{framing:Ts,codec:t}}function Us(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[ot]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var dd={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},ld=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",ot],Cs=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function cd(t){let e=ie(t);if(!e)throw new A("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new A(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new A("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new A(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new A("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Cs.includes(e.activityHandling))throw new A(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Cs.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var pd=["temperature","maxOutputTokens","responseModalities"];function Ds(t){for(let[p,y]of Object.entries(dd))if(t[p]!==void 0)throw new A(y);for(let p of Object.keys(t))if(!ld.includes(p))throw new A(`unsupported setup field "${p}"`);if(typeof t.model!="string"||t.model.length===0)throw new A('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new A("setup.generationConfig must be an object");if(s){for(let p of Object.keys(s))if(!pd.includes(p))throw new A(`unsupported generationConfig field "${p}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new A("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new A("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let p=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let y of p){let c=String(y).toUpperCase();if(c==="AUDIO"){o=!0;continue}if(c!=="TEXT")throw new A(`responseModalities ${JSON.stringify(y)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Ls(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new A("setup.tools must be an array");a=[];for(let p of t.tools){let y=ie(p);if(!y)throw new A("setup.tools entries must be objects");for(let c of Object.keys(y))if(c!=="functionDeclarations")throw new A(`unsupported tool "${c}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(y.functionDeclarations))throw new A("tool.functionDeclarations must be an array");for(let c of y.functionDeclarations){let m=ie(c);if(!m||typeof m.name!="string")throw new A("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let p=ie(t.sessionResumption);if(!p)throw new A("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let y of Object.keys(p))if(y!=="handle")throw new A(`unsupported sessionResumption field "${y}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(p.handle!==void 0&&(typeof p.handle!="string"||p.handle.length===0))throw new A("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof p.handle=="string"?p.handle:null}}let d=t.realtimeInputConfig===void 0?ud:cd(t.realtimeInputConfig),l=!1;if(t[ot]!==void 0){if(!ie(t[ot]))throw new A(`setup["${ot}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:l}}function Fs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Bs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function js(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new A(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new A("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new A("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new A(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Ls(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var yn=16e3,Hs=24e3,fd=`audio/pcm;rate=${Hs}`,qs=Buffer.alloc(960).toString("base64");function md(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let l=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function hd(t){let e=ie(t);if(!e)throw new A("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new A("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function gd(t){let e=ie(t);if(!e)throw new A("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==yn)throw new A(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${yn} Hz (audio/pcm;rate=${yn})`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new A(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=md(o,yn,Hs);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Gs(t){if(t.mediaChunks!==void 0)throw new A('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new A("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new A(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new A(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new A(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:gd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:hd(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new A("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new A("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Vs(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new A(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new A("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new A("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Js(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ws(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:fd,data:t}}]}}}}function Ks(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=ie(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let p of l.content){let y=ie(p);y?.type==="output_text"&&typeof y.text=="string"&&(s+=y.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=ie(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new A(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,Ve);let p=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",y;try{y=JSON.parse(p)}catch{throw new A(`upstream function_call arguments are not valid JSON: ${p}`,Ve)}r.push({id:l.call_id,name:l.name,args:y}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:p})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}k();var zs=require("crypto"),Ys=require("ws");var yd=256,Rr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>yd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},wd="local",Ut=t=>t.slice(0,120),xr=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof z){this.ws.close(Ms,Ut(e.message));return}if(e instanceof fe){this.ws.close(vn,Ut(e.message));return}if(e instanceof A){this.ws.close(e.closeCode,Ut(e.message));return}this.ws.close(Ve,Ut(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=$s(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new A(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=js(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Gs(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:qs);return}this.transcript.push(...Vs(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new A("setup may only be sent once, as the first client message");let n=Ds(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new A("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",vn);if(s.model!==n.model)throw new A(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new A("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new A(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,vn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(Us(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[ot]=Ns(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new A("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new A("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ve);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ws(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new A("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new A("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ve);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new A(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new A("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new A("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,zs.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Fs(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Bs(e.timeLeftMs)),this.ws.close(Ve,Ut(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new A(`upstream error: ${JSON.stringify(d)}`,Ve);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=Js(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new A("upstream produced no response.completed event",Ve);let{messages:i,assistantItems:a}=Ks(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},st=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function _d(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new st(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new st(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new st(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Er(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Ys.WebSocketServer({noServer:!0}),o=new Rr;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===_n&&(a.on("error",()=>{}),(async()=>{let l=_d(i,d,n),p;if(e.authenticate)p=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new st(401,"invalid local proxy api key");p={clients:e.clients,scope:wd}}r.handleUpgrade(i,a,u,y=>{new xr(y,p,o)})})().catch(l=>{let p=502;(l instanceof st||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(p=l.status);let y=p===401?"Unauthorized":p===403?"Forbidden":p===502?"Bad Gateway":"Internal Server Error",c=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${p} ${y}\r
|
|
12
12
|
Connection: close\r
|
|
13
13
|
\r
|
|
14
14
|
${c}\r
|
|
15
|
-
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}k();var
|
|
16
|
-
`}var ud=256,dd=128;function ke(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,dd)}var rt=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=ud?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+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:e},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}}}},ld=256;function cd(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 ot=class extends Error{},gt=class{conversations=new Map;thread(e,n){let r=cd(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ot(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=ld)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ys=new WeakMap;function Ut(t){let e=Ys.get(t);return e||(e=new gt,Ys.set(t,e)),e}function yt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function wt(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 Ke=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},pd=["<tool_call>","<function="];function fd(t){return pd.find(e=>t.includes(e))}function st(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} 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 it(t,e,n){if(!(!t||e>0))return fd(n)}function _t(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function md(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Sr(t,e){let n=md(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Oe=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function vt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ot?new Oe(n.message,"previous_response_not_found",400,"previous_response_id"):new Oe(String(n instanceof Error?n.message:n),"invalid_input")}}function Xs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Rr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Oe("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Xs(e)!==void 0?{response_format:Xs(e)}:{}},o)}async function Nt(t){let{body:e,clients:n,store:r,stats:o}=t,s=vt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=ke(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,p=t.turn,y=await Rr(n,e,s,!0,p?Ee(p):void 0);return{responseId:i,events:wd({events:y,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function hd(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?yd(o[i++],u):u),...gd(r,n)]}function gd(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(o(l)):!0})}function yd(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*wd(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],p=H=>H.response&&typeof H.response=="object"?{...H,response:{...H.response,id:r}}:H,y=`item_${r.slice(5)}`,c=!1,m=!1,w=0;function*R(){c||(c=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let g=[],v=(H,O)=>{g.push({output_index:H,item:O})},b=!1,L=0,S="",x=0,C="";function*J(){if(!b)return;b=!1,yield{type:"response.reasoning_text.done",item_id:S,output_index:L,content_index:0,text:C};let H={id:S,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:C}],status:"completed"};yield{type:"response.output_item.done",output_index:L,item:H},v(L,H),C=""}let I=!1,M=0,G="",Y=0,de="",ge="";function*ve(H){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:G,output_index:M,content_index:0,text:de},yield{type:"response.content_part.done",item_id:G,output_index:M,content_index:0,part:{type:"output_text",text:de}};let O={id:G,type:"message",role:"assistant",status:H,content:[{type:"output_text",text:de}]};yield{type:"response.output_item.done",output_index:M,item:O},v(M,O),de=""}let Ie=new Ke,ee=null,te=-1;function*le(H){if(!ee)return;let O=ee;ee=null,yield{type:"response.function_call_arguments.done",item_id:O.fcId,output_index:O.outputIndex,arguments:O.args};let X={id:O.fcId,type:"function_call",call_id:O.callId??O.fcId,name:O.name??"",arguments:O.args,status:H};yield{type:"response.output_item.done",output_index:O.outputIndex,item:X},v(O.outputIndex,X)}let Me=!1;for await(let H of d.track(e,o,t.turn)){l.push(H);let O=String(H.type??"");if(O==="response.created"||O==="response.in_progress"){c=!0,yield p(H);continue}if(O==="response.output_item.added"){m=!0,yield p(H);continue}if(O==="response.reasoning_text.delta"&&!m){yield*R(),b||(b=!0,L=w++,x+=1,S=x===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${x}`,yield{type:"response.output_item.added",output_index:L,item:{id:S,type:"reasoning",summary:[],content:[],status:"in_progress"}}),C+=String(H.delta??""),yield{type:"response.reasoning_text.delta",item_id:S,output_index:L,content_index:0,delta:H.delta};continue}if(O==="response.output_text.delta"&&!m){yield*R(),yield*J(),I||(I=!0,M=w++,Y+=1,G=Y===1?y:`${y}_${Y}`,yield{type:"response.output_item.added",output_index:M,item:{id:G,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:G,output_index:M,content_index:0,part:{type:"output_text",text:""}}),de+=String(H.delta??""),ge+=String(H.delta??""),yield{type:O,item_id:G,output_index:M,content_index:0,delta:H.delta};continue}let X=m?null:wt(H);if(X){if(yield*R(),yield*J(),yield*ve("completed"),Ie.add(X),X.tool_index!==te){yield*le("completed"),te=X.tool_index;let Te=w++;ee={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:Te,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:ee.fcId,type:"function_call",call_id:ee.callId??ee.fcId,name:ee.name??"",arguments:"",status:"in_progress"}}}ee&&(X.call_id&&(ee.callId=X.call_id),X.name&&(ee.name=X.name),ee.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:ee.fcId,output_index:ee.outputIndex,delta:X.delta});continue}if(O==="response.completed"&&!m){let Te=yt(H.response),B=it(s,Ie.size+Te.length,ge);if(B){Me=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:st(o,B)}};break}if(yield*J(),yield*ve("completed"),yield*le("completed"),Ie.size===0)for(let $e of Te){let Be=w++,lt=$e.id??$e.call_id??`fc_${Be}`,be=$e.arguments??"",St={id:lt,type:"function_call",call_id:$e.call_id??lt,name:$e.name??""};yield{type:"response.output_item.added",output_index:Be,item:{...St,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:lt,output_index:Be,delta:be},yield{type:"response.function_call_arguments.done",item_id:lt,output_index:Be,arguments:be};let je={...St,arguments:be,status:"completed"};yield{type:"response.output_item.done",output_index:Be,item:je},v(Be,je)}let he=hd(g,H.response);yield he.length>0?p({...H,response:{...H.response,output:he}}):p(H);continue}yield p(H)}if(yield*J(),yield*ve("incomplete"),yield*le("incomplete"),i&&!Me){let H=Ue(l);u.remember(r,n,Sr(H,_t(l,H)),a)}}var Or="/v1/responses",_d=64*1024*1024,vd=8*1024*1024,bd=16,Qs=32,Zs=3600*1e3,kd=/^[A-Za-z0-9._-]{1,256}$/;function Se(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Sd=Se(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Ar(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Rd(t){for(;t.bufferedAmount>vd&&t.readyState===ze.WebSocket.OPEN;){let{promise:e,resolve:n}=Ar();setTimeout(n,5),await e}}var xr=class extends gt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof ot))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Er=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new xr(Ut(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Zs/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Zs).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(Se(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(Se(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(Se(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(Se(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(Se(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(Se(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!kd.test(o.stream_id)){this.sendFrame(Sd);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Qs){this.sendFrame(Se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Qs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Nt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Lt($t())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==ze.WebSocket.OPEN)break;this.send(i,n),await Rd(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=Lt($t());try{let o=vt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof Oe)return Se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof z)return Se(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof fe)return Se(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?Se(o.status,{type:o.openaiType,message:r},n):Se(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=bd;){let{promise:e,resolve:n}=Ar();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==ze.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==ze.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function gn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
15
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}k();var Xe=require("ws");k();k();var Xs=require("crypto"),Qs="Inference-Id";function Dt(){return(0,Xs.randomUUID)()}function Or(t){return t==="/v1"||t.startsWith("/v1/")}function Zs(t,e){if(!Or(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function Ft(t){return`resp_${t}`}function ei(t){return`chatcmpl-${t}`}function ti(t){return`msg_${t}`}function Ee(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ni(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function ri(t){return`${JSON.stringify(t)}
|
|
16
|
+
`}var vd=256,bd=128;function ke(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,bd)}var it=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=vd?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+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:e},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}}}},kd=256;function Sd(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 at=class extends Error{},vt=class{conversations=new Map;thread(e,n){let r=Sd(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new at(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=kd)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},oi=new WeakMap;function Bt(t){let e=oi.get(t);return e||(e=new vt,oi.set(t,e)),e}function bt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ne(t){return t.find(e=>e.type==="response.completed")?.response??null}function kt(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 Ye=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Rd=["<tool_call>","<function="];function xd(t){return Rd.find(e=>t.includes(e))}function ut(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} 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 dt(t,e,n){if(!(!t||e>0))return xd(n)}function St(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ed(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Ar(t,e){let n=Ed(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Oe=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Rt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof at?new Oe(n.message,"previous_response_not_found",400,"previous_response_id"):new Oe(String(n instanceof Error?n.message:n),"invalid_input")}}function si(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ir(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Oe("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...si(e)!==void 0?{response_format:si(e)}:{}},o)}async function jt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Rt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=ke(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,p=t.turn,y=await Ir(n,e,s,!0,p?Ee(p):void 0);return{responseId:i,events:Td({events:y,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Od(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Id(o[i++],u):u),...Ad(r,n)]}function Ad(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(o(l)):!0})}function Id(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*Td(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],p=H=>H.response&&typeof H.response=="object"?{...H,response:{...H.response,id:r}}:H,y=`item_${r.slice(5)}`,c=!1,m=!1,w=0;function*S(){c||(c=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let g=[],v=(H,O)=>{g.push({output_index:H,item:O})},b=!1,L=0,R="",x=0,C="";function*W(){if(!b)return;b=!1,yield{type:"response.reasoning_text.done",item_id:R,output_index:L,content_index:0,text:C};let H={id:R,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:C}],status:"completed"};yield{type:"response.output_item.done",output_index:L,item:H},v(L,H),C=""}let I=!1,M=0,G="",Y=0,de="",ge="";function*ve(H){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:G,output_index:M,content_index:0,text:de},yield{type:"response.content_part.done",item_id:G,output_index:M,content_index:0,part:{type:"output_text",text:de}};let O={id:G,type:"message",role:"assistant",status:H,content:[{type:"output_text",text:de}]};yield{type:"response.output_item.done",output_index:M,item:O},v(M,O),de=""}let Ie=new Ye,ee=null,te=-1;function*le(H){if(!ee)return;let O=ee;ee=null,yield{type:"response.function_call_arguments.done",item_id:O.fcId,output_index:O.outputIndex,arguments:O.args};let X={id:O.fcId,type:"function_call",call_id:O.callId??O.fcId,name:O.name??"",arguments:O.args,status:H};yield{type:"response.output_item.done",output_index:O.outputIndex,item:X},v(O.outputIndex,X)}let Me=!1;for await(let H of d.track(e,o,t.turn)){l.push(H);let O=String(H.type??"");if(O==="response.created"||O==="response.in_progress"){c=!0,yield p(H);continue}if(O==="response.output_item.added"){m=!0,yield p(H);continue}if(O==="response.reasoning_text.delta"&&!m){yield*S(),b||(b=!0,L=w++,x+=1,R=x===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${x}`,yield{type:"response.output_item.added",output_index:L,item:{id:R,type:"reasoning",summary:[],content:[],status:"in_progress"}}),C+=String(H.delta??""),yield{type:"response.reasoning_text.delta",item_id:R,output_index:L,content_index:0,delta:H.delta};continue}if(O==="response.output_text.delta"&&!m){yield*S(),yield*W(),I||(I=!0,M=w++,Y+=1,G=Y===1?y:`${y}_${Y}`,yield{type:"response.output_item.added",output_index:M,item:{id:G,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:G,output_index:M,content_index:0,part:{type:"output_text",text:""}}),de+=String(H.delta??""),ge+=String(H.delta??""),yield{type:O,item_id:G,output_index:M,content_index:0,delta:H.delta};continue}let X=m?null:kt(H);if(X){if(yield*S(),yield*W(),yield*ve("completed"),Ie.add(X),X.tool_index!==te){yield*le("completed"),te=X.tool_index;let Te=w++;ee={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:Te,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:ee.fcId,type:"function_call",call_id:ee.callId??ee.fcId,name:ee.name??"",arguments:"",status:"in_progress"}}}ee&&(X.call_id&&(ee.callId=X.call_id),X.name&&(ee.name=X.name),ee.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:ee.fcId,output_index:ee.outputIndex,delta:X.delta});continue}if(O==="response.completed"&&!m){let Te=bt(H.response),j=dt(s,Ie.size+Te.length,ge);if(j){Me=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ut(o,j)}};break}if(yield*W(),yield*ve("completed"),yield*le("completed"),Ie.size===0)for(let $e of Te){let je=w++,ft=$e.id??$e.call_id??`fc_${je}`,be=$e.arguments??"",Ot={id:ft,type:"function_call",call_id:$e.call_id??ft,name:$e.name??""};yield{type:"response.output_item.added",output_index:je,item:{...Ot,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ft,output_index:je,delta:be},yield{type:"response.function_call_arguments.done",item_id:ft,output_index:je,arguments:be};let He={...Ot,arguments:be,status:"completed"};yield{type:"response.output_item.done",output_index:je,item:He},v(je,He)}let he=Od(g,H.response);yield he.length>0?p({...H,response:{...H.response,output:he}}):p(H);continue}yield p(H)}if(yield*W(),yield*ve("incomplete"),yield*le("incomplete"),i&&!Me){let H=Ne(l);u.remember(r,n,Ar(H,St(l,H)),a)}}var Cr="/v1/responses",Pd=64*1024*1024,Cd=8*1024*1024,Md=16,ii=32,ai=3600*1e3,$d=/^[A-Za-z0-9._-]{1,256}$/;function Se(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ld=Se(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Mr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Nd(t){for(;t.bufferedAmount>Cd&&t.readyState===Xe.WebSocket.OPEN;){let{promise:e,resolve:n}=Mr();setTimeout(n,5),await e}}var Tr=class extends vt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof at))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Pr=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Tr(Bt(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ai/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ai).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(Se(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(Se(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(Se(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(Se(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(Se(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(Se(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!$d.test(o.stream_id)){this.sendFrame(Ld);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ii){this.sendFrame(Se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ii}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await jt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ft(Dt())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)break;this.send(i,n),await Nd(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=Ft(Dt());try{let o=Rt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof Oe)return Se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof z)return Se(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof fe)return Se(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?Se(o.status,{type:o.openaiType,message:r},n):Se(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Md;){let{promise:e,resolve:n}=Mr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Xe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function bn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
17
17
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
18
18
|
Connection: close\r
|
|
19
19
|
Content-Type: text/plain; charset=utf-8\r
|
|
20
20
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
21
21
|
\r
|
|
22
|
-
${o}`)}function Ir(t,e){let n=new ze.WebSocketServer({noServer:!0,maxPayload:_d}),r=new rt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,p,y)=>{let c;try{c=new URL(l.url??"/","http://localhost")}catch{gn(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>i.delete(p)),c.pathname!==Or){i.add(p);return}s.add(p);let m=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){gn(p,401,"invalid local proxy api key");return}let w;try{w=await a(l)}catch(R){let g=e.statusOf?.(R)??null;gn(p,g?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(m=!0,n.handleUpgrade(l,p,y,R=>{s.delete(p),o.add(R),R.on("close",()=>o.delete(R));try{new Er(R,w,r,e.statusOf)}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!p.destroyed&&gn(p,500,"responses websocket upgrade failed")}).finally(()=>s.delete(p))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:p}=Ar();if(u)return p(),l;u=!0,t.off("upgrade",d);for(let c of s)c.destroy();s.clear();for(let c of i)c.destroy();i.clear();for(let c of o)c.close(1001,"server shutting down");let y=setTimeout(()=>{for(let c of o)c.readyState!==ze.WebSocket.CLOSED&&c.terminate()},2e3);return y.unref?.(),n.close(()=>{clearTimeout(y),p()}),l}}}k();k();var ii=require("@urun-sh/core");k();var ei=require("@urun-sh/core"),xd={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ed={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Tr(t,e){let n=Ed[t.code];return e?`${n} (${e})`:n}function yn(t){if(t==null)return null;let e=xd[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function wn(t){if(t.kind==="create-failed")return yn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ei.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return yn(e?"cold_start_exceeded":"queue_timeout")}var ai=require("ws");k();var si=require("@urun-sh/core");k();var ni=require("crypto");function D(t){return`${t}_${(0,ni.randomUUID)().replace(/-/g,"").slice(0,24)}`}var _n=4*1024*1024,Pr=8*1024*1024,vn=512,bn=20*1024*1024;function ae(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function bt(t,e){return{type:"server_error",code:t,message:e}}function Z(t){return{type:"error",event_id:D("event"),error:t}}function Cr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var j=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Od={model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Ad={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Id={format:!0,voice:!0,speed:!0};function ti(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new j(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Dt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new j("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in Od));if(o.length>0)throw new j(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new j("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new j("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new j("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new j(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new j('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new j("voice must be a string or null","voice");if(!n.voice)throw new j("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new j(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new j("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new j(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new j("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new j("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new j("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new j("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new j(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new j("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new j("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new j(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new j("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new j("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new j("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in Ad))throw new j(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&ti(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=Dt({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=Dt({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new j("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new j("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in Id))throw new j(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&ti(d.format,"audio.output.format"),d.speed!==void 0)throw new j("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new j("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new j("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function kn(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Mr(t,e){let n=t;if(!n||typeof n!="object")throw new j("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new j("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:D("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new j('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new j("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new j("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new j(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new j("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new j("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new j(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:D("item"),type:"message",role:r,content:o}}throw new j(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function $r(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Td=1001,Pd=1011,ri=t=>t.slice(0,120),Cd=/^[A-Za-z0-9+/=]*$/,Md=2;function $d(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Md)return!1;return!0}var Ft=class{id=D("conn");ws;binding;onClosed;config=Cr();sessionId=D("sess");conversationId=D("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:D("event"),session:kn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:D("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(Z(bt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:D("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:D("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=D("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:D("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:D("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:D("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:D("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ae("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>_n){this.fail(ae("frame_too_large",`frame exceeds the ${_n}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ae("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ae("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(Z({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(bt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Dt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:D("event"),session:kn(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Mr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:D("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(Z(ae("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:D("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(Z(ae("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:D("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(Z(ae("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:D("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(Z(ae("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Cd.test(e.audio)){this.send(Z(ae("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>bn){this.send(Z(ae("buffer_full",`uncommitted input audio exceeds the ${bn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:D("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(Z(ae("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=D("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:D("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:D("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(Z(ae("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(Z(ae("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Z(ae("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(Z({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(Z(ae("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(w=>w!=="text"&&w!=="audio")){this.send(Z(ae("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(Z(ae("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=D("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=$r(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,p=l==="inf"||l===void 0?void 0:l,y=n.tools!==void 0?n.tools:this.config.tools,c=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,m={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...p!==void 0?{max_output_tokens:p}:{},...y!==void 0?{tools:y}:{},...c!==void 0?{tool_choice:c}:{}};for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],R=L=>{this.responseFlushed?this.send(L):w.push(L)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:D("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:D("event"),response:this.responseObject(o,"in_progress")});for(let L of w)this.send(L);w.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},b=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{L=await this.upstreamStream(m,r)}catch(S){this.upstreamTurnFault(S,o);return}try{for await(let S of L){if(this.cancelled)break;let x=S;if(x.type==="error"){let C=this.upstreamErrorBody(x);this.responseFlushed?this.send(Z(C)):this.send({type:"response.failed",event_id:D("event"),response:this.failedResponse(o,C)});return}if(x.type==="response.output_text.delta"&&typeof x.delta=="string"){g(),v.messageOpen||(this.beginMessageItem(o,v.nextOutputIndex++),v.messageOpen=!0),R({type:"response.output_text.delta",event_id:D("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:x.delta}),v.messageText+=x.delta;continue}if(x.type==="response.function_call_arguments.delta"){g();let C=typeof x.delta=="string"?x.delta:"",J=typeof x.call_id=="string"&&x.call_id.length>0?x.call_id:`${o}_fc_${v.nextOutputIndex}`,I=v.tools.get(J);if(!I){let M=typeof x.name=="string"&&x.name.length>0?x.name:void 0;I={outputIndex:v.nextOutputIndex++,name:M,args:""},v.tools.set(J,I),R({type:"response.output_item.added",event_id:D("event"),response_id:o,output_index:I.outputIndex,item:{id:J,object:"realtime.item",type:"function_call",call_id:J,name:M??"",arguments:"",status:"in_progress"}})}typeof x.name=="string"&&x.name.length>0&&(I.name=x.name),I.args+=C,R({type:"response.function_call_arguments.delta",event_id:D("event"),item_id:J,response_id:o,output_index:I.outputIndex,call_id:J,name:I.name??"",delta:C});continue}if(x.type==="response.completed"){b=x.response??null;continue}}}catch(S){this.upstreamTurnFault(S,o);return}if(this.cancelled)return;this.closeOpenItems(o,v,s),g(),this.send({type:"response.done",event_id:D("event"),response:this.doneResponse(o,s,b)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if($d(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Z({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:D("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:D("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:D("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:D("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:D("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:D("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:D("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:D("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:D("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:D("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:D("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:D("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:D("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(bt("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof fe){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof si.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=bt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(Z(r)):this.send({type:"response.failed",event_id:D("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(Z(ae("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:D("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>vn&&(this.items.shift(),this.send(Z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${vn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Pr){this.ws.close(Td,ri("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(Z(e)),this.ws.close(Pd,ri(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>oi(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),oi(this.id,e)}}},Lr=[];function oi(t,e){Lr.push({id:t,reason:e}),Lr.length>256&&Lr.shift()}var Bt="/v1/realtime",Ld=t=>t.slice(0,120);function Ud(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
22
|
+
${o}`)}function $r(t,e){let n=new Xe.WebSocketServer({noServer:!0,maxPayload:Pd}),r=new it,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,p,y)=>{let c;try{c=new URL(l.url??"/","http://localhost")}catch{bn(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>i.delete(p)),c.pathname!==Cr){i.add(p);return}s.add(p);let m=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){bn(p,401,"invalid local proxy api key");return}let w;try{w=await a(l)}catch(S){let g=e.statusOf?.(S)??null;bn(p,g?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(m=!0,n.handleUpgrade(l,p,y,S=>{s.delete(p),o.add(S),S.on("close",()=>o.delete(S));try{new Pr(S,w,r,e.statusOf)}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!p.destroyed&&bn(p,500,"responses websocket upgrade failed")}).finally(()=>s.delete(p))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:p}=Mr();if(u)return p(),l;u=!0,t.off("upgrade",d);for(let c of s)c.destroy();s.clear();for(let c of i)c.destroy();i.clear();for(let c of o)c.close(1001,"server shutting down");let y=setTimeout(()=>{for(let c of o)c.readyState!==Xe.WebSocket.CLOSED&&c.terminate()},2e3);return y.unref?.(),n.close(()=>{clearTimeout(y),p()}),l}}}k();k();var mi=require("@urun-sh/core");k();var ui=require("@urun-sh/core"),Ud={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Dd={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Lr(t,e){let n=Dd[t.code];return e?`${n} (${e})`:n}function kn(t){if(t==null)return null;let e=Ud[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Sn(t){if(t.kind==="create-failed")return kn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ui.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return kn(e?"cold_start_exceeded":"queue_timeout")}var hi=require("ws");k();var fi=require("@urun-sh/core");k();var li=require("crypto");function U(t){return`${t}_${(0,li.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Rn=4*1024*1024,Nr=8*1024*1024,xn=512,En=20*1024*1024;function ae(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function xt(t,e){return{type:"server_error",code:t,message:e}}function Z(t){return{type:"error",event_id:U("event"),error:t}}function Ur(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var B=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Fd={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Bd={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},jd={format:!0,voice:!0,speed:!0};function di(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new B(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Ht(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new B("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in Fd));if(o.length>0)throw new B(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"type":{if(a!=="realtime"&&a!=="transcription")throw new B(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new B(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new B('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new B("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new B("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new B("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new B(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new B('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new B("voice must be a string or null","voice");if(!n.voice)throw new B("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new B(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new B("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new B(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new B("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new B("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new B("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new B(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new B("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new B("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new B(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=a.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new B(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new B("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new B("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in Bd))throw new B(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&di(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=Ht({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=Ht({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new B("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new B("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in jd))throw new B(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&di(d.format,"audio.output.format"),d.speed!==void 0)throw new B("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new B("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new B("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function On(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Dr(t,e){let n=t;if(!n||typeof n!="object")throw new B("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new B("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:U("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new B('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new B("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new B("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new B(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new B("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new B("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new B(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:U("item"),type:"message",role:r,content:o}}throw new B(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Fr(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Hd=1001,qd=1011,ci=t=>t.slice(0,120),Gd=/^[A-Za-z0-9+/=]*$/,Vd=2;function Jd(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Vd)return!1;return!0}var qt=class{id=U("conn");ws;binding;onClosed;config=Ur();sessionId=U("sess");conversationId=U("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:U("event"),session:On(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:U("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(Z(xt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:U("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:U("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:U("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:U("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:U("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:U("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=U("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:U("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.created",event_id:U("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:U("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:U("event"),item_id:i,content_index:0,transcript:s}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ae("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Rn){this.fail(ae("frame_too_large",`frame exceeds the ${Rn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ae("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ae("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(Z({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(xt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Ht(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:U("event"),session:On(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Dr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:U("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(Z(ae("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:U("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(Z(ae("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:U("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(Z(ae("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:U("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(Z(ae("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Gd.test(e.audio)){this.send(Z(ae("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>En){this.send(Z(ae("buffer_full",`uncommitted input audio exceeds the ${En}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:U("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(Z(ae("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=U("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:U("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:U("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:U("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:U("event"),item_id:r,content_index:0,transcript:s}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(Z(ae("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(Z(ae("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(Z(ae("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Z(ae("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(Z({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(Z(ae("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(w=>w!=="text"&&w!=="audio")){this.send(Z(ae("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(Z(ae("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=U("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Fr(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,p=l==="inf"||l===void 0?void 0:l,y=n.tools!==void 0?n.tools:this.config.tools,c=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,m={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...p!==void 0?{max_output_tokens:p}:{},...y!==void 0?{tools:y}:{},...c!==void 0?{tool_choice:c}:{}};for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],S=L=>{this.responseFlushed?this.send(L):w.push(L)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:U("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:U("event"),response:this.responseObject(o,"in_progress")});for(let L of w)this.send(L);w.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},b=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{L=await this.upstreamStream(m,r)}catch(R){this.upstreamTurnFault(R,o);return}try{for await(let R of L){if(this.cancelled)break;let x=R;if(x.type==="error"){let C=this.upstreamErrorBody(x);this.responseFlushed?this.send(Z(C)):this.send({type:"response.failed",event_id:U("event"),response:this.failedResponse(o,C)});return}if(x.type==="response.output_text.delta"&&typeof x.delta=="string"){g(),v.messageOpen||(this.beginMessageItem(o,v.nextOutputIndex++),v.messageOpen=!0),S({type:"response.output_text.delta",event_id:U("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:x.delta}),v.messageText+=x.delta;continue}if(x.type==="response.function_call_arguments.delta"){g();let C=typeof x.delta=="string"?x.delta:"",W=typeof x.call_id=="string"&&x.call_id.length>0?x.call_id:`${o}_fc_${v.nextOutputIndex}`,I=v.tools.get(W);if(!I){let M=typeof x.name=="string"&&x.name.length>0?x.name:void 0;I={outputIndex:v.nextOutputIndex++,name:M,args:""},v.tools.set(W,I),S({type:"response.output_item.added",event_id:U("event"),response_id:o,output_index:I.outputIndex,item:{id:W,object:"realtime.item",type:"function_call",call_id:W,name:M??"",arguments:"",status:"in_progress"}})}typeof x.name=="string"&&x.name.length>0&&(I.name=x.name),I.args+=C,S({type:"response.function_call_arguments.delta",event_id:U("event"),item_id:W,response_id:o,output_index:I.outputIndex,call_id:W,name:I.name??"",delta:C});continue}if(x.type==="response.completed"){b=x.response??null;continue}}}catch(R){this.upstreamTurnFault(R,o);return}if(this.cancelled)return;this.closeOpenItems(o,v,s),g(),this.send({type:"response.done",event_id:U("event"),response:this.doneResponse(o,s,b)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Jd(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Z({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:U("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:U("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:U("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:U("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:U("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:U("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:U("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:U("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:U("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:U("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:U("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:U("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:U("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(xt("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof fe){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof fi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=xt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(Z(r)):this.send({type:"response.failed",event_id:U("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(Z(ae("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:U("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>xn&&(this.items.shift(),this.send(Z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${xn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Nr){this.ws.close(Hd,ci("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(Z(e)),this.ws.close(qd,ci(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>pi(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),pi(this.id,e)}},Br=[];function pi(t,e){Br.push({id:t,reason:e}),Br.length>256&&Br.shift()}var Gt="/v1/realtime",Wd=t=>t.slice(0,120);function Kd(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
23
23
|
Connection: close\r
|
|
24
24
|
Content-Type: text/plain\r
|
|
25
25
|
\r
|
|
26
|
-
${
|
|
27
|
-
`),t.destroy()}function
|
|
28
|
-
`}function Dd(t){Le(process.stdout,t)}function Fd(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ur(t){return t.audioSession?.audio.sessionId??void 0}function Sn(t,e){let n=new ai.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Bt)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=D("rtup"),d=Fd(o),l=S=>{(e.log??Dd)(Nd(S))};l({stage:"accept",conn:u,model:d}),s.resume();let p=new AbortController,y=null,c=S=>{y??=S,p.abort(new Error(y))},m=()=>c("client socket closed"),w=()=>c("client socket closed (half-close)"),R=S=>c(`client socket error: ${S.message}`);s.once("close",m),s.once("end",w),s.once("error",R);let g=()=>{s.removeListener("close",m),s.removeListener("end",w),s.removeListener("error",R)},v=S=>{l({stage:"close",conn:u,model:d,...S})},b=S=>{let x=S,C=x.session!=null&&typeof x.session.sendResponseCreate=="function",J=x.clients!=null&&typeof x.clients.createResponse=="function";if(!C&&!J)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((I,M)=>{n.handleUpgrade(o,s,i,G=>{try{new Ft({ws:G,binding:S,onClosed:(Y,de)=>{v({while:"live",reason:de.reason})}}),l({stage:"admit",conn:u,model:d,...Ur(S)===void 0?{}:{session:Ur(S)}}),I()}catch(Y){M(Y)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal).then(async S=>{if(p.signal.aborted){g();let x=Ur(S);try{await S.release?.()}catch(C){v({while:"queued",...x===void 0?{}:{session:x},reason:y??"client socket closed",release_failed:C instanceof Error?C.message:String(C)});return}v({while:"queued",...x===void 0?{}:{session:x},reason:y??"client socket closed",released:!0}),s.destroy();return}g(),await b(S)}).catch(S=>{let x=S instanceof ii.SessionFailedError?wn(S):null,C=null;if(S!==null&&typeof S=="object"&&"status"in S){let M=S.status;typeof M=="number"&&(C=M)}let J=C??x?.status??502,I=S instanceof Error?S.message:String(S);v({while:"queued",...p.signal.aborted?{reason:y??"client socket closed"}:{reason:I,status:J}}),s.destroyed||Ud(s,J,I)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}k();k();var El=require("http");k();k();var ye=class extends Error{};async function Rn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ye(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ye(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function xn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new ye(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let p of l)i.append(d,p);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof ye?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ui="/v1/images/generations",En="/v1/images/edits";function di(t){return t===ui||t===En}var li="/v1/images/models";async function ci(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Bd=16*1024*1024,pi=64*1024*1024;function fi(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function jt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function mi(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let p of o){if(p.type==="error"){let y=p.error??{};throw new K(502,`image upstream error: ${String(y.message??"upstream reported an error")}`)}if(p.type==="response.completed"){s=p.response??null;break}}if(s===null)throw new K(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new K(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(fi(d)===null)throw new K(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function hi(t){return t instanceof K?t:t instanceof z?new K(404,t.message):new K(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function gi(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return jt(r,new K(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function yi(t,e){t&&(t.outputUnits=e.images.length)}function wi(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var jd={model:!0,prompt:!0,response_format:!0,n:!0};async function _i(t,e,n){let r=n.maxBodyBytes??pi;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${ui}`);let o;try{o=JSON.parse((await Rn(t,r)).toString("utf8")||"{}")}catch(p){throw p instanceof ye?new K(413,p.message):new K(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new K(400,"request body must be a JSON object");let s=o;for(let p of Object.keys(s))if(!jd[p])throw new K(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new K(400,"model must be a string","model");await ci(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new K(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new K(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await gi(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let p=await mi(n.clients,a,l,n.turn?Ee(n.turn):void 0);yi(n.turn,p),wi(e,p)}catch(p){throw hi(p)}}catch(o){if(o instanceof ye){jt(e,new K(413,o.message));return}if(o instanceof K){jt(e,o);return}throw o}}var Hd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function vi(t,e,n){let r=n.maxBodyBytes??pi,o=n.maxImagePartBytes??Bd;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${En}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await xn(t,r)}catch(c){throw c instanceof ye?new K(413,c.message):new K(400,String(c instanceof Error?c.message:c))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new K(400,"model must be a string field","model");let d=u===null?void 0:u;await ci(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new K(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let c of i.keys())if(!Hd[c])throw new K(400,`form field "${c}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,c);let p=[];for(let c of["image","image[]"])for(let m of i.getAll(c)){if(!(m instanceof File))throw new K(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",c);if(m.size>o)throw new K(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,c);let w=new Uint8Array(await m.arrayBuffer()),R=fi(w);if(R===null)throw new K(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",c);p.push({bytes:w,mime:R})}if(p.length===0)throw new K(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await gi(n.imageModels,d,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:c,mime:m}of p)y.push({type:"input_image",image_url:`data:${m};base64,${Buffer.from(c).toString("base64")}`});try{let c=await mi(n.clients,d,y,n.turn?Ee(n.turn):void 0);yi(n.turn,c),wi(e,c)}catch(c){throw hi(c)}}catch(s){if(s instanceof ye){jt(e,new K(413,s.message));return}if(s instanceof K){jt(e,s);return}throw s}}k();var qt="/v1/audio/speech";function xi(t){return t===qt}var bi=4096,qd=18e4,Gd=5e3,Vd=64*1024*1024,ki=8,Si=5,An="voice_applied",Wd="X-Urun-Voice-Applied",q=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Nr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var In=class extends q{constructor(e){super(502,e)}};async function Jd(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Kd(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var zd=2;function Yd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>zd)return!1;return!0}function Xd(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Ri=new WeakMap,On=new WeakMap;function Qd(t,e){let n=On.get(t)??0;if(n>=ki)throw new q(503,`this model's speech queue is full \u2014 ${ki} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Si}s`,void 0,Si);On.set(t,n+1);let r=Ri.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ri.set(t,s),(async()=>{await r;try{return await e()}finally{On.set(t,(On.get(t)??1)-1),o()}})()}async function Zd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof fe))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Ht(t){return t instanceof q?t:t instanceof z?new q(404,t.message):new q(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function el(t,e,n,r,o,s,i){return Qd(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,l=!1,p=!1,y,c=new Promise(L=>{y=L}),m=()=>{l&&!p&&d>=o.quietRunFrames&&(p=!0,y())},w=e.onOutputAudio(L=>{let S=Buffer.from(L,"base64");if(S.byteLength===0)return;let x=Yd(S);if(!u){if(x)return;u=!0}a.push(S),d=x?d+1:0,m()}),R=null,g,v,b;try{b=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let S=new Promise(I=>{v=setTimeout(I,s.capMs)}),x=!1;for(;;){let I=b.next(),M=await Promise.race([I,S]);if(M===void 0){x=!0,I.catch(()=>{});break}if(M.done)break;let G=M.value;if(G.type==="error"){let Y=G.error??{};throw await b.return?.(),new q(502,`speech upstream error: ${String(Y.message??"upstream reported an error")}`)}if(G.type==="response.completed"){R=G.response??null,l=!0,m(),await b.return?.();break}}if(clearTimeout(v),x)throw new q(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(R===null)throw new q(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([c,new Promise(I=>{g=setTimeout(()=>{C=!0,I()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let I=R[An];if(typeof I!="string"||I!==r.voice){let M=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${An} ${JSON.stringify(I)}`:`no ${An} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw p?new In(M):new q(502,M)}}if(!u)throw new q(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!p&&d<1)throw new q(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let J=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(J),completed:R}}catch(L){throw L instanceof In||await Zd(t,n,b,s.returnBoundMs),L}finally{g!==void 0&&clearTimeout(g),v!==void 0&&clearTimeout(v),w()}})}async function tl(t,e,n){let r;try{r=await t(e)}catch(o){throw Ht(o)}return r?!0:(Nr(n,new q(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var nl={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},rl="wav, pcm";async function Ei(t,e,n){let r=n.maxBodyBytes??Vd,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${qt}`);let i;try{i=JSON.parse((await Rn(t,r)).toString("utf8")||"{}")}catch(b){throw b instanceof ye?new q(413,b.message):new q(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new q(400,"request body must be a JSON object");let a=i;for(let b of Object.keys(a))if(!nl[b])throw new q(400,`request field "${b}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,b);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new q(400,"input is required and must be a non-empty string","input");if(u.length>bi)throw new q(400,`input is ${u.length} chars \u2014 over the ${bi}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new q(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new q(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new q(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${qt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(b){throw Ht(b)}if(p.defect!==null)throw new q(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof l=="string"?l:void 0;if(y!==void 0&&p.published.length>0&&!p.published.includes(y))throw new q(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let c=a.response_format??"wav";if(c!=="wav"&&c!=="pcm")throw new q(400,`response_format ${JSON.stringify(c)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${rl} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new q(400,"stream_format, when present, must be a string","stream_format");let m=a.speed;if(m!==void 0){if(typeof m!="number"||!Number.isFinite(m))throw new q(400,"speed, when present, must be a number","speed");if(m!==1)throw new q(400,`speed=${JSON.stringify(m)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let w=a.instructions;if(w!==void 0){if(typeof w!="string")throw new q(400,"instructions, when present, must be a string","instructions");if(w.trim().length>0)throw new q(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await Jd(n.turn,n.clients,d);let R=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",R,R),!await tl(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new q(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new q(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let g;try{g=await n.clients.speechSessionHandle(d)}catch(b){throw Ht(b)}let v;try{v=await n.clients.openAudioOn(g)}catch(b){throw Ht(b)}n.turn&&(n.turn.sessionId=v.sessionId);try{let b=await el(n.clients,v,g,{model:d,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??qd,returnBoundMs:n.turnReturnBoundMs??Gd},s);if(b===null||s())return;if(Kd(n.turn,b.pcm.byteLength),e.statusCode=200,y===void 0){let L=b.completed[An];typeof L=="string"&&e.setHeader(Wd,L)}c==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Xd(b.pcm.byteLength),b.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(b.pcm))}catch(b){throw Ht(b)}}catch(i){if(i instanceof ye){Nr(e,new q(413,i.message));return}if(i instanceof q){Nr(e,i);return}throw i}}k();var Tn="/v1/audio/transcriptions";function Oi(t){return t===Tn}var Ai="/v1/audio/models",ol=16*1024*1024,sl=64*1024*1024,ne=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Dr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Ii(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function il(t){if(!Ii(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:l}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function al(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ul(t,e){t&&(t.outputUnits=e.seconds)}async function dl(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",p=String(d.message??"upstream reported an error");throw new ne(l==="invalid_request_error"?400:502,`transcription upstream error: ${p}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new ne(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return _t(i,a)}function Ti(t){return t instanceof ne?t:t instanceof z?new ne(404,t.message):new ne(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ll(t,e,n){let r;try{r=await t(e)}catch(o){throw Ti(o)}return r?!0:(Dr(n,new ne(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var cl=new Set(["file","model","language","response_format"]);async function Pi(t,e,n){let r=n.maxBodyBytes??sl,o=n.maxAudioPartBytes??ol;try{if(t.method!=="POST")throw new ne(405,`${String(t.method)} is not supported on ${Tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new ne(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await xn(t,r)}catch(g){throw g instanceof ye?new ne(413,g.message):new ne(400,String(g instanceof Error?g.message:g))}let a=new Map;for(let g of i.keys()){if(!cl.has(g))throw new ne(400,`form field "${g}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,g);a.set(g,(a.get(g)??0)+1)}for(let[g,v]of a)if(v>1)throw new ne(400,`form field "${g}" appears ${v} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,g);let u=i.get("model");if(u!==null&&typeof u!="string")throw new ne(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new ne(400,"language, when present, must be a non-empty string","language");let p=l===null?void 0:l,y=i.get("response_format")??"json";if(y!=="json")throw new ne(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let c=i.get("file");if(!(c instanceof File))throw new ne(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(c.size>o)throw new ne(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let m=new Uint8Array(await c.arrayBuffer());if(!Ii(m))throw new ne(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let w=il(m);if(w===null)throw new ne(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await al(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",m.length,m.length),!await ll(n.transcriptionModels,d,e))return;let R=[{type:"input_audio",input_audio:{data:Buffer.from(m).toString("base64"),format:"wav"}}];try{let g=await dl(n.clients,d,R,p,n.turn?Ee(n.turn):void 0);ul(n.turn,w),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw Ti(g)}}catch(s){if(s instanceof ye){Dr(e,new ne(413,s.message));return}if(s instanceof ne){Dr(e,s);return}throw s}}var Nn=require("@urun-sh/core");k();var Br="x-urun-profile",Gt="voice";var Re=class extends Error{status=400},pl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,fl=/\s/;function ml(t){return pl.test(t)}function Fr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Ci(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Mi(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new Re(`the ${Br} header is empty \u2014 the only profile this lane accepts is "${Gt}" (omit the header for the ordinary lane)`);if(d!==Gt)throw new Re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Gt)throw new Re(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Ci(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Ci(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Fr(u,"sentence_flush",!0),includeReasoning:Fr(u,"include_reasoning",!1),metadata:Fr(u,"metadata",!1)}}var Pn=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&ml(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(fl.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};k();var jr=Ye(require("crypto"),1),hl="urun-runtime-key-v1";function gl(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return jr.createHmac("sha256",t).update(`${hl}|${e}`,"ascii").digest("base64url")}var yl="decision-intake",Cn=6e4,wl=Cn/1e3+5,$i=3,Hr=15;function _l(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:yl,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=jr.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function vl(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function bl(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(Cn)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new Ne(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${Cn}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!vl(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=Hr)}var kl=Hr*1e3,Sl=Hr*500,Rl=256,Mn=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new Ne("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new Ne(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let l=null;for(let p=0;p<$i;p++){let y=this.pick(d);if(y===null)throw new Ne(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let c=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,m=_l(gl(this.opts.secret,c),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},wl);try{return{...await this.post(y,e,m),target:{...r,fnName:s}}}catch(w){if(w instanceof at)throw w;l=w;let R=this.replicas.get(y)??{outstanding:0,cooldownUntil:0};R.cooldownUntil=this.nowMs()+5e3,this.replicas.set(y,R);let g=this.presenceCache.get(u);g&&(g.rows=g.rows.filter(v=>v.address!==y),g.rows.length===0&&this.presenceCache.delete(u))}}throw new Ne(`no runtime for app=${o} answered within ${$i} attempts: ${String(l instanceof Error?l.message:l)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>kl)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>Sl&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=Rl;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return bl({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??Cn)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new at(s.status,i);return{status:s.status,body:i,completed:xl(i)}}finally{o.outstanding-=1}}};function xl(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var at=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},Ne=class extends Error{};function Vr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ol(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ue(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function me(t,e,n,r="invalid_request_error",o){ue(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Wr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);ue(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function De(t,e,n,r){ue(t,e,{type:"error",error:{type:n,message:r}})}function Fe(t,e,n){if(e==="anthropic"){ue(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ue(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Al=64*1024*1024,Vt=class extends Error{};async function Li(t,e=Al){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Vt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ut(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Ni(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function $n(t){let e=Ni(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Ui(t){let e=$n(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Il(t,e){let n=Ni(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Tl(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function Pl(t,e){let n=Tl(e);n&&(t.timing=n)}function Ve(t,e){Il(t,e),Pl(t,e)}async function Dn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Di(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Cl(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Ln=class extends Error{};function Ml(t,e){return Array.isArray(e)?e.map(n=>{let r=n;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 Ln(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function $l(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Ml(n.role,n.content)})}return e}function qr(t){return yt(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Ll(t,e,n,r,o,s){let i=Lt(s.id),a=t.stream===!0;if(s.model=ke(t),s.stream=a,await Dn(s,e,typeof t.model=="string"?t.model:void 0),a){let g;try{g=await Nt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(v){if(v instanceof z){Fe(r,"openai",v);return}if(v instanceof Oe){me(r,v.status,v.message);return}throw v}Vr(r);for await(let v of g.events)v.type==="error"&&(s.streamError=!0),v.type==="response.completed"&&Ve(s,v.response),r.write(`event: ${String(v.type??"message")}
|
|
26
|
+
${Wd(n)}\r
|
|
27
|
+
`),t.destroy()}function zd(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
28
|
+
`}function Yd(t){Le(process.stdout,t)}function Xd(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function jr(t){return t.audioSession?.audio.sessionId??void 0}function An(t,e){let n=new hi.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Gt)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=U("rtup"),d=Xd(o),l=R=>{(e.log??Yd)(zd(R))};l({stage:"accept",conn:u,model:d}),s.resume();let p=new AbortController,y=null,c=R=>{y??=R,p.abort(new Error(y))},m=()=>c("client socket closed"),w=()=>c("client socket closed (half-close)"),S=R=>c(`client socket error: ${R.message}`);s.once("close",m),s.once("end",w),s.once("error",S);let g=()=>{s.removeListener("close",m),s.removeListener("end",w),s.removeListener("error",S)},v=R=>{l({stage:"close",conn:u,model:d,...R})},b=R=>{let x=R,C=x.session!=null&&typeof x.session.sendResponseCreate=="function",W=x.clients!=null&&typeof x.clients.createResponse=="function";if(!C&&!W)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((I,M)=>{n.handleUpgrade(o,s,i,G=>{try{new qt({ws:G,binding:R,onClosed:(Y,de)=>{v({while:"live",reason:de.reason})}}),l({stage:"admit",conn:u,model:d,...jr(R)===void 0?{}:{session:jr(R)}}),I()}catch(Y){M(Y)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal).then(async R=>{if(p.signal.aborted){g();let x=jr(R);try{await R.release?.()}catch(C){v({while:"queued",...x===void 0?{}:{session:x},reason:y??"client socket closed",release_failed:C instanceof Error?C.message:String(C)});return}v({while:"queued",...x===void 0?{}:{session:x},reason:y??"client socket closed",released:!0}),s.destroy();return}g(),await b(R)}).catch(R=>{let x=R instanceof mi.SessionFailedError?Sn(R):null,C=null;if(R!==null&&typeof R=="object"&&"status"in R){let M=R.status;typeof M=="number"&&(C=M)}let W=C??x?.status??502,I=R instanceof Error?R.message:String(R);v({while:"queued",...p.signal.aborted?{reason:y??"client socket closed"}:{reason:I,status:W}}),s.destroyed||Kd(s,W,I)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}k();k();var Dl=require("http");k();k();var ye=class extends Error{};async function In(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ye(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ye(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Tn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new ye(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let p of l)i.append(d,p);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof ye?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var gi="/v1/images/generations",Pn="/v1/images/edits";function yi(t){return t===gi||t===Pn}var wi="/v1/images/models";async function _i(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Qd=16*1024*1024,vi=64*1024*1024;function bi(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Vt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function ki(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let p of o){if(p.type==="error"){let y=p.error??{};throw new K(502,`image upstream error: ${String(y.message??"upstream reported an error")}`)}if(p.type==="response.completed"){s=p.response??null;break}}if(s===null)throw new K(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new K(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(bi(d)===null)throw new K(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function Si(t){return t instanceof K?t:t instanceof z?new K(404,t.message):new K(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ri(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Vt(r,new K(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function xi(t,e){t&&(t.outputUnits=e.images.length)}function Ei(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Zd={model:!0,prompt:!0,response_format:!0,n:!0};async function Oi(t,e,n){let r=n.maxBodyBytes??vi;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${gi}`);let o;try{o=JSON.parse((await In(t,r)).toString("utf8")||"{}")}catch(p){throw p instanceof ye?new K(413,p.message):new K(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new K(400,"request body must be a JSON object");let s=o;for(let p of Object.keys(s))if(!Zd[p])throw new K(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new K(400,"model must be a string","model");await _i(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new K(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new K(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Ri(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let p=await ki(n.clients,a,l,n.turn?Ee(n.turn):void 0);xi(n.turn,p),Ei(e,p)}catch(p){throw Si(p)}}catch(o){if(o instanceof ye){Vt(e,new K(413,o.message));return}if(o instanceof K){Vt(e,o);return}throw o}}var el={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ai(t,e,n){let r=n.maxBodyBytes??vi,o=n.maxImagePartBytes??Qd;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${Pn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await Tn(t,r)}catch(c){throw c instanceof ye?new K(413,c.message):new K(400,String(c instanceof Error?c.message:c))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new K(400,"model must be a string field","model");let d=u===null?void 0:u;await _i(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new K(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let c of i.keys())if(!el[c])throw new K(400,`form field "${c}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,c);let p=[];for(let c of["image","image[]"])for(let m of i.getAll(c)){if(!(m instanceof File))throw new K(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",c);if(m.size>o)throw new K(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,c);let w=new Uint8Array(await m.arrayBuffer()),S=bi(w);if(S===null)throw new K(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",c);p.push({bytes:w,mime:S})}if(p.length===0)throw new K(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Ri(n.imageModels,d,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:c,mime:m}of p)y.push({type:"input_image",image_url:`data:${m};base64,${Buffer.from(c).toString("base64")}`});try{let c=await ki(n.clients,d,y,n.turn?Ee(n.turn):void 0);xi(n.turn,c),Ei(e,c)}catch(c){throw Si(c)}}catch(s){if(s instanceof ye){Vt(e,new K(413,s.message));return}if(s instanceof K){Vt(e,s);return}throw s}}k();var Wt="/v1/audio/speech";function Mi(t){return t===Wt}var Ii=4096,tl=18e4,nl=5e3,rl=64*1024*1024,Ti=8,Pi=5,Mn="voice_applied",ol="X-Urun-Voice-Applied",q=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Hr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var $n=class extends q{constructor(e){super(502,e)}};async function sl(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function il(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var al=2;function ul(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>al)return!1;return!0}function dl(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Ci=new WeakMap,Cn=new WeakMap;function ll(t,e){let n=Cn.get(t)??0;if(n>=Ti)throw new q(503,`this model's speech queue is full \u2014 ${Ti} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Pi}s`,void 0,Pi);Cn.set(t,n+1);let r=Ci.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ci.set(t,s),(async()=>{await r;try{return await e()}finally{Cn.set(t,(Cn.get(t)??1)-1),o()}})()}async function cl(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof fe))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Jt(t){return t instanceof q?t:t instanceof z?new q(404,t.message):new q(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function pl(t,e,n,r,o,s,i){return ll(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,l=!1,p=!1,y,c=new Promise(L=>{y=L}),m=()=>{l&&!p&&d>=o.quietRunFrames&&(p=!0,y())},w=e.onOutputAudio(L=>{let R=Buffer.from(L,"base64");if(R.byteLength===0)return;let x=ul(R);if(!u){if(x)return;u=!0}a.push(R),d=x?d+1:0,m()}),S=null,g,v,b;try{b=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let R=new Promise(I=>{v=setTimeout(I,s.capMs)}),x=!1;for(;;){let I=b.next(),M=await Promise.race([I,R]);if(M===void 0){x=!0,I.catch(()=>{});break}if(M.done)break;let G=M.value;if(G.type==="error"){let Y=G.error??{};throw await b.return?.(),new q(502,`speech upstream error: ${String(Y.message??"upstream reported an error")}`)}if(G.type==="response.completed"){S=G.response??null,l=!0,m(),await b.return?.();break}}if(clearTimeout(v),x)throw new q(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(S===null)throw new q(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([c,new Promise(I=>{g=setTimeout(()=>{C=!0,I()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let I=S[Mn];if(typeof I!="string"||I!==r.voice){let M=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${Mn} ${JSON.stringify(I)}`:`no ${Mn} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw p?new $n(M):new q(502,M)}}if(!u)throw new q(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!p&&d<1)throw new q(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let W=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(W),completed:S}}catch(L){throw L instanceof $n||await cl(t,n,b,s.returnBoundMs),L}finally{g!==void 0&&clearTimeout(g),v!==void 0&&clearTimeout(v),w()}})}async function fl(t,e,n){let r;try{r=await t(e)}catch(o){throw Jt(o)}return r?!0:(Hr(n,new q(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var ml={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},hl="wav, pcm";async function $i(t,e,n){let r=n.maxBodyBytes??rl,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Wt}`);let i;try{i=JSON.parse((await In(t,r)).toString("utf8")||"{}")}catch(b){throw b instanceof ye?new q(413,b.message):new q(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new q(400,"request body must be a JSON object");let a=i;for(let b of Object.keys(a))if(!ml[b])throw new q(400,`request field "${b}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,b);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new q(400,"input is required and must be a non-empty string","input");if(u.length>Ii)throw new q(400,`input is ${u.length} chars \u2014 over the ${Ii}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new q(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new q(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new q(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Wt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(b){throw Jt(b)}if(p.defect!==null)throw new q(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof l=="string"?l:void 0;if(y!==void 0&&p.published.length>0&&!p.published.includes(y))throw new q(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let c=a.response_format??"wav";if(c!=="wav"&&c!=="pcm")throw new q(400,`response_format ${JSON.stringify(c)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${hl} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new q(400,"stream_format, when present, must be a string","stream_format");let m=a.speed;if(m!==void 0){if(typeof m!="number"||!Number.isFinite(m))throw new q(400,"speed, when present, must be a number","speed");if(m!==1)throw new q(400,`speed=${JSON.stringify(m)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let w=a.instructions;if(w!==void 0){if(typeof w!="string")throw new q(400,"instructions, when present, must be a string","instructions");if(w.trim().length>0)throw new q(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await sl(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await fl(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new q(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new q(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let g;try{g=await n.clients.speechSessionHandle(d)}catch(b){throw Jt(b)}let v;try{v=await n.clients.openAudioOn(g)}catch(b){throw Jt(b)}n.turn&&(n.turn.sessionId=v.sessionId);try{let b=await pl(n.clients,v,g,{model:d,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??tl,returnBoundMs:n.turnReturnBoundMs??nl},s);if(b===null||s())return;if(il(n.turn,b.pcm.byteLength),e.statusCode=200,y===void 0){let L=b.completed[Mn];typeof L=="string"&&e.setHeader(ol,L)}c==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([dl(b.pcm.byteLength),b.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(b.pcm))}catch(b){throw Jt(b)}}catch(i){if(i instanceof ye){Hr(e,new q(413,i.message));return}if(i instanceof q){Hr(e,i);return}throw i}}k();var Ln="/v1/audio/transcriptions";function Li(t){return t===Ln}var Ni="/v1/audio/models",gl=16*1024*1024,yl=64*1024*1024,ne=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function qr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Ui(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function wl(t){if(!Ui(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:l}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function _l(t,e,n){if(t){if(t.model=ke({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function vl(t,e){t&&(t.outputUnits=e.seconds)}async function bl(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",p=String(d.message??"upstream reported an error");throw new ne(l==="invalid_request_error"?400:502,`transcription upstream error: ${p}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new ne(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return St(i,a)}function Di(t){return t instanceof ne?t:t instanceof z?new ne(404,t.message):new ne(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function kl(t,e,n){let r;try{r=await t(e)}catch(o){throw Di(o)}return r?!0:(qr(n,new ne(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Sl=new Set(["file","model","language","response_format"]);async function Fi(t,e,n){let r=n.maxBodyBytes??yl,o=n.maxAudioPartBytes??gl;try{if(t.method!=="POST")throw new ne(405,`${String(t.method)} is not supported on ${Ln}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new ne(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await Tn(t,r)}catch(g){throw g instanceof ye?new ne(413,g.message):new ne(400,String(g instanceof Error?g.message:g))}let a=new Map;for(let g of i.keys()){if(!Sl.has(g))throw new ne(400,`form field "${g}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,g);a.set(g,(a.get(g)??0)+1)}for(let[g,v]of a)if(v>1)throw new ne(400,`form field "${g}" appears ${v} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,g);let u=i.get("model");if(u!==null&&typeof u!="string")throw new ne(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new ne(400,"language, when present, must be a non-empty string","language");let p=l===null?void 0:l,y=i.get("response_format")??"json";if(y!=="json")throw new ne(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let c=i.get("file");if(!(c instanceof File))throw new ne(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(c.size>o)throw new ne(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let m=new Uint8Array(await c.arrayBuffer());if(!Ui(m))throw new ne(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let w=wl(m);if(w===null)throw new ne(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await _l(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",m.length,m.length),!await kl(n.transcriptionModels,d,e))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(m).toString("base64"),format:"wav"}}];try{let g=await bl(n.clients,d,S,p,n.turn?Ee(n.turn):void 0);vl(n.turn,w),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw Di(g)}}catch(s){if(s instanceof ye){qr(e,new ne(413,s.message));return}if(s instanceof ne){qr(e,s);return}throw s}}var Hn=require("@urun-sh/core");k();var Vr="x-urun-profile",Kt="voice";var Re=class extends Error{status=400},Rl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,xl=/\s/;function El(t){return Rl.test(t)}function Gr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Bi(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function ji(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new Re(`the ${Vr} header is empty \u2014 the only profile this lane accepts is "${Kt}" (omit the header for the ordinary lane)`);if(d!==Kt)throw new Re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${Kt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Kt)throw new Re(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Kt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Bi(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Bi(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Gr(u,"sentence_flush",!0),includeReasoning:Gr(u,"include_reasoning",!1),metadata:Gr(u,"metadata",!1)}}var Nn=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&El(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(xl.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};k();var Jr=Qe(require("crypto"),1),Ol="urun-runtime-key-v1";function Al(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return Jr.createHmac("sha256",t).update(`${Ol}|${e}`,"ascii").digest("base64url")}var Il="decision-intake",Un=6e4,Tl=Un/1e3+5,Hi=3,Wr=15;function Pl(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:Il,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=Jr.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function Cl(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function Ml(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(Un)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new Ue(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${Un}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!Cl(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=Wr)}var $l=Wr*1e3,Ll=Wr*500,Nl=256,Dn=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new Ue("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new Ue(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let l=null;for(let p=0;p<Hi;p++){let y=this.pick(d);if(y===null)throw new Ue(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let c=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,m=Pl(Al(this.opts.secret,c),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},Tl);try{return{...await this.post(y,e,m),target:{...r,fnName:s}}}catch(w){if(w instanceof lt)throw w;l=w;let S=this.replicas.get(y)??{outstanding:0,cooldownUntil:0};S.cooldownUntil=this.nowMs()+5e3,this.replicas.set(y,S);let g=this.presenceCache.get(u);g&&(g.rows=g.rows.filter(v=>v.address!==y),g.rows.length===0&&this.presenceCache.delete(u))}}throw new Ue(`no runtime for app=${o} answered within ${Hi} attempts: ${String(l instanceof Error?l.message:l)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>$l)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>Ll&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=Nl;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return Ml({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??Un)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new lt(s.status,i);return{status:s.status,body:i,completed:Ul(i)}}finally{o.outstanding-=1}}};function Ul(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var lt=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},Ue=class extends Error{};function Yr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Fl(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ue(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function me(t,e,n,r="invalid_request_error",o){ue(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Xr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);ue(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function De(t,e,n,r){ue(t,e,{type:"error",error:{type:n,message:r}})}function Fe(t,e,n){if(e==="anthropic"){ue(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ue(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Bl=64*1024*1024,zt=class extends Error{};async function qi(t,e=Bl){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new zt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ct(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Vi(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Fn(t){let e=Vi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Gi(t){let e=Fn(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function jl(t,e){let n=Vi(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Hl(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function ql(t,e){let n=Hl(e);n&&(t.timing=n)}function Je(t,e){jl(t,e),ql(t,e)}async function qn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Ji(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Gl(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Bn=class extends Error{};function Vl(t,e){return Array.isArray(e)?e.map(n=>{let r=n;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 Bn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Jl(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Vl(n.role,n.content)})}return e}function Kr(t){return bt(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Wl(t,e,n,r,o,s){let i=Ft(s.id),a=t.stream===!0;if(s.model=ke(t),s.stream=a,await qn(s,e,typeof t.model=="string"?t.model:void 0),a){let g;try{g=await jt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(v){if(v instanceof z){Fe(r,"openai",v);return}if(v instanceof Oe){me(r,v.status,v.message);return}throw v}Yr(r);for await(let v of g.events)v.type==="error"&&(s.streamError=!0),v.type==="response.completed"&&Je(s,v.response),r.write(`event: ${String(v.type??"message")}
|
|
29
29
|
data: ${JSON.stringify(v)}
|
|
30
30
|
|
|
31
31
|
`);r.write(`data: [DONE]
|
|
32
32
|
|
|
33
|
-
`),r.end();return}let u;try{u=
|
|
33
|
+
`),r.end();return}let u;try{u=Rt(n,t)}catch(g){if(g instanceof Oe){me(r,g.status,g.message);return}throw g}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=ke(t);o.model(l);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await Ir(e,t,u,!1,Ee(s))}catch(g){if(g instanceof z){Fe(r,"openai",g);return}if(g instanceof Oe){me(r,g.status,g.message);return}throw g}let c=[],m=null;for await(let g of o.track(y,l,s)){if(c.push(g),g.type==="error"){Xr(r,g);return}g.type==="response.completed"&&(m=g.response)}if(m==null){me(r,502,"upstream produced no response.completed event","upstream_error");return}Je(s,m);let w=St(c,m),S=dt(p,bt(m).length,w);if(S){me(r,502,ut(l,S),"upstream_error");return}d&&n.remember(i,u,Ar(m,w),d),ue(r,200,{...m,id:i})}async function Kl(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){me(n,400,"chat/completions requires a messages array");return}let a;try{a=ji(s,t)}catch(I){if(I instanceof Re){me(n,I.status,I.message);return}throw I}let u=String(t.model??"urun"),d=ei(o.id),l;try{l=Jl(i)}catch(I){if(I instanceof Bn){me(n,400,I.message);return}throw I}let p=ke(t);r.model(p),o.model=p,o.stream=t.stream===!0,await qn(o,e,typeof t.model=="string"?t.model:void 0);let y=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let I;try{I=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(M){if(M instanceof z){Fe(n,"openai",M);return}throw M}if(I!==null){try{let M=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=Ct(M.target),Je(o,M.completed),ue(n,200,{...M.body,id:d})}catch(M){if(M instanceof z){Fe(n,"openai",M);return}if(M instanceof lt){ue(n,M.status,M.body);return}if(M instanceof Ue){me(n,503,M.message,"upstream_error");return}throw M}return}}let c;try{c=await e.createResponse({model:t.model,input:l,stream:!0,tools:Gl(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},Ee(o))}catch(I){if(I instanceof z){Fe(n,"openai",I);return}throw I}if(t.stream===!0){a?Fl(n):Yr(n);let I=[],M=new Ye,G="",Y=a?new Nn(a,ge=>{n.write(`data: ${JSON.stringify(ct(d,u,{content:ge},null))}
|
|
34
34
|
|
|
35
35
|
`)}):null,de=ge=>{Y?.flush(),n.write(ge),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
36
36
|
|
|
37
|
-
`),n.write(`data: ${JSON.stringify(
|
|
37
|
+
`),n.write(`data: ${JSON.stringify(ct(d,u,{role:"assistant"},null))}
|
|
38
38
|
|
|
39
|
-
`);for await(let te of r.track(c,p,o)){I.push(te);let le=
|
|
39
|
+
`);for await(let te of r.track(c,p,o)){I.push(te);let le=kt(te);if(te.type==="response.output_text.delta"&&typeof te.delta=="string")G+=te.delta,Y?Y.push(te.delta):n.write(`data: ${JSON.stringify(ct(d,u,{content:te.delta},null))}
|
|
40
40
|
|
|
41
|
-
`);else if(te.type==="response.reasoning_text.delta"&&typeof te.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(
|
|
41
|
+
`);else if(te.type==="response.reasoning_text.delta"&&typeof te.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(ct(d,u,{reasoning_content:te.delta},null))}
|
|
42
42
|
|
|
43
|
-
`);else if(le){Y?.flush();let{call:Me,isNew:H}=M.add(le),O=H?{index:le.tool_index,id:Me.id??`call_${le.tool_index}`,type:"function",function:{name:Me.name??"",arguments:le.delta}}:{index:le.tool_index,function:{arguments:le.delta}};n.write(`data: ${JSON.stringify(
|
|
43
|
+
`);else if(le){Y?.flush();let{call:Me,isNew:H}=M.add(le),O=H?{index:le.tool_index,id:Me.id??`call_${le.tool_index}`,type:"function",function:{name:Me.name??"",arguments:le.delta}}:{index:le.tool_index,function:{arguments:le.delta}};n.write(`data: ${JSON.stringify(ct(d,u,{tool_calls:[O]},null))}
|
|
44
44
|
|
|
45
45
|
`)}else if(te.type==="error"){o.streamError=!0,de(`data: ${JSON.stringify({error:te})}
|
|
46
46
|
|
|
47
|
-
`);return}}let ge=
|
|
47
|
+
`);return}}let ge=Kr(Ne(I)),ve=dt(y,M.size+ge.length,G);if(ve){o.streamError=!0,de(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ut(p,ve)}})}
|
|
48
48
|
|
|
49
|
-
`);return}Y?.flush(),M.size===0&&ge.length>0&&n.write(`data: ${JSON.stringify(
|
|
49
|
+
`);return}Y?.flush(),M.size===0&&ge.length>0&&n.write(`data: ${JSON.stringify(ct(d,u,{tool_calls:ge},null))}
|
|
50
50
|
|
|
51
|
-
`);let Ie=M.size>0||ge.length>0;n.write(`data: ${JSON.stringify(
|
|
51
|
+
`);let Ie=M.size>0||ge.length>0;n.write(`data: ${JSON.stringify(ct(d,u,{},Ie?"tool_calls":"stop"))}
|
|
52
52
|
|
|
53
|
-
`);let ee
|
|
53
|
+
`);let ee=Fn(Ne(I));Je(o,Ne(I)),ee&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Gi(Ne(I))})}
|
|
54
54
|
|
|
55
55
|
`),n.write(`data: [DONE]
|
|
56
56
|
|
|
57
|
-
`),n.end();return}finally{Y?.flush(),Y?.dispose()}}let m="",w="",
|
|
58
|
-
data: ${JSON.stringify({type:C,...
|
|
57
|
+
`),n.end();return}finally{Y?.flush(),Y?.dispose()}}let m="",w="",S=[],g=new Ye;for await(let I of r.track(c,p,o)){S.push(I),I.type==="response.output_text.delta"&&typeof I.delta=="string"&&(m+=I.delta),I.type==="response.reasoning_text.delta"&&typeof I.delta=="string"&&(w+=I.delta);let M=kt(I);if(M&&g.add(M),I.type==="error"){Xr(n,I);return}}let v=Ne(S);Je(o,v);let b=Kr(v),L=b.length>0?b:Kr({output:g.items()}),R=dt(y,L.length,m);if(R){me(n,502,ut(p,R),"upstream_error");return}let x=L.map(({index:I,...M})=>M),C={role:"assistant",content:m||null},W=w||Ji(v);W&&(C.reasoning_content=W),x.length>0&&(C.tool_calls=x),ue(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:C,finish_reason:x.length>0?"tool_calls":"stop"}],usage:Gi(v)})}var zl="reflex-latest";async function Yl(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){me(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:zl,i=ke({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){me(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){me(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){me(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await qn(o,e,s),e.stateless?.enabled){let c;try{c=await e.stateless.targetFor(s)}catch(m){if(m instanceof z){Fe(n,"openai",m);return}throw m}if(c!==null){try{let m=await e.stateless.decide(t,s);o.catalog=Ct(m.target),Je(o,m.completed),ue(n,200,m.body)}catch(m){if(m instanceof z){Fe(n,"openai",m);return}if(m instanceof lt){ue(n,m.status,m.body);return}if(m instanceof Ue){me(n,503,m.message,"upstream_error");return}throw m}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Ee(o))}catch(c){if(c instanceof z){Fe(n,"openai",c);return}throw c}let d=[];try{for await(let c of r.track(u,i,o))if(d.push(c),c.type==="error"){Xr(n,c);return}}catch(c){if(c instanceof z){Fe(n,"openai",c);return}throw c}let l=Ne(d);if(l==null){me(n,502,"upstream produced no response.completed event","upstream_error");return}Je(o,l);let p=St(d,l),y;try{y=JSON.parse(p)}catch{me(n,502,"systemone answer was not valid JSON","upstream_error");return}if(y===null||typeof y!="object"||Array.isArray(y)){me(n,502,"systemone answer was not a JSON object","upstream_error");return}ue(n,200,y)}function Xl(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Yt=class extends Error{};function jn(t){return new Yt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ql(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function Zl(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Yt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function ec(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw jn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw jn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function tc(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw jn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:ec(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw jn(a)}}return s(),r}function zr(t){return bt(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function nc(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){De(n,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){De(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){De(n,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(C=>typeof C!="string"))){De(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=ti(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Xl(t.system)});for(let C of s)u.push(...tc(C));d=Zl(t.tool_choice)}catch(C){if(C instanceof Yt){De(n,400,"invalid_request_error",C.message);return}throw C}let l=ke(t);r.model(l),o.model=l,o.stream=t.stream===!0,await qn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:u,stream:!0,tools:Ql(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Ee(o))}catch(C){if(C instanceof z){Fe(n,"anthropic",C);return}throw C}let c=(C,W)=>{n.destroyed||n.write(`event: ${C}
|
|
58
|
+
data: ${JSON.stringify({type:C,...W})}
|
|
59
59
|
|
|
60
|
-
`)};if(t.stream===!0){let C=r.track(y,l,o);
|
|
60
|
+
`)};if(t.stream===!0){let C=r.track(y,l,o);Yr(n),c("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let W=0,I="",M=0,G="none",Y=()=>G,de=-1,ge=-1,ve=new Ye,Ie=[],ee=()=>{G!=="none"&&(G="none",c("content_block_stop",{index:de}))},te=(j,he)=>{ee(),G=j,de=M++,c("content_block_start",{index:de,content_block:he})};for await(let j of C){if(n.destroyed)break;Ie.push(j);let he=kt(j);if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")Y()!=="thinking"&&te("thinking",{type:"thinking",thinking:""}),c("content_block_delta",{index:de,delta:{type:"thinking_delta",thinking:j.delta}});else if(j.type==="response.output_text.delta"&&typeof j.delta=="string")Y()!=="text"&&te("text",{type:"text",text:""}),W+=1,I+=j.delta,c("content_block_delta",{index:de,delta:{type:"text_delta",text:j.delta}});else if(he){let{call:$e}=ve.add(he);(Y()!=="tool"||he.tool_index!==ge)&&(ge=he.tool_index,te("tool",{type:"tool_use",id:$e.id??`call_${he.tool_index}`,name:$e.name??"",input:{}})),he.delta&&c("content_block_delta",{index:de,delta:{type:"input_json_delta",partial_json:he.delta}})}else if(j.type==="error"){o.streamError=!0,c("error",{error:{type:"api_error",message:JSON.stringify(j)}}),n.end();return}}if(n.destroyed)return;let le=Ne(Ie),Me=bt(le),H=dt(p,ve.size+Me.length,I);if(H){o.streamError=!0,c("error",{error:{type:"api_error",message:ut(l,H)}}),n.end();return}ee();let O=[];if(ve.size===0)try{O=zr(le)}catch(j){o.streamError=!0,c("error",{error:{type:"api_error",message:String(j instanceof Error?j.message:j)}}),n.end();return}M===0&&O.length===0&&(te("text",{type:"text",text:""}),ee()),O.forEach(j=>{let he=M++;c("content_block_start",{index:he,content_block:{...j,input:{}}}),c("content_block_delta",{index:he,delta:{type:"input_json_delta",partial_json:JSON.stringify(j.input??{})}}),c("content_block_stop",{index:he})});let X=ve.size>0||O.length>0,Te=Fn(le);Je(o,le),c("message_delta",{delta:{stop_reason:X?"tool_use":"end_turn"},usage:Te?{input_tokens:Te.input_tokens,output_tokens:Te.output_tokens}:{output_tokens:W}}),c("message_stop",{}),n.end();return}let m="",w="",S=[],g=new Ye;for await(let C of r.track(y,l,o)){S.push(C),C.type==="response.output_text.delta"&&typeof C.delta=="string"&&(m+=C.delta),C.type==="response.reasoning_text.delta"&&typeof C.delta=="string"&&(w+=C.delta);let W=kt(C);if(W&&g.add(W),C.type==="error"){let I=C.error,M=I?.type==="invalid_request_error";De(n,M?400:502,M?"invalid_request_error":"api_error",I?.message??JSON.stringify(C));return}if(n.destroyed)break}if(n.destroyed)return;let v=Ne(S);Je(o,v);let b;try{b=zr(v),b.length===0&&g.size>0&&(b=zr({output:g.items()}))}catch(C){De(n,502,"api_error",String(C instanceof Error?C.message:C));return}let L=dt(p,b.length,m);if(L){De(n,502,"api_error",ut(l,L));return}let R=[],x=w||Ji(v);x&&R.push({type:"thinking",thinking:x}),(m||b.length===0)&&R.push({type:"text",text:m}),R.push(...b),ue(n,200,{id:a,type:"message",role:"assistant",content:R,model:i,stop_reason:b.length>0?"tool_use":"end_turn",usage:Fn(v)??{input_tokens:0,output_tokens:0}})}function rc(t){Le(process.stdout,t)}function Wi(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??rc,a=t.observe,u=new it;return(d,l)=>{let p=new URL(d.url??"/","http://localhost"),y=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),c=(v,b,L,R,x)=>y?De(l,v,R,b):me(l,v,b,L,x),m=Or(p.pathname),w=p.pathname.startsWith("/partners/"),S=m||w?{id:Dt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;S&&(l.setHeader(Qs,S.id),l.once("close",()=>{let v=ni({turn:S,method:d.method??"",path:p.pathname,res:l});i(ri(v)),a?.(v),us({record:v,ledger:t.ledger??null,req:d})}));let g=()=>Zs(p.pathname,S);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ue(l,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ue(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){c(401,"invalid local proxy api key","authentication_error","authentication_error");return}let v=p.pathname===un?"canonical":p.pathname===Lt?"huggingface":null;if(v){if(d.method!=="POST"){c(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let x=t.usage;if(!x){c(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let C=x.authorize(d),W;try{W=await qi(d,fs)}catch(G){if(G instanceof zt){c(413,G.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=G=>x.lookup(C,G),M;try{if(v==="canonical"){let G=ms(W),Y=await I(G);dn(Y,G),M={requests:Y}}else M=await ys(W,I)}catch(G){if(G instanceof ze){c(G.status,G.message,"invalid_request_error","invalid_request_error");return}throw G}ue(l,200,M);return}if(d.method==="GET"&&p.pathname===et){let x=await s(d);if(S&&(S.org=x.tenant??null),!x.openRouterModels){c(501,`GET ${et} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ue(l,200,await x.openRouterModels());return}if(p.pathname.startsWith("/partners/")){c(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Lt} and GET ${et}`,"invalid_request_error","not_found_error");return}let b=await s(d);if(S&&(S.org=b.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:et}),l.end();return}ue(l,200,await b.listModels());return}if(d.method==="GET"&&p.pathname===wi){if(!b.listImageModels){c(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ue(l,200,await b.listImageModels());return}if(yi(p.pathname)){if(!b.supportsImages){c(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let x={clients:b,imageModels:b.supportsImages,stats:u,turn:g()};p.pathname===Pn?await Ai(d,l,x):await Oi(d,l,x);return}if(d.method==="GET"&&p.pathname===Ni){if(!b.listSpeechToTextModels){c(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ue(l,200,await b.listSpeechToTextModels());return}if(Li(p.pathname)){if(!b.supportsTranscription){c(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Ln}`,"not_implemented","not_implemented_error");return}let x={clients:b,transcriptionModels:b.supportsTranscription,stats:u,turn:g()};await Fi(d,l,x);return}if(Mi(p.pathname)){if(!b.supportsSpeech){c(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Wt}`,"not_implemented","not_implemented_error");return}let x={clients:b,speechModels:b.supportsSpeech,stats:u,turn:g()};await $i(d,l,x);return}if(d.method!=="POST"){c(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let L;try{L=await qi(d)}catch(x){if(x instanceof zt){c(413,x.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=Buffer.byteLength(JSON.stringify(L));if(p.pathname==="/v1/responses"){u.request("responses",R,R),await Wl(L,b,Bt(b),l,u,g());return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",R,R),await Kl(L,b,l,u,g(),d.headers[Vr]);return}if(p.pathname==="/v1/systemone"){u.request("systemone",R,R),await Yl(L,b,l,u,g());return}if(p.pathname==="/v1/messages"){u.request("messages",R,R),await nc(L,b,l,u,g());return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",R,R),De(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}c(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(v=>{let b=String(v instanceof Error?v.message:v);if(!l.headersSent){let L=o?.(v)??null;if(L){c(L.status,b,L.openaiType,L.anthropicType);return}if(v instanceof Hn.SessionAllocationError){let R=kn(v.code);if(R){let x=v.retryAfterSeconds??(R.status===429?30:void 0);x!==void 0&&l.setHeader("Retry-After",String(x)),c(R.status,Lr(R,v.code??void 0),R.openaiType,R.anthropicType,R.code);return}}if(v instanceof Hn.SessionFailedError){let R=Sn(v);if(R){let x=R.status===429?30:void 0;x!==void 0&&l.setHeader("Retry-After",String(x)),c(R.status,Lr(R,v.status.sessionId?`session ${v.status.sessionId}`:void 0),R.openaiType,R.anthropicType,R.code);return}}if(v instanceof re){c(502,b,"upstream_error","api_error");return}c(500,b,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0),l.destroyed||(y?l.write(`event: error
|
|
61
61
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:b}})}
|
|
62
62
|
|
|
63
63
|
`):l.write(`data: ${JSON.stringify({error:{message:b,type:"upstream_error"}})}
|
|
64
64
|
|
|
65
|
-
`)),l.end()})}}var Fn=(t,e)=>Object.assign(new Error(e),{status:t});function Bi(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function ji(t,e,n){if(!t.supportsAudio)throw Fn(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof z?Fn(404,a.message):a}if(!r)throw Fn(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw Fn(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}k();var jn=require("@urun-sh/core"),Ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},kt=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Jt(t){let e=(t??"").trim();if(e==="")throw new Ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Wl=60,Jl=6e4,Kl=4096;function zl(t){return t===401||t===403}var Bn=class{constructor(e){this.opts=e;this.mint=e.mint??jn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Ae("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Jl)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Wl})).orgId}catch(o){throw o instanceof jn.ClientTokenError&&zl(o.status)?(this.cache.delete(e),new Ae("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new kt(`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 kt("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>=Kl){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};k();var Kn=require("crypto");k();var dt=require("@urun-sh/core");k();k();k();k();function Hi(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function qi(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}k();k();function Gi(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 e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Yl="llm-resp";async function*Jr(t,e){let n=`${Yl}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield Gi(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var qn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=qi(e,n,this.consumerId);return this.write(r),Jr(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Hi(e,n,r,this.consumerId);return this.write(o),Jr(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Vi=0;function Xl(){return Vi+=1,`req_${Date.now().toString(36)}_${Vi.toString(36)}`}var Gn=class{transport;constructor(e){this.transport=new qn(e)}responses={create:async e=>{let n=Xl(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};k();async function Wi(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}k();var Ji=require("@urun-sh/core"),Kr=2;function Ql(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Zl(t){let e=t?.type;return e==="response.completed"||e==="error"}function Ki(t){return async function(n,r){return(async function*(){for(let s=1;s<=Kr;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,l=!1;try{let p=await t.createStream(a,n);for await(let y of p){if(Zl(y)&&(d=!0),Ql(y)){if(s>1)continue}else l=!0;yield y}}catch(p){if(p instanceof Ji.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,p)}catch{}throw p}if(s<Kr&&!l){await t.evict(i,a);continue}throw p}if(d)return;if(s<Kr&&!l){await t.evict(i,a);continue}return}})()}}k();var ec=3,tc="llm",nc=new Set(["paused","error"]);function zi(t,e){let n=t.doc(tc),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" 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 s=null,i=!1,a=new Set,u=[],d=l=>{if(!s){s=l;for(let p of[...a])p(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<ec||d(new fe(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.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&&u.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&nc.has(l.name)&&d(new fe(`the pooled session for app "${e}" lost its compute binding (phase "${l.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(l){return s?(l(s),()=>{}):(a.add(l),()=>a.delete(l))},dispose(){a.clear();for(let l of u.splice(0))l()}}}async function*zr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function Yi(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function rc(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(Qe)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),l=e.sharedApp?{sharedApp:!0,...d}:d,p=w=>({session:w,responses:new Gn(w),gone:zi(w,n)});if(s.lane==="jwt"){let w=(0,dt.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return p(Yi(w,e.appSlug,u,l))}let{apiKey:y,gatewayUrl:c}=s,m=(0,dt.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,dt.createClientToken)(y,{baseUrl:c,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return p(Yi(m,e.appSlug,u,l))}function oc(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function sc(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var ic=new Set(["error","paused"]);function Qr(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=rc(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new Qt({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Uo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>Wi(n):null,listPrices:n?()=>ko(n):null,shared:e.lane==="api-key"?()=>yo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:oc});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ot({appSlug:t.defaultApp}))),s}async function Yr(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:dt.DEFAULT_WHEN_LIVE_TIMEOUT_MS,signal:e})}async function Xi(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Xr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Zr(t,e=bs,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=new WeakMap,d=c=>{let m=c.session.id;return typeof m=="string"&&m.length>0?m:null},l=c=>{let m=o.get(c);if(!m){let w={waiting:0,gone:new AbortController};u.set(c,w),m=(async()=>{if(await Yr(c.session,w.gone.signal),w.gone.signal.aborted)throw Xr(w.gone.signal);u.get(c)===w&&u.delete(c);let R=await _s(c.session,await e());return Object.assign(R,{sessionId:c.session.id})})(),o.set(c,m),m.catch(()=>{o.get(c)===m&&o.delete(c)}),m.then(()=>{u.get(c)===w&&u.delete(c)},()=>{u.get(c)===w&&u.delete(c)})}return m},p=c=>{let m=a.get(c);return m||(m=(async()=>{let w=await l(c);return{appendInputAudio:R=>w.appendInputAudio(R),onOutputAudio:R=>w.onOutputAudio(R),sessionId:d(c)}})(),a.set(c,m),m.catch(()=>{a.get(c)===m&&a.delete(c)})),m},y=async(c,m,w)=>{if(w?.aborted){let v=u.get(c);throw(o.get(c)===void 0||v!==void 0&&v.waiting===0)&&await Xi(c.session),Xr(w)}let R=m(c),g=u.get(c);return g!==void 0&&g.waiting++,w===void 0?R:new Promise((v,b)=>{let L=()=>{g!==void 0&&--g.waiting===0&&u.get(c)===g&&(g.gone.abort(),u.delete(c),o.delete(c),a.delete(c),Xi(c.session).catch(()=>{})),b(Xr(w))};w.addEventListener("abort",L,{once:!0});let S=()=>w.removeEventListener("abort",L);R.then(x=>{S(),v(x)},x=>{S(),b(x)})})};return{createResponse:Ki({sessionFor:c=>t.sessionFor(c),sessionIdOf:c=>d(c),evict:(c,m)=>t.evict(c,m),onAdmissionVerdict:(c,m,w)=>{sc(w)&&(t.evict(c,m),n?.(c,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(c,m)=>(await Yr(c.session),zr(await c.responses.responses.create(m),c.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(c,m)=>t.supportsImages(c,m),listImageModels:()=>t.imageModelList(),catalogIdentity:c=>t.catalogIdentityFor(c),servingAppSlug:async c=>await t.servingAppSlugFor(c),supportsAudio:c=>t.supportsAudio(c),supportsSpeech:c=>t.supportsSpeech(c),speechVoices:c=>t.speechVoices(c),supportsTranscription:c=>t.supportsTranscription(c),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(c,m)=>{let{entry:w}=await t.sessionFor(c);return await y(w,l,m)},openAudioOn:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c);return await y(w,p,m)},openVideo:async c=>{let{entry:m}=await t.sessionFor(c),w=s.get(m);return w||(w=vs(m.session),s.set(m,w)),w},openVideoOut:async c=>{let{entry:m}=await t.sessionFor(c),w=i.get(m);return w||(w=Ss(m.session),i.set(m,w)),w},sessionHandle:async c=>(await t.handleFor(c)).handle,speechSessionHandle:async c=>(await t.speechHandleFor(c)).handle,evictSpeechSession:async c=>{let{app:m,entry:w}=await t.sessionForHandle(c);await t.evict(m,w)},createResponseOn:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c);return await Yr(w.session),zr(await w.responses.responses.create(m),w.gone)},onSessionEnd:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c),R=w.session;if(typeof R.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let g=!1;return R.onPhase(v=>{if(g||!ic.has(v.name))return;g=!0;let b=R.endsAt??null;m({timeLeftMs:b?Math.max(0,b.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})},...r?{stateless:r}:{}}}var ac=512;function zn(t){return`urun-inference-proxy-${(0,Kn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Vn=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return{router:a.router,clients:this.label(a.clients,e)}}let n=0,r=zn(e.apiKey),o=()=>{n+=1},s=Qr({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:dn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:()=>n===0?r:`${r}#${n}`,onPoolWedged:o,release:"end"}),i=this.opts.decisionIntake?new Mn({targetFor:a=>s.targetFor(a),apiUrl:this.opts.apiUrl,apiKey:e.apiKey,orgId:e.orgId,fnName:dn,secret:this.opts.decisionIntake.secret,...this.opts.decisionIntake.shared?{shared:this.opts.decisionIntake.shared}:{}}):void 0;return{router:s,clients:this.label(Zr(s,void 0,o,i),e)}}clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=ac;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let e=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r.closeAll()}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Qi=512,uc=1024,Wn=class extends Error{constructor(){super(`conversation capacity reached (${Qi} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function dc(t){return{sessionStartOptions:e=>{if(e.startsWith(Qe))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Qe)||t.set(e,n)}}}function lc(t,e,n,r){let o=Qr({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:dn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...dc(r)});return{clients:Zr(o),release:async()=>{await o.closeAll()}}}var Jn=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${zn(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):lc(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Qi;){let e=this.byCaller.keys().next();if(e.done)throw new Wn;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new Wn;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,Kn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async(i,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(i,a)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},s.supportsTranscription=async i=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=uc;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new fe("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};k();var Yn="/inference-usage",Zi=25e3;var cc=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function ea(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=cc.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Xn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Yn}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Zi)})}catch(i){throw new re(`the uRun usage surface (POST ${Yn}) could not be reached within ${Zi}ms: ${ea(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new re(`the uRun usage surface (POST ${Yn}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new re(`the uRun usage surface (POST ${Yn}) answered HTTP ${o.status} with a body that is not JSON: ${ea(i)}`)}return us(s,this.opts.onRejectedRow)}};k();var pc="/inference-ledger",fc=1e4,Qn=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},no=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},_e=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},ro=class extends Ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},mc=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",eo],["output_minutes",eo],["cost_nano_usd",eo],["price_version",t=>t===null||typeof t=="string"]];function hc(t){for(let[e,n]of mc){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function gc(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:hc(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function eo(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function to(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function yc(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function ta(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function wc(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&ta(t.started_at,n.started_at)&&ta(t.completed_at,n.completed_at)&&to(t.prompt_tokens,n.prompt_tokens)&&to(t.completion_tokens,n.completion_tokens)&&to(t.output_units,n.output_units)&&yc(t.output_minutes,n.output_minutes)}function _c(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new _e(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new _e(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new _e(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new _e(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=d=>{if(!(d in n))throw new _e(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let l=n[d];if(l===null)return null;if(typeof l!="string")throw new _e(`${e} answered a non-string ${d}: ${JSON.stringify(l)}`);if(!/[^\s]/.test(l))throw new _e(`${e} answered a BLANK ${d} (${JSON.stringify(l)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return l},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new _e(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new _e(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var Zn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${pc}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(fc)})}catch(u){throw new _e(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),d=gc(u);throw d.status==="found"&&wc(n,d.row)?new no(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new Qn(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new Qn(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ro("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(d=>`<body unreadable: ${d instanceof Error?d.message:String(d)}>`);throw new _e(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let s;try{s=await o.json()}catch(u){throw new _e(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let i=s?.recorded;if(i===void 0)throw new _e(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=_c(i,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new _e(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var vc=5e3,bc=3e3,kc="/api/client-tokens";function oo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function na(t,e,n,r){oo(t,e,{error:{message:n,type:r}})}async function Sc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${kc}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(bc)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function oa(t){let e=t.resolver??new Bn({gatewayUrl:t.baseUrl}),n=t.decisionSecret??"",r=t.sharedOrgKey&&t.sharedOrgId?{apiKey:t.sharedOrgKey}:void 0,o=t.registry??new Vn({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog,...n!==""?{decisionIntake:{secret:n,...r?{shared:r}:{}}}:{}});n!==""&&process.stderr.write(`inference-proxy: stateless direct path ENABLED \u2014 caller-org decisions dial ready runtimes directly (no session mint)
|
|
66
|
-
`);let s=t.probeControlPlane??(()=>
|
|
65
|
+
`)),l.end()})}}var Be=(t,e)=>Object.assign(new Error(e),{status:t});function Ki(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function zi(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var oc='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Yi(t,e,n,r){if(!t.supportsAudio)throw Be(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof z?Be(404,d.message):d}if(!o)throw Be(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw Be(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof z?Be(404,d.message):d}if(s&&!t.openTurnsOn)throw Be(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(l){throw l instanceof z?Be(404,l.message):l}if(d!=="stt")throw Be(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Be(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${oc}`);if(r==="transcription"&&!s)throw Be(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i=await t.sessionHandle(e),a={audio:await t.openAudioOn(i,n)},u={clients:{createResponse:async d=>await t.createResponseOn(i,d)},voice:o,audioSession:a};return s&&(u.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}k();var Vn=require("@urun-sh/core"),Ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Et=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Xt(t){let e=(t??"").trim();if(e==="")throw new Ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var sc=60,ic=6e4,ac=4096;function uc(t){return t===401||t===403}var Gn=class{constructor(e){this.opts=e;this.mint=e.mint??Vn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Ae("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<ic)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:sc})).orgId}catch(o){throw o instanceof Vn.ClientTokenError&&uc(o.status)?(this.cache.delete(e),new Ae("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Et(`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 Et("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>=ac){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};k();var Zn=require("crypto");k();var pt=require("@urun-sh/core");k();k();k();k();function Xi(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Qi(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}k();k();function Zi(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 e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var dc="llm-resp";async function*Qr(t,e){let n=`${dc}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield Zi(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Wn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Qi(e,n,this.consumerId);return this.write(r),Qr(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Xi(e,n,r,this.consumerId);return this.write(o),Qr(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var ea=0;function lc(){return ea+=1,`req_${Date.now().toString(36)}_${ea.toString(36)}`}var Kn=class{transport;constructor(e){this.transport=new Wn(e)}responses={create:async e=>{let n=lc(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};k();async function ta(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}k();var na=require("@urun-sh/core"),Zr=2;function cc(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function pc(t){let e=t?.type;return e==="response.completed"||e==="error"}function ra(t){return async function(n,r){return(async function*(){for(let s=1;s<=Zr;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,l=!1;try{let p=await t.createStream(a,n);for await(let y of p){if(pc(y)&&(d=!0),cc(y)){if(s>1)continue}else l=!0;yield y}}catch(p){if(p instanceof na.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,p)}catch{}throw p}if(s<Zr&&!l){await t.evict(i,a);continue}throw p}if(d)return;if(s<Zr&&!l){await t.evict(i,a);continue}return}})()}}k();var fc=3,mc="llm",hc=new Set(["paused","error"]);function oa(t,e){let n=t.doc(mc),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" 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 s=null,i=!1,a=new Set,u=[],d=l=>{if(!s){s=l;for(let p of[...a])p(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<fc||d(new fe(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.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&&u.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&hc.has(l.name)&&d(new fe(`the pooled session for app "${e}" lost its compute binding (phase "${l.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(l){return s?(l(s),()=>{}):(a.add(l),()=>a.delete(l))},dispose(){a.clear();for(let l of u.splice(0))l()}}}async function*eo(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function sa(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function gc(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(tt)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),l=e.sharedApp?{sharedApp:!0,...d}:d,p=w=>({session:w,responses:new Kn(w),gone:oa(w,n)});if(s.lane==="jwt"){let w=(0,pt.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return p(sa(w,e.appSlug,u,l))}let{apiKey:y,gatewayUrl:c}=s,m=(0,pt.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,pt.createClientToken)(y,{baseUrl:c,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return p(sa(m,e.appSlug,u,l))}function yc(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function wc(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var _c=new Set(["error","paused"]);function no(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=gc(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new nn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Go({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>ta(n):null,listPrices:n?()=>Eo(n):null,shared:e.lane==="api-key"?()=>bo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:yc});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Pt({appSlug:t.defaultApp}))),s}async function to(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:pt.DEFAULT_WHEN_LIVE_TIMEOUT_MS,signal:e})}async function ia(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function zn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ro(t,e=Is,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=new WeakMap,d=c=>{let m=c.session.id;return typeof m=="string"&&m.length>0?m:null},l=c=>{let m=o.get(c);if(!m){let w={waiting:0,gone:new AbortController};u.set(c,w),m=(async()=>{if(await to(c.session,w.gone.signal),w.gone.signal.aborted)throw zn(w.gone.signal);u.get(c)===w&&u.delete(c);let S=await Os(c.session,await e());return Object.assign(S,{sessionId:c.session.id})})(),o.set(c,m),m.catch(()=>{o.get(c)===m&&o.delete(c)}),m.then(()=>{u.get(c)===w&&u.delete(c)},()=>{u.get(c)===w&&u.delete(c)})}return m},p=c=>{let m=a.get(c);return m||(m=(async()=>{let w=await l(c);return{appendInputAudio:S=>w.appendInputAudio(S),onOutputAudio:S=>w.onOutputAudio(S),sessionId:d(c)}})(),a.set(c,m),m.catch(()=>{a.get(c)===m&&a.delete(c)})),m},y=async(c,m,w)=>{if(w?.aborted){let v=u.get(c);throw(o.get(c)===void 0||v!==void 0&&v.waiting===0)&&await ia(c.session),zn(w)}let S=m(c),g=u.get(c);return g!==void 0&&g.waiting++,w===void 0?S:new Promise((v,b)=>{let L=()=>{g!==void 0&&--g.waiting===0&&u.get(c)===g&&(g.gone.abort(),u.delete(c),o.delete(c),a.delete(c),ia(c.session).catch(()=>{})),b(zn(w))};w.addEventListener("abort",L,{once:!0});let R=()=>w.removeEventListener("abort",L);S.then(x=>{R(),v(x)},x=>{R(),b(x)})})};return{createResponse:ra({sessionFor:c=>t.sessionFor(c),sessionIdOf:c=>d(c),evict:(c,m)=>t.evict(c,m),onAdmissionVerdict:(c,m,w)=>{wc(w)&&(t.evict(c,m),n?.(c,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(c,m)=>(await to(c.session),eo(await c.responses.responses.create(m),c.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(c,m)=>t.supportsImages(c,m),listImageModels:()=>t.imageModelList(),catalogIdentity:c=>t.catalogIdentityFor(c),servingAppSlug:async c=>await t.servingAppSlugFor(c),supportsAudio:c=>t.supportsAudio(c),supportsSpeech:c=>t.supportsSpeech(c),speechVoices:c=>t.speechVoices(c),supportsTranscription:c=>t.supportsTranscription(c),transcriptStreamFor:c=>t.transcriptStreamFor(c),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(c,m)=>{let{entry:w}=await t.sessionFor(c);return await y(w,l,m)},openAudioOn:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c);return await y(w,p,m)},openTurnsOn:async function*(c,m){if(m?.aborted)throw zn(m);let{entry:w}=await t.sessionForHandle(c);yield*Fo(w.session,m)},openVideo:async c=>{let{entry:m}=await t.sessionFor(c),w=s.get(m);return w||(w=As(m.session),s.set(m,w)),w},openVideoOut:async c=>{let{entry:m}=await t.sessionFor(c),w=i.get(m);return w||(w=Ps(m.session),i.set(m,w)),w},sessionHandle:async c=>(await t.handleFor(c)).handle,speechSessionHandle:async c=>(await t.speechHandleFor(c)).handle,evictSpeechSession:async c=>{let{app:m,entry:w}=await t.sessionForHandle(c);await t.evict(m,w)},createResponseOn:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c);return await to(w.session),eo(await w.responses.responses.create(m),w.gone)},onSessionEnd:async(c,m)=>{let{entry:w}=await t.sessionForHandle(c),S=w.session;if(typeof S.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let g=!1;return S.onPhase(v=>{if(g||!_c.has(v.name))return;g=!0;let b=S.endsAt??null;m({timeLeftMs:b?Math.max(0,b.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})},...r?{stateless:r}:{}}}var vc=512;function er(t){return`urun-inference-proxy-${(0,Zn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Yn=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return{router:a.router,clients:this.label(a.clients,e)}}let n=0,r=er(e.apiKey),o=()=>{n+=1},s=no({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:mn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:()=>n===0?r:`${r}#${n}`,onPoolWedged:o,release:"end"}),i=this.opts.decisionIntake?new Dn({targetFor:a=>s.targetFor(a),apiUrl:this.opts.apiUrl,apiKey:e.apiKey,orgId:e.orgId,fnName:mn,secret:this.opts.decisionIntake.secret,...this.opts.decisionIntake.shared?{shared:this.opts.decisionIntake.shared}:{}}):void 0;return{router:s,clients:this.label(ro(s,void 0,o,i),e)}}clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=vc;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let e=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r.closeAll()}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},aa=512,bc=1024,Xn=class extends Error{constructor(){super(`conversation capacity reached (${aa} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function kc(t){return{sessionStartOptions:e=>{if(e.startsWith(tt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(tt)||t.set(e,n)}}}function Sc(t,e,n,r){let o=no({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:mn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...kc(r)});return{clients:ro(o),release:async()=>{await o.closeAll()}}}var Qn=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${er(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Sc(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=aa;){let e=this.byCaller.keys().next();if(e.done)throw new Xn;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new Xn;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,Zn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async(i,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(i,a)},s.openTurnsOn=(i,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(i,a)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},s.supportsTranscription=async i=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(i)},s.transcriptStreamFor=async i=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=bc;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new fe("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};k();var tr="/inference-usage",ua=25e3;var Rc=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function da(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Rc.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var nr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${tr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(ua)})}catch(i){throw new re(`the uRun usage surface (POST ${tr}) could not be reached within ${ua}ms: ${da(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new re(`the uRun usage surface (POST ${tr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new re(`the uRun usage surface (POST ${tr}) answered HTTP ${o.status} with a body that is not JSON: ${da(i)}`)}return gs(s,this.opts.onRejectedRow)}};k();var xc="/inference-ledger",Ec=1e4,rr=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},io=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},_e=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},ao=class extends Ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Oc=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",oo],["output_minutes",oo],["cost_nano_usd",oo],["price_version",t=>t===null||typeof t=="string"]];function Ac(t){for(let[e,n]of Oc){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Ic(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Ac(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function oo(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function so(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Tc(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function la(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Pc(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&la(t.started_at,n.started_at)&&la(t.completed_at,n.completed_at)&&so(t.prompt_tokens,n.prompt_tokens)&&so(t.completion_tokens,n.completion_tokens)&&so(t.output_units,n.output_units)&&Tc(t.output_minutes,n.output_minutes)}function Cc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new _e(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new _e(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new _e(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new _e(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=d=>{if(!(d in n))throw new _e(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let l=n[d];if(l===null)return null;if(typeof l!="string")throw new _e(`${e} answered a non-string ${d}: ${JSON.stringify(l)}`);if(!/[^\s]/.test(l))throw new _e(`${e} answered a BLANK ${d} (${JSON.stringify(l)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return l},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new _e(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new _e(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var or=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${xc}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(Ec)})}catch(u){throw new _e(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),d=Ic(u);throw d.status==="found"&&Pc(n,d.row)?new io(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new rr(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new rr(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ao("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(d=>`<body unreadable: ${d instanceof Error?d.message:String(d)}>`);throw new _e(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let s;try{s=await o.json()}catch(u){throw new _e(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let i=s?.recorded;if(i===void 0)throw new _e(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=Cc(i,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new _e(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var Mc=5e3,$c=3e3,Lc="/api/client-tokens";function uo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ca(t,e,n,r){uo(t,e,{error:{message:n,type:r}})}async function Nc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Lc}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout($c)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function fa(t){let e=t.resolver??new Gn({gatewayUrl:t.baseUrl}),n=t.decisionSecret??"",r=t.sharedOrgKey&&t.sharedOrgId?{apiKey:t.sharedOrgKey}:void 0,o=t.registry??new Yn({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog,...n!==""?{decisionIntake:{secret:n,...r?{shared:r}:{}}}:{}});n!==""&&process.stderr.write(`inference-proxy: stateless direct path ENABLED \u2014 caller-org decisions dial ready runtimes directly (no session mint)
|
|
66
|
+
`);let s=t.probeControlPlane??(()=>Nc(t.baseUrl)),i=t.usageClient??new nr({apiUrl:t.apiUrl}),a=t.ledgerClient??new or({apiUrl:t.apiUrl}),u=new fn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async g=>e.resolve(Xt(g.headers.authorization)),l=g=>g instanceof Ae?{status:g.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:g instanceof Et?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,p=Wi({clients:async g=>o.clientsFor(await d(g)),usage:{authorize:g=>Xt(g.headers.authorization),lookup:(g,v)=>i.lookup(g,v)},statusOf:l,...t.requestLog?{requestLog:t.requestLog}:{},observe:g=>u.observe(g),ledger:{write:(g,v)=>a.write(Xt(g.headers.authorization),v),observe:g=>u.observeLedger(g),...t.ledgerLog?{report:t.ledgerLog}:{}}}),y=null,c=(0,pa.createServer)((g,v)=>{let b=new URL(g.url??"/","http://localhost");(async()=>{if(g.method==="GET"&&b.pathname==="/healthz"){uo(v,200,{ok:!0});return}if(g.method==="GET"&&b.pathname==="/readyz"){let x=Date.now();if(!y||x-y.at>=Mc){let C=await s();y={at:x,...C}}uo(v,y.ready?200:503,{ok:y.ready,control_plane:y.detail});return}let L=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),R=b.pathname.startsWith("/partners/");if(!L&&!R){ca(v,404,`no route for ${g.method} ${b.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}p(g,v)})().catch(L=>{if(!v.headersSent){ca(v,500,String(L instanceof Error?L.message:L),"proxy_error");return}v.end()})}),m=t.conversations??new Qn({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),w=[Er(c,{authenticate:async g=>{let v=await e.resolve(g),b=m.connectionFor(v);return{clients:b.clients,scope:er(v.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),$r(c,{clients:async g=>o.clientsFor(await d(g)),statusOf:l}).close,An(c,{resolver:{resolve:async(g,v)=>{let b=await e.resolve(Xt(g.headers.authorization)),L=m.connectionFor(b),R;try{R=await Yi(L.clients,Ki(g),v,zi(g))}catch(x){throw L.release().catch(()=>{}),x}return{...R,release:L.release}}}})];c.on("upgrade",(g,v)=>{let b=new URL(g.url??"/","http://localhost");b.pathname===_n||b.pathname===Cr||b.pathname===Gt||v.destroyed||(v.write(`HTTP/1.1 404 Not Found\r
|
|
67
67
|
Connection: close\r
|
|
68
68
|
\r
|
|
69
|
-
no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),v.destroy())});let
|
|
69
|
+
no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),v.destroy())});let S=async()=>{for(let g of w)await g();await m.detachAll()};return{server:c,metricsServer:_s(u),metrics:u,edgeIdentityServer:ks(),registry:o,closeAll:()=>o.closeAll(),closeWebSockets:S}}async function ma(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await rs()||os(),await e()}function Uc(){let t=null;return t=Ko({streams:Ce.default,note:e=>{t?.isDead("stderr")!==!0&&Le(Ce.default.stderr,e)}}),t}async function Dc(){Uc();let t=Ss(Ce.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=fa(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,rt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(_r,rt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(br,rt,a)}),Ce.default.stdout.write(`inference-proxy listening on http://${rt}:${t.port}/v1 (metrics http://${rt}:${_r}${ln}, edge identity http://${rt}:${br}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
|
|
70
70
|
`);let i=async a=>{Ce.default.stdout.write(`inference-proxy: ${a} \u2014 draining
|
|
71
|
-
`),await
|
|
71
|
+
`),await ma(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Ce.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Ce.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}Dc().then(()=>Ce.default.exit(0),t=>{Ce.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
|
|
72
72
|
`),Ce.default.exit(1)});
|
|
73
73
|
/*! Bundled license information:
|
|
74
74
|
|