@urun-sh/openai 0.6.55 → 0.6.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Md=Object.create;var mi=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var Fd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Bd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nd(e))!Dd.call(t,o)&&o!==n&&mi(t,o,{get:()=>e[o],enumerable:!(r=$d(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Md(Ud(t)):{},Hd(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var T=Fd(()=>{"use strict"});var gi=Bd(()=>{"use strict";T();var hi;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(d,c)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return Ro(Object.create(null))}:l?function(){return Ro({__proto__:null})}:function(){return Ro({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Td(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Od(),m=typeof WeakMap=="function"?WeakMap:Pd(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=xd(),x=Ad(E);function v(k,I,L,D){if(N(L)){if(!vn(k))throw new TypeError;if(!ai(I))throw new TypeError;return b(k,I)}else{if(!vn(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(D)&&!N(D)&&!ee(D))throw new TypeError;return ee(D)&&(D=void 0),L=$e(L),C(k,I,L,D)}}e("decorate",v);function _(k,I){function L(D,Y){if(!ue(D))throw new TypeError;if(!N(Y)&&!Rd(Y))throw new TypeError;X(k,I,D,Y)}return L}e("metadata",_);function p(k,I,L,D){if(!ue(L))throw new TypeError;return N(D)||(D=$e(D)),X(k,I,L,D)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),M(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),U(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function O(k,I,L){if(!ue(I))throw new TypeError;if(N(L)||(L=$e(L)),!ue(I))throw new TypeError;N(L)||(L=$e(L));var D=bn(I,L,!1);return N(D)?!1:D.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",O);function b(k,I){for(var L=k.length-1;L>=0;--L){var D=k[L],Y=D(I);if(!N(Y)&&!ee(Y)){if(!ai(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,D){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,D);if(!N(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;D=ke}}return D}function $(k,I,L){var D=M(k,I,L);if(D)return!0;var Y=ko(I);return ee(Y)?!1:$(k,Y,L)}function M(k,I,L){var D=bn(I,L,!1);return N(D)?!1:Me(D.OrdinaryHasOwnMetadata(k,I,L))}function U(k,I,L){var D=M(k,I,L);if(D)return q(k,I,L);var Y=ko(I);if(!ee(Y))return U(k,Y,L)}function q(k,I,L){var D=bn(I,L,!1);if(!N(D))return D.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,D){var Y=bn(L,D,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,D)}function G(k,I){var L=re(k,I),D=ko(k);if(D===null)return L;var Y=G(D,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=bn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function N(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",D=li(k,s);if(D!==void 0){var Y=D.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var D=L.call(k);if(!ue(D))return D}var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}}else{var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}var ve=k.toString;if(at(ve)){var D=ve.call(k);if(!ue(D))return D}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function vn(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function ai(k){return typeof k=="function"}function Rd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function So(k,I){return k===I||k!==k&&I!==I}function li(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ui(k){var I=li(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function di(k){return k.value}function ci(k){var I=k.next();return I.done?!1:I}function pi(k){var I=k.return;I&&I.call(k)}function ko(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,D=L&&Object.getPrototypeOf(L);if(D==null||D===Object.prototype)return I;var Y=D.constructor;return typeof Y!="function"||Y===k?I:Y}function Ed(){var k;!N(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Id(n.Reflect));var I,L,D,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case N(I):I=V;break;case I===V:break;case N(L):L=V;break;case L===V:break;default:D===void 0&&(D=new h),D.add(V);break}}function ne(V,oe){if(!N(I)){if(I.isProviderFor(V,oe))return I;if(!N(L)){if(L.isProviderFor(V,oe))return I;if(!N(D))for(var pe=ui(D);;){var be=ci(pe);if(!be)return;var Je=di(be);if(Je.isProviderFor(V,oe))return pi(pe),Je}}}if(!N(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return N(pe)||(be=pe.get(oe)),N(be)&&(be=ne(V,oe),N(be)||(N(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(N(V))throw new TypeError;return I===V||L===V||!N(D)&&D.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!N(be))return!1;var Je=Y.get(V);N(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function xd(){var k;return!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),N(k)&&(k=Ed()),!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function Ad(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return N(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function D(W,J,V){var oe=I.get(W),pe=!1;if(N(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(N(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=D(J,V,!1);return N(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=D(J,V,!1);if(!N(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=D(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=D(W,J,!1);if(N(oe))return V;for(var pe=oe.keys(),be=ui(pe),Je=0;;){var fi=ci(be);if(!fi)return V.length=Je,V;var Cd=di(fi);try{V[Je]=Cd}catch(Ld){try{pi(be)}finally{throw Ld}}Je++}}function B(W,J,V){var oe=D(J,V,!1);if(N(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);N(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Id(k){var I=k.defineMetadata,L=k.hasOwnMetadata,D=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!N(J)&&J.has(W)?!0:Y(B,W).length?(N(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:D,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function bn(k,I,L){var D=E.getProvider(k,I);if(!N(D))return D;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Td(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),D=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,So(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!So(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(So(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return D;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function Od(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Pd(){var k=16,I=d.create(),L=D();return(function(){function B(){this._key=D()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=D()},B})();function D(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function Ro(k){return k.__=void 0,delete k.__,k}})})(hi||(hi={}))});T();var iS=Ee(gi(),1),et=Ee(require("process"),1);T();var hc=Ee(require("os"),1),gc=Ee(require("path"),1),yc=require("url"),wc=require("util");T();var Di=require("crypto");T();var he=class extends Error{},jd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qd(t){if(typeof t!="string")return!1;let e=jd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Gd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",qd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yi(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new he(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Eo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function wi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Gd(await r.json())}T();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}T();var Be=class extends Error{name="ModelPriceError"},xo="per_million_input_tokens",Ao="per_million_output_tokens",vi="model_id,variant,unit,price_usd,effective_at,expires_at",_i={per_request:!0,per_minute:!0,per_output_unit:!0},Wd=5e3;function Jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function bi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Vd(t,e,n){return t===null?null:bi(t,e,n)}function Kd(t,e){if(t===xo)return"input";if(t===Ao)return"output";if(typeof t=="string"&&Object.hasOwn(_i,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${xo} | ${Ao}) nor a known GPU-time unit (${Object.keys(_i).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function zd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function Io(t,e){return`${t}\0${e}`}function Yd(t){if(!Array.isArray(t))throw new Be(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of vi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Kd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Jd(s.price_usd,o),effective_at:bi(s.effective_at,o,"effective_at"),expires_at:Vd(s.expires_at,o,"expires_at")})}return e}function Si(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=zd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(Io(l,m))?E.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Sn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var kn={prices:[],refusals:[]};async function ki(t){let e=t.fetchImpl??fetch,n=`${xo},${Ao}`,r=await e(`${t.catalogUrl}/model_prices?select=${vi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Yd(await r.json())}T();var Rt="/partners/openrouter/models",Xd={chat:!0,code:!0,agent:!0,vl:!0},Ri={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Qd(t){let e=t.toLowerCase();return Object.hasOwn(Ri,e)?Ri[e]:null}var Ei={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ei,o)?Ei[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ai={2:"Llama2",3:"Llama3"};function ec(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xi,s))return xi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ai,i))return Ai[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var tc=["context_length","max_model_len"];function nc(t){let e=tc.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function or(t){let e=t.map(nc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function rc(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function To(t){if(t.length===0)return null;let e=t.map(rc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Oo(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function oc(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return Rn(r);let o=Oo(t,e);return o.length>0?Rn(o):null}function Rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:sc(t),matches:t}:null}function sc(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var mt=class extends Error{name="ModelCreatedError"};function Jt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new mt(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new mt(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function sr(t,e,n){let r=oc(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=or(s),a=Jt(s),l=Sn(o.model_id,o.variant,n),u=Oi(o,s),d=To(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ic=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...ic],defect:o}:{published:[],defect:o}}function Po(t){let e=t.length>0?Rn(t):null;return e===null?{published:[],defect:null}:Oi(e.row,e.matches)}function Ii(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ti(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ii(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ii(t.output)}]}}function ac(t,e,n,r){if(e.length===0)return null;let o=Rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Xd[s.task]!==!0)return null;let a=or(i),l=Sn(s.model_id,s.variant,n),u=ec(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Jt(i),quantization:Qd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ti(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ti(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Pi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ac(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}T();var Ci={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Li(t){let e=t.t;if(typeof e!="string"||!(e in Ci))throw new Vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ci).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function lc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Vt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Vt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Li(t)}function Mi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function $i(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Mi(e);let s=o.next();if(e!==void 0&&await uc(s,e)==="aborted")throw s.catch(()=>{}),Mi(e);let i=await s;if(i.done)return;yield lc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},$o="credits_exhausted",No="insufficient_credits",Lo="urs1.";function An(t,e){return Lo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Lo))return null;try{let e=JSON.parse(Buffer.from(t.slice(Lo.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Fi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Ni(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=pc(t);return e===null?[]:[e]}function dc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var Md=Object.create;var mi=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var Fd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Bd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nd(e))!Dd.call(t,o)&&o!==n&&mi(t,o,{get:()=>e[o],enumerable:!(r=$d(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Md(Ud(t)):{},Hd(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var T=Fd(()=>{"use strict"});var gi=Bd(()=>{"use strict";T();var hi;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(d,c)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return Ro(Object.create(null))}:l?function(){return Ro({__proto__:null})}:function(){return Ro({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Td(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Od(),m=typeof WeakMap=="function"?WeakMap:Pd(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=xd(),x=Ad(E);function v(k,I,L,D){if(N(L)){if(!vn(k))throw new TypeError;if(!ai(I))throw new TypeError;return b(k,I)}else{if(!vn(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(D)&&!N(D)&&!ee(D))throw new TypeError;return ee(D)&&(D=void 0),L=$e(L),C(k,I,L,D)}}e("decorate",v);function _(k,I){function L(D,Y){if(!ue(D))throw new TypeError;if(!N(Y)&&!Rd(Y))throw new TypeError;X(k,I,D,Y)}return L}e("metadata",_);function p(k,I,L,D){if(!ue(L))throw new TypeError;return N(D)||(D=$e(D)),X(k,I,L,D)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),M(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),U(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function O(k,I,L){if(!ue(I))throw new TypeError;if(N(L)||(L=$e(L)),!ue(I))throw new TypeError;N(L)||(L=$e(L));var D=bn(I,L,!1);return N(D)?!1:D.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",O);function b(k,I){for(var L=k.length-1;L>=0;--L){var D=k[L],Y=D(I);if(!N(Y)&&!ee(Y)){if(!ai(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,D){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,D);if(!N(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;D=ke}}return D}function $(k,I,L){var D=M(k,I,L);if(D)return!0;var Y=ko(I);return ee(Y)?!1:$(k,Y,L)}function M(k,I,L){var D=bn(I,L,!1);return N(D)?!1:Me(D.OrdinaryHasOwnMetadata(k,I,L))}function U(k,I,L){var D=M(k,I,L);if(D)return q(k,I,L);var Y=ko(I);if(!ee(Y))return U(k,Y,L)}function q(k,I,L){var D=bn(I,L,!1);if(!N(D))return D.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,D){var Y=bn(L,D,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,D)}function G(k,I){var L=re(k,I),D=ko(k);if(D===null)return L;var Y=G(D,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=bn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function N(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",D=li(k,s);if(D!==void 0){var Y=D.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var D=L.call(k);if(!ue(D))return D}var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}}else{var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}var ve=k.toString;if(at(ve)){var D=ve.call(k);if(!ue(D))return D}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function vn(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function ai(k){return typeof k=="function"}function Rd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function So(k,I){return k===I||k!==k&&I!==I}function li(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ui(k){var I=li(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function di(k){return k.value}function ci(k){var I=k.next();return I.done?!1:I}function pi(k){var I=k.return;I&&I.call(k)}function ko(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,D=L&&Object.getPrototypeOf(L);if(D==null||D===Object.prototype)return I;var Y=D.constructor;return typeof Y!="function"||Y===k?I:Y}function Ed(){var k;!N(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Id(n.Reflect));var I,L,D,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case N(I):I=V;break;case I===V:break;case N(L):L=V;break;case L===V:break;default:D===void 0&&(D=new h),D.add(V);break}}function ne(V,oe){if(!N(I)){if(I.isProviderFor(V,oe))return I;if(!N(L)){if(L.isProviderFor(V,oe))return I;if(!N(D))for(var pe=ui(D);;){var be=ci(pe);if(!be)return;var Je=di(be);if(Je.isProviderFor(V,oe))return pi(pe),Je}}}if(!N(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return N(pe)||(be=pe.get(oe)),N(be)&&(be=ne(V,oe),N(be)||(N(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(N(V))throw new TypeError;return I===V||L===V||!N(D)&&D.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!N(be))return!1;var Je=Y.get(V);N(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function xd(){var k;return!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),N(k)&&(k=Ed()),!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function Ad(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return N(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function D(W,J,V){var oe=I.get(W),pe=!1;if(N(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(N(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=D(J,V,!1);return N(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=D(J,V,!1);if(!N(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=D(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=D(W,J,!1);if(N(oe))return V;for(var pe=oe.keys(),be=ui(pe),Je=0;;){var fi=ci(be);if(!fi)return V.length=Je,V;var Cd=di(fi);try{V[Je]=Cd}catch(Ld){try{pi(be)}finally{throw Ld}}Je++}}function B(W,J,V){var oe=D(J,V,!1);if(N(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);N(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Id(k){var I=k.defineMetadata,L=k.hasOwnMetadata,D=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!N(J)&&J.has(W)?!0:Y(B,W).length?(N(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:D,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function bn(k,I,L){var D=E.getProvider(k,I);if(!N(D))return D;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Td(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),D=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,So(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!So(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(So(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return D;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function Od(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Pd(){var k=16,I=d.create(),L=D();return(function(){function B(){this._key=D()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=D()},B})();function D(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function Ro(k){return k.__=void 0,delete k.__,k}})})(hi||(hi={}))});T();var iS=Ee(gi(),1),et=Ee(require("process"),1);T();var hc=Ee(require("os"),1),gc=Ee(require("path"),1),yc=require("url"),wc=require("util");T();var Di=require("crypto");T();var he=class extends Error{},jd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qd(t){if(typeof t!="string")return!1;let e=jd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Gd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",qd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yi(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new he(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Eo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function wi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Gd(await r.json())}T();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}T();var Be=class extends Error{name="ModelPriceError"},xo="per_million_input_tokens",Ao="per_million_output_tokens",vi="model_id,variant,unit,price_usd,effective_at,expires_at",_i={per_request:!0,per_minute:!0,per_output_unit:!0},Wd=5e3;function Jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function bi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Vd(t,e,n){return t===null?null:bi(t,e,n)}function Kd(t,e){if(t===xo)return"input";if(t===Ao)return"output";if(typeof t=="string"&&Object.hasOwn(_i,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${xo} | ${Ao}) nor a known GPU-time unit (${Object.keys(_i).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function zd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function Io(t,e){return`${t}\0${e}`}function Yd(t){if(!Array.isArray(t))throw new Be(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of vi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Kd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Jd(s.price_usd,o),effective_at:bi(s.effective_at,o,"effective_at"),expires_at:Vd(s.expires_at,o,"expires_at")})}return e}function Si(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=zd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(Io(l,m))?E.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Sn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var kn={prices:[],refusals:[]};async function ki(t){let e=t.fetchImpl??fetch,n=`${xo},${Ao}`,r=await e(`${t.catalogUrl}/model_prices?select=${vi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Yd(await r.json())}T();var Rt="/partners/openrouter/models",Xd={chat:!0,code:!0,agent:!0,vl:!0},Ri={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Qd(t){let e=t.toLowerCase();return Object.hasOwn(Ri,e)?Ri[e]:null}var Ei={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ei,o)?Ei[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ai={2:"Llama2",3:"Llama3"};function ec(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xi,s))return xi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ai,i))return Ai[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var tc=["context_length","max_model_len"];function nc(t){let e=tc.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function or(t){let e=t.map(nc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function rc(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function To(t){if(t.length===0)return null;let e=t.map(rc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Oo(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function oc(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return Rn(r);let o=Oo(t,e);return o.length>0?Rn(o):null}function Rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:sc(t),matches:t}:null}function sc(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var mt=class extends Error{name="ModelCreatedError"};function Jt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new mt(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new mt(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function sr(t,e,n){let r=oc(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=or(s),a=Jt(s),l=Sn(o.model_id,o.variant,n),u=Oi(o,s),d=To(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ic=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...ic],defect:o}:{published:[],defect:o}}function Po(t){let e=t.length>0?Rn(t):null;return e===null?{published:[],defect:null}:Oi(e.row,e.matches)}function Ii(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ti(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ii(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ii(t.output)}]}}function ac(t,e,n,r){if(e.length===0)return null;let o=Rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Xd[s.task]!==!0)return null;let a=or(i),l=Sn(s.model_id,s.variant,n),u=ec(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Jt(i),quantization:Qd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ti(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ti(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Pi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ac(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}T();var Ci={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},Vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Li(t){let e=t.t;if(typeof e!="string"||!(e in Ci))throw new Vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ci).join(", ")}`);let n={kind:e};return e!=="turn_dropped"&&typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function lc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Vt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Vt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Li(t)}function Mi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function $i(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Mi(e);let s=o.next();if(e!==void 0&&await uc(s,e)==="aborted")throw s.catch(()=>{}),Mi(e);let i=await s;if(i.done)return;yield lc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},$o="credits_exhausted",No="insufficient_credits",Lo="urs1.";function An(t,e){return Lo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Lo))return null;try{let e=JSON.parse(Buffer.from(t.slice(Lo.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Fi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Ni(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=pc(t);return e===null?[]:[e]}function dc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
4
  `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function Uo(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||Ue(`${r.model_id}-${r.variant}`)===e.appSlug||Ue(r.model_id)===e.appSlug)),n?dc(n.engine_args?.pool):null}function Co(t,e,n,r,o){if(!o)throw new he(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new he(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new he(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Ui(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new he(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Bi="shared:",Kt="speech:",yt="realtime:";function gt(t){return t.sharedApp?Bi+t.appSlug:t.appSlug}function xn(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Mo(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ue(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function cc(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function pc(t){let e=t.map(cc),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var fc={stt:"stt",tts:"tts"};function ht(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:fc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Hi(t,e){let n=Mo(t,e);return n.length>0?n:Oo(t,e)}function En(t,e){return Hi(t.appSlug,e)}function mc(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new he(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var ir=6e4,ar=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??ir):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??ir):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??ir):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??ir;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof Be)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
5
  `),kn}let r=Si(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
@@ -21,8 +21,8 @@ Connection: close\r
21
21
  Content-Type: text/plain; charset=utf-8\r
22
22
  Content-Length: ${Buffer.byteLength(o)}\r
23
23
  \r
24
- ${o}`)}function us(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Wp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Ir(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==as){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ir(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;Ir(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new is(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Ir(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ls();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}T();T();var vs=require("@urun-sh/core");T();var ol=require("@urun-sh/core"),Xp={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Qp={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; 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:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Dn(t,e){let n=Qp[t.code];return e?`${n} (${e})`:n}function Tr(t){if(t==null)return null;let e=Xp[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Or(t){if(t.kind==="create-failed")return Tr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ol.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Tr(e?"cold_start_exceeded":"queue_timeout")}var Hn=require("ws");T();var ll=require("@urun-sh/core");T();var il=require("crypto");function j(t){return`${t}_${(0,il.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Pr=4*1024*1024,ds=8*1024*1024,cs=512,an=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ps(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zp={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_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,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},ef={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tf={format:!0,voice:!0,speed:!0};function nf(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function sn(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function sl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rf=10;function fs(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:rf})}function Fn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=sn(o.modalities,"modalities"),l=sn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=sn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nf(l))throw new z(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=fs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("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=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`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=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`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")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("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 z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ef))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Fn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Fn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("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 z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tf))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Cr(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 ms(t,e){let n=t;if(!n||typeof n!="object")throw new z("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 z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:j("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 z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("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 z("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 z(`${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 z("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 z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Lr(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 of=1001,sf=1011,af=6e4,lf=3e5,hs=3;var Mr=class extends Error{},$r=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},gs=t=>t.slice(0,120),uf=/^[A-Za-z0-9+/=]*$/,df=600;function ys(t){return _r(Buffer.from(t,"base64"))}var Bn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ps();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;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.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??af,this.responseDeadlineMs=e.responseDeadlineMs??lf,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),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.binding.onSessionEnd?.(n=>{n.reason===$o&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Cr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}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){if(!this.closed&&!e.signal.aborted)if(r instanceof te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(ot("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[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:j("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:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),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:j("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:j("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.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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=j("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:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!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(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Pr){this.fail(fe("frame_too_large",`frame exceeds the ${Pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Mr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
- ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Fn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:j("event"),session:Cr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ms(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("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:j("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(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("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(le(fe("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:j("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(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uf.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>an&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${an}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${an} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>an&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&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=j("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:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("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(le(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,gs("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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 Mr("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(le({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*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new $r),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),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,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?sn(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?sn(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Lr(this.items),x=fs(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},O={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Lr(this.items)}let{input:$,sawAudioOnlyItem:M}=E??{input:[],sawAudioOnlyItem:!1},U={...S,input:$,...m?this.compositeTurnAsk(r):{}};M&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(U,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);O.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),O.contentFlowed=!0,O.messageOpen||(this.beginMessageItem(h,O.nextOutputIndex++),O.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(O.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),O.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),O.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${O.nextOutputIndex}`,N=O.tools.get(K);if(!N){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;N={outputIndex:O.nextOutputIndex++,name:ee,args:""},O.tools.set(K,N);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:N.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(N.name=G.name),N.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:N.outputIndex,call_id:K,name:N.name??"",delta:re});continue}if(G.type==="response.completed"){b=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof $r)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(O.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=hs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${hs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${hs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(ys(n))return;this.openDuplexResponse()}else if(ys(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=df){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(ys(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("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`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("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,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("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:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}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:j("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:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}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=rt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(No,"the organization is out of credits \u2014 top up to continue"),No))}failSessionGone(e){if(e instanceof te&&e.reason===$o){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ll.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cs&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Cn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>ds){this.ws.close(of,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(sf,gs(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,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>al(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),al(this.id,e)}},ws=[];function al(t,e){ws.push({id:t,reason:e}),ws.length>256&&ws.shift()}var jn="/v1/realtime",ul="urun.admission",dl=t=>t.slice(0,120);function cf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
24
+ ${o}`)}function us(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Wp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Ir(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==as){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ir(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;Ir(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new is(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Ir(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ls();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}T();T();var vs=require("@urun-sh/core");T();var ol=require("@urun-sh/core"),Xp={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Qp={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; 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:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Dn(t,e){let n=Qp[t.code];return e?`${n} (${e})`:n}function Tr(t){if(t==null)return null;let e=Xp[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Or(t){if(t.kind==="create-failed")return Tr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ol.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Tr(e?"cold_start_exceeded":"queue_timeout")}var Hn=require("ws");T();var ll=require("@urun-sh/core");T();var il=require("crypto");function j(t){return`${t}_${(0,il.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Pr=4*1024*1024,ds=8*1024*1024,cs=512,an=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ps(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zp={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_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,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},ef={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tf={format:!0,voice:!0,speed:!0};function nf(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function sn(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function sl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rf=10;function fs(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:rf})}function Fn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=sn(o.modalities,"modalities"),l=sn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=sn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nf(l))throw new z(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=fs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("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=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`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=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`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")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("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 z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ef))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Fn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Fn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("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 z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tf))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Cr(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 ms(t,e){let n=t;if(!n||typeof n!="object")throw new z("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 z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:j("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 z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("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 z("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 z(`${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 z("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 z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Lr(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 of=1001,sf=1011,af=6e4,lf=3e5,hs=3;var Mr=class extends Error{},$r=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},gs=t=>t.slice(0,120),uf=/^[A-Za-z0-9+/=]*$/,df=600;function ys(t){return _r(Buffer.from(t,"base64"))}var Bn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ps();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!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.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??af,this.responseDeadlineMs=e.responseDeadlineMs??lf,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),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.binding.onSessionEnd?.(n=>{n.reason===$o&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Cr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}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){if(!this.closed&&!e.signal.aborted)if(r instanceof te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(ot("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[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:j("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:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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:j("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.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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=j("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:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});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(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Pr){this.fail(fe("frame_too_large",`frame exceeds the ${Pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Mr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
+ ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Fn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:j("event"),session:Cr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ms(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("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:j("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(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("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(le(fe("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:j("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(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uf.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>an&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${an}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${an} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>an&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&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=j("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:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("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(le(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,gs("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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 Mr("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(le({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*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new $r),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),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,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?sn(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?sn(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Lr(this.items),x=fs(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},O={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Lr(this.items)}let{input:$,sawAudioOnlyItem:M}=E??{input:[],sawAudioOnlyItem:!1},U={...S,input:$,...m?this.compositeTurnAsk(r):{}};M&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(U,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);O.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),O.contentFlowed=!0,O.messageOpen||(this.beginMessageItem(h,O.nextOutputIndex++),O.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(O.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),O.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),O.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${O.nextOutputIndex}`,N=O.tools.get(K);if(!N){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;N={outputIndex:O.nextOutputIndex++,name:ee,args:""},O.tools.set(K,N);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:N.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(N.name=G.name),N.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:N.outputIndex,call_id:K,name:N.name??"",delta:re});continue}if(G.type==="response.completed"){b=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof $r)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(O.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=hs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${hs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${hs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(ys(n)||this.userTurnOpen)return;this.openDuplexResponse()}else if(ys(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=df){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(ys(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("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`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("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,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("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:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}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:j("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:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}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=rt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(No,"the organization is out of credits \u2014 top up to continue"),No))}failSessionGone(e){if(e instanceof te&&e.reason===$o){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ll.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cs&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Cn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>ds){this.ws.close(of,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(sf,gs(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,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>al(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),al(this.id,e)}},ws=[];function al(t,e){ws.push({id:t,reason:e}),ws.length>256&&ws.shift()}var jn="/v1/realtime",ul="urun.admission",dl=t=>t.slice(0,120);function cf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-4UE7XH7T.js";import"../chunk-HLSJAQHY.js";import"../chunk-CAR4AEQJ.js";import"../chunk-PPEND4SP.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-BVM4ZQ2Y.js";import"../chunk-KNWFUWXY.js";import{v as m,w as p}from"../chunk-Z74YK7AL.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
2
+ import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-SNCDIY53.js";import"../chunk-HIM6EB3J.js";import"../chunk-CAR4AEQJ.js";import"../chunk-RONITPWW.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-2VZR5MAX.js";import"../chunk-EA3GQ2MM.js";import{v as m,w as p}from"../chunk-O3Z5AY5E.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-4GW343S5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
3
3
  `);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
4
4
  `),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
5
5
  `),o.exit(1)});