@urun-sh/openai 0.6.30 → 0.6.32

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.
Files changed (49) hide show
  1. package/dist/chunk-5473ZAQ4.js +17 -0
  2. package/dist/chunk-7OH7UJ2H.js +60 -0
  3. package/dist/chunk-CAR4AEQJ.js +1 -0
  4. package/dist/{chunk-76BZLCGT.js → chunk-GL7EWL3V.js} +1 -1
  5. package/dist/chunk-KTMDSM7F.js +2 -0
  6. package/dist/chunk-L6HTHDVV.js +1 -0
  7. package/dist/chunk-LM4E5YM2.js +19 -0
  8. package/dist/chunk-M3YMNU5P.js +6 -0
  9. package/dist/chunk-NN6TQQUG.js +1 -0
  10. package/dist/chunk-OOCRI7ZM.js +6 -0
  11. package/dist/chunk-PAYCMH5F.js +1 -0
  12. package/dist/{responses-turn-BGb_XPOa.d.ts → composite-DMawda97.d.ts} +125 -83
  13. package/dist/{responses-turn-DXrwiPJh.d.cts → composite-DtBebn0Y.d.cts} +545 -309
  14. package/dist/gemini-live.cjs +2 -2
  15. package/dist/gemini-live.d.cts +85 -105
  16. package/dist/gemini-live.d.ts +48 -48
  17. package/dist/gemini-live.js +1 -1
  18. package/dist/hosted/bin.cjs +56 -42
  19. package/dist/hosted/bin.js +4 -22
  20. package/dist/hosted/index.cjs +52 -38
  21. package/dist/hosted/index.d.cts +230 -7
  22. package/dist/hosted/index.d.ts +114 -3
  23. package/dist/hosted/index.js +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.cts +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/{models-DUdx_Y6X.d.cts → models-D7F0bLJ3.d.cts} +14 -0
  29. package/dist/{models-DUdx_Y6X.d.ts → models-D7F0bLJ3.d.ts} +6 -0
  30. package/dist/pi-extension/index.cjs +6 -6
  31. package/dist/pi-extension/index.js +1 -1
  32. package/dist/pi-extension/standalone.cjs +33 -33
  33. package/dist/pooler/bin.cjs +335 -0
  34. package/dist/pooler/bin.js +316 -0
  35. package/dist/proxy/cli.cjs +58 -53
  36. package/dist/proxy/cli.js +1 -1
  37. package/dist/proxy/conformance-probe.cjs +1 -0
  38. package/dist/proxy/conformance-probe.js +1 -0
  39. package/dist/proxy/index.cjs +31 -28
  40. package/dist/proxy/index.d.cts +315 -167
  41. package/dist/proxy/index.d.ts +85 -53
  42. package/dist/proxy/index.js +1 -1
  43. package/package.json +14 -4
  44. package/dist/chunk-55LV3IXW.js +0 -62
  45. package/dist/chunk-7V2JKPIG.js +0 -1
  46. package/dist/chunk-CUDFHFNX.js +0 -4
  47. package/dist/chunk-K23AZPI4.js +0 -1
  48. package/dist/chunk-OPMTYD3Z.js +0 -2
  49. package/dist/chunk-WUNJ3FMI.js +0 -8
@@ -1,77 +1,91 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ga=Object.create;var Ro=Object.defineProperty;var Va=Object.getOwnPropertyDescriptor;var Wa=Object.getOwnPropertyNames;var Ja=Object.getPrototypeOf,Ka=Object.prototype.hasOwnProperty;var za=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Ya=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Xa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wa(e))!Ka.call(t,o)&&o!==n&&Ro(t,o,{get:()=>e[o],enumerable:!(r=Va(e,o))||r.enumerable});return t};var mt=(t,e,n)=>(n=t!=null?Ga(Ja(t)):{},Xa(e||!t||!t.__esModule?Ro(n,"default",{value:t,enumerable:!0}):n,t));var x=za(()=>{"use strict"});var Eo=Ya(()=>{"use strict";x();var xo;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,l){return function(d,c){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:c}),l&&l(d,c)}}function i(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||s()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",u={__proto__:[]}instanceof Array,l=!a&&!u,d={create:a?function(){return dr(Object.create(null))}:u?function(){return dr({__proto__:null})}:function(){return dr({})},has:l?function(m,g){return r.call(m,g)}:function(m,g){return g in m},get:l?function(m,g){return r.call(m,g)?m[g]:void 0}:function(m,g){return m[g]}},c=Object.getPrototypeOf(Function),y=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Fa(),f=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ba(),p=typeof WeakMap=="function"?WeakMap:ja(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,_=Na(),b=Ua(_);function k(m,g,S,E){if(I(S)){if(!Pt(m))throw new TypeError;if(!yo(g))throw new TypeError;return z(m,g)}else{if(!Pt(m))throw new TypeError;if(!q(g))throw new TypeError;if(!q(E)&&!I(E)&&!X(E))throw new TypeError;return X(E)&&(E=void 0),S=be(S),ie(m,g,S,E)}}e("decorate",k);function h(m,g){function S(E,U){if(!q(E))throw new TypeError;if(!I(U)&&!La(U))throw new TypeError;te(m,g,E,U)}return S}e("metadata",h);function A(m,g,S,E){if(!q(S))throw new TypeError;return I(E)||(E=be(E)),te(m,g,S,E)}e("defineMetadata",A);function R(m,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),he(m,g,S)}e("hasMetadata",R);function v(m,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),ve(m,g,S)}e("hasOwnMetadata",v);function O(m,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),Te(m,g,S)}e("getMetadata",O);function j(m,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),ee(m,g,S)}e("getOwnMetadata",j);function C(m,g){if(!q(m))throw new TypeError;return I(g)||(g=be(g)),de(m,g)}e("getMetadataKeys",C);function D(m,g){if(!q(m))throw new TypeError;return I(g)||(g=be(g)),Le(m,g)}e("getOwnMetadataKeys",D);function H(m,g,S){if(!q(g))throw new TypeError;if(I(S)||(S=be(S)),!q(g))throw new TypeError;I(S)||(S=be(S));var E=Ct(g,S,!1);return I(E)?!1:E.OrdinaryDeleteMetadata(m,g,S)}e("deleteMetadata",H);function z(m,g){for(var S=m.length-1;S>=0;--S){var E=m[S],U=E(g);if(!I(U)&&!X(U)){if(!yo(U))throw new TypeError;g=U}}return g}function ie(m,g,S,E){for(var U=m.length-1;U>=0;--U){var se=m[U],ce=se(g,S,E);if(!I(ce)&&!X(ce)){if(!q(ce))throw new TypeError;E=ce}}return E}function he(m,g,S){var E=ve(m,g,S);if(E)return!0;var U=lr(g);return X(U)?!1:he(m,U,S)}function ve(m,g,S){var E=Ct(g,S,!1);return I(E)?!1:Be(E.OrdinaryHasOwnMetadata(m,g,S))}function Te(m,g,S){var E=ve(m,g,S);if(E)return ee(m,g,S);var U=lr(g);if(!X(U))return Te(m,U,S)}function ee(m,g,S){var E=Ct(g,S,!1);if(!I(E))return E.OrdinaryGetOwnMetadata(m,g,S)}function te(m,g,S,E){var U=Ct(S,E,!0);U.OrdinaryDefineOwnMetadata(m,g,S,E)}function de(m,g){var S=Le(m,g),E=lr(m);if(E===null)return S;var U=de(E,g);if(U.length<=0)return S;if(S.length<=0)return U;for(var se=new f,ce=[],W=0,P=S;W<P.length;W++){var M=P[W],L=se.has(M);L||(se.add(M),ce.push(M))}for(var $=0,J=U;$<J.length;$++){var M=J[$],L=se.has(M);L||(se.add(M),ce.push(M))}return ce}function Le(m,g){var S=Ct(m,g,!1);return S?S.OrdinaryOwnMetadataKeys(m,g):[]}function G(m){if(m===null)return 1;switch(typeof m){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return m===null?1:6;default:return 6}}function I(m){return m===void 0}function X(m){return m===null}function Pe(m){return typeof m=="symbol"}function q(m){return typeof m=="object"?m!==null:typeof m=="function"}function me(m,g){switch(G(m)){case 0:return m;case 1:return m;case 2:return m;case 3:return m;case 4:return m;case 5:return m}var S=g===3?"string":g===5?"number":"default",E=_o(m,i);if(E!==void 0){var U=E.call(m,S);if(q(U))throw new TypeError;return U}return $e(m,S==="default"?"number":S)}function $e(m,g){if(g==="string"){var S=m.toString;if(je(S)){var E=S.call(m);if(!q(E))return E}var U=m.valueOf;if(je(U)){var E=U.call(m);if(!q(E))return E}}else{var U=m.valueOf;if(je(U)){var E=U.call(m);if(!q(E))return E}var se=m.toString;if(je(se)){var E=se.call(m);if(!q(E))return E}}throw new TypeError}function Be(m){return!!m}function ft(m){return""+m}function be(m){var g=me(m,3);return Pe(g)?g:ft(g)}function Pt(m){return Array.isArray?Array.isArray(m):m instanceof Object?m instanceof Array:Object.prototype.toString.call(m)==="[object Array]"}function je(m){return typeof m=="function"}function yo(m){return typeof m=="function"}function La(m){switch(G(m)){case 3:return!0;case 4:return!0;default:return!1}}function ur(m,g){return m===g||m!==m&&g!==g}function _o(m,g){var S=m[g];if(S!=null){if(!je(S))throw new TypeError;return S}}function wo(m){var g=_o(m,s);if(!je(g))throw new TypeError;var S=g.call(m);if(!q(S))throw new TypeError;return S}function vo(m){return m.value}function bo(m){var g=m.next();return g.done?!1:g}function So(m){var g=m.return;g&&g.call(m)}function lr(m){var g=Object.getPrototypeOf(m);if(typeof m!="function"||m===c||g!==c)return g;var S=m.prototype,E=S&&Object.getPrototypeOf(S);if(E==null||E===Object.prototype)return g;var U=E.constructor;return typeof U!="function"||U===m?g:U}function $a(){var m;!I(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(m=Da(n.Reflect));var g,S,E,U=new p,se={registerProvider:ce,getProvider:P,setProvider:L};return se;function ce($){if(!Object.isExtensible(se))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case m===$:break;case I(g):g=$;break;case g===$:break;case I(S):S=$;break;case S===$:break;default:E===void 0&&(E=new f),E.add($);break}}function W($,J){if(!I(g)){if(g.isProviderFor($,J))return g;if(!I(S)){if(S.isProviderFor($,J))return g;if(!I(E))for(var Q=wo(E);;){var ae=bo(Q);if(!ae)return;var Ce=vo(ae);if(Ce.isProviderFor($,J))return So(Q),Ce}}}if(!I(m)&&m.isProviderFor($,J))return m}function P($,J){var Q=U.get($),ae;return I(Q)||(ae=Q.get(J)),I(ae)&&(ae=W($,J),I(ae)||(I(Q)&&(Q=new y,U.set($,Q)),Q.set(J,ae))),ae}function M($){if(I($))throw new TypeError;return g===$||S===$||!I(E)&&E.has($)}function L($,J,Q){if(!M(Q))throw new Error("Metadata provider not registered.");var ae=P($,J);if(ae!==Q){if(!I(ae))return!1;var Ce=U.get($);I(Ce)&&(Ce=new y,U.set($,Ce)),Ce.set(J,Q)}return!0}}function Na(){var m;return!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&(m=n.Reflect[w]),I(m)&&(m=$a()),!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:m}),m}function Ua(m){var g=new p,S={isProviderFor:function(M,L){var $=g.get(M);return I($)?!1:$.has(L)},OrdinaryDefineOwnMetadata:ce,OrdinaryHasOwnMetadata:U,OrdinaryGetOwnMetadata:se,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:P};return _.registerProvider(S),S;function E(M,L,$){var J=g.get(M),Q=!1;if(I(J)){if(!$)return;J=new y,g.set(M,J),Q=!0}var ae=J.get(L);if(I(ae)){if(!$)return;if(ae=new y,J.set(L,ae),!m.setProvider(M,L,S))throw J.delete(L),Q&&g.delete(M),new Error("Wrong provider for target.")}return ae}function U(M,L,$){var J=E(L,$,!1);return I(J)?!1:Be(J.has(M))}function se(M,L,$){var J=E(L,$,!1);if(!I(J))return J.get(M)}function ce(M,L,$,J){var Q=E($,J,!0);Q.set(M,L)}function W(M,L){var $=[],J=E(M,L,!1);if(I(J))return $;for(var Q=J.keys(),ae=wo(Q),Ce=0;;){var ko=bo(ae);if(!ko)return $.length=Ce,$;var qa=vo(ko);try{$[Ce]=qa}catch(Ha){try{So(ae)}finally{throw Ha}}Ce++}}function P(M,L,$){var J=E(L,$,!1);if(I(J)||!J.delete(M))return!1;if(J.size===0){var Q=g.get(L);I(Q)||(Q.delete($),Q.size===0&&g.delete(Q))}return!0}}function Da(m){var g=m.defineMetadata,S=m.hasOwnMetadata,E=m.getOwnMetadata,U=m.getOwnMetadataKeys,se=m.deleteMetadata,ce=new p,W={isProviderFor:function(P,M){var L=ce.get(P);return!I(L)&&L.has(M)?!0:U(P,M).length?(I(L)&&(L=new f,ce.set(P,L)),L.add(M),!0):!1},OrdinaryDefineOwnMetadata:g,OrdinaryHasOwnMetadata:S,OrdinaryGetOwnMetadata:E,OrdinaryOwnMetadataKeys:U,OrdinaryDeleteMetadata:se};return W}function Ct(m,g,S){var E=_.getProvider(m,g);if(!I(E))return E;if(S){if(_.setProvider(m,g,b))return b;throw new Error("Illegal state.")}}function Fa(){var m={},g=[],S=(function(){function W(P,M,L){this._index=0,this._keys=P,this._values=M,this._selector=L}return W.prototype["@@iterator"]=function(){return this},W.prototype[s]=function(){return this},W.prototype.next=function(){var P=this._index;if(P>=0&&P<this._keys.length){var M=this._selector(this._keys[P],this._values[P]);return P+1>=this._keys.length?(this._index=-1,this._keys=g,this._values=g):this._index++,{value:M,done:!1}}return{value:void 0,done:!0}},W.prototype.throw=function(P){throw this._index>=0&&(this._index=-1,this._keys=g,this._values=g),P},W.prototype.return=function(P){return this._index>=0&&(this._index=-1,this._keys=g,this._values=g),{value:P,done:!0}},W})(),E=(function(){function W(){this._keys=[],this._values=[],this._cacheKey=m,this._cacheIndex=-2}return Object.defineProperty(W.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),W.prototype.has=function(P){return this._find(P,!1)>=0},W.prototype.get=function(P){var M=this._find(P,!1);return M>=0?this._values[M]:void 0},W.prototype.set=function(P,M){var L=this._find(P,!0);return this._values[L]=M,this},W.prototype.delete=function(P){var M=this._find(P,!1);if(M>=0){for(var L=this._keys.length,$=M+1;$<L;$++)this._keys[$-1]=this._keys[$],this._values[$-1]=this._values[$];return this._keys.length--,this._values.length--,ur(P,this._cacheKey)&&(this._cacheKey=m,this._cacheIndex=-2),!0}return!1},W.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=m,this._cacheIndex=-2},W.prototype.keys=function(){return new S(this._keys,this._values,U)},W.prototype.values=function(){return new S(this._keys,this._values,se)},W.prototype.entries=function(){return new S(this._keys,this._values,ce)},W.prototype["@@iterator"]=function(){return this.entries()},W.prototype[s]=function(){return this.entries()},W.prototype._find=function(P,M){if(!ur(this._cacheKey,P)){this._cacheIndex=-1;for(var L=0;L<this._keys.length;L++)if(ur(this._keys[L],P)){this._cacheIndex=L;break}}return this._cacheIndex<0&&M&&(this._cacheIndex=this._keys.length,this._keys.push(P),this._values.push(void 0)),this._cacheIndex},W})();return E;function U(W,P){return W}function se(W,P){return P}function ce(W,P){return[W,P]}}function Ba(){var m=(function(){function g(){this._map=new y}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(S){return this._map.has(S)},g.prototype.add=function(S){return this._map.set(S,S),this},g.prototype.delete=function(S){return this._map.delete(S)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.keys()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[s]=function(){return this.keys()},g})();return m}function ja(){var m=16,g=d.create(),S=E();return(function(){function P(){this._key=E()}return P.prototype.has=function(M){var L=U(M,!1);return L!==void 0?d.has(L,this._key):!1},P.prototype.get=function(M){var L=U(M,!1);return L!==void 0?d.get(L,this._key):void 0},P.prototype.set=function(M,L){var $=U(M,!0);return $[this._key]=L,this},P.prototype.delete=function(M){var L=U(M,!1);return L!==void 0?delete L[this._key]:!1},P.prototype.clear=function(){this._key=E()},P})();function E(){var P;do P="@@WeakMap@@"+W();while(d.has(g,P));return g[P]=!0,P}function U(P,M){if(!r.call(P,S)){if(!M)return;Object.defineProperty(P,S,{value:d.create()})}return P[S]}function se(P,M){for(var L=0;L<M;++L)P[L]=Math.random()*255|0;return P}function ce(P){if(typeof Uint8Array=="function"){var M=new Uint8Array(P);return typeof crypto<"u"?crypto.getRandomValues(M):typeof msCrypto<"u"?msCrypto.getRandomValues(M):se(M,P),M}return se(new Array(P),P)}function W(){var P=ce(m);P[6]=P[6]&79|64,P[8]=P[8]&191|128;for(var M="",L=0;L<m;++L){var $=P[L];(L===4||L===6||L===8)&&(M+="-"),$<16&&(M+="0"),M+=$.toString(16).toLowerCase()}return M}}function dr(m){return m.__=void 0,delete m.__,m}})})(xo||(xo={}))});x();var tg=mt(Eo(),1),Me=mt(require("process"),1);x();var Ru=mt(require("os"),1),xu=mt(require("path"),1),Eu=require("url"),Ou=require("util");x();x();var pe=class extends Error{},Qa=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Za(t){if(typeof t!="string")return!1;let e=Qa.exec(t);if(!e)return!1;let[,n,r,o,i,s,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,i,s,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===i&&u.getUTCMinutes()===s&&u.getUTCSeconds()===a}function eu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new pe(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:i}=e;if(typeof n!="string"||n==="")throw new pe(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new pe(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let s=r.map((a,u)=>{if(a===null||typeof a!="object")throw new pe(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let l=a;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new pe(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);let d=(c,y)=>{if(l[c]!==void 0&&l[c]!==null&&!y)throw new pe(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",Za(l.ready_since));for(let c of["model_id","variant"]){let y=l[c];if(y.includes(":"))throw new pe(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(y)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new pe(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(i!=null){let a=i;if(typeof i!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new pe(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new pe(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return s.length===0?null:{shared_org_id:n,endpoints:s,...o!=null?{regions:o}:{},...i!=null?{compliance:i}:{}}}function ht(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Oo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,i=n,s=r.lastIndexOf(":");s>0&&(o=r.slice(0,s),i=r.slice(s+1));let a=t.endpoints.filter(l=>l.model_id===o);if(a.length===0)return null;if(i!==void 0){let l=a.find(d=>d.variant===i);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(l=>l.compat_default===!0);if(u.length!==1)throw new pe(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Io(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new pe(`catalog read failed: GET ${n} \u2192 ${r.status}`);return eu(await r.json())}x();function qe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var xe=class extends Error{name="ModelPriceError"},cr="per_million_input_tokens",pr="per_million_output_tokens",To="model_id,variant,unit,price_usd,effective_at,expires_at",Ao={per_request:!0,per_minute:!0,per_output_unit:!0},tu=5e3;function nu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new xe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Po(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new xe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function ru(t,e,n){return t===null?null:Po(t,e,n)}function ou(t,e){if(t===cr)return"input";if(t===pr)return"output";if(typeof t=="string"&&Object.hasOwn(Ao,t))return null;throw new xe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${cr} | ${pr}) nor a known GPU-time unit (${Object.keys(Ao).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 iu(t,e){let n=t.reduce((o,i)=>i.effective_at>o.effective_at?i: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 fr(t,e){return`${t}\0${e}`}function su(t){if(!Array.isArray(t))throw new xe(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new xe(`${o} is not an object: ${JSON.stringify(r)}`);let i=r;for(let l of To.split(","))if(!Object.hasOwn(i,l))throw new xe(`${o} has no "${l}" column: ${JSON.stringify(i)}`);let s=ou(i.unit,o);if(s===null)continue;let a=i.model_id;if(typeof a!="string"||a==="")throw new xe(`${o} has no model_id (${JSON.stringify(i)})`);let u=i.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new xe(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:s,usd:nu(i.price_usd,o),effective_at:Po(i.effective_at,o,"effective_at"),expires_at:ru(i.expires_at,o,"expires_at")})}return e}function Co(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let l=r.get(u.model_id);l||(l=new Map,r.set(u.model_id,l),o.set(u.model_id,new Map));let d=u.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(u.model_id).set(d,u.variant)),c[u.side].push({effective_at:u.effective_at,usd:u.usd})}let i=[],s=[];for(let[u,l]of r){let d=l.get(""),c=(y,f,p)=>{let w=y&&y.length>0?y:d?.[f];if(!w||w.length===0)return null;let _=iu(w,f);return"reason"in _?_:_.rate.usd===0?f==="output"&&p!==null&&n?.has(fr(u,p))?_.rate:{reason:`the ${f} 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`}:_.rate};for(let[y,f]of o.get(u)){let p=l.get(y),w=c(p?.input,"input",f),_=c(p?.output,"output",f);if(w!==null&&"reason"in w){s.push({model_id:u,variant:f,reason:w.reason});continue}if(_!==null&&"reason"in _){s.push({model_id:u,variant:f,reason:_.reason});continue}w===null||_===null||i.push({model_id:u,variant:f,pricing:{input:w.usd,output:_.usd}})}}let a=(u,l)=>u.model_id.localeCompare(l.model_id)||(u.variant===null?1:0)-(l.variant===null?1:0)||(u.variant??"").localeCompare(l.variant??"");return{prices:i.sort(a),refusals:s.sort(a)}}function Mt(t,e,n){if(n.refusals.some(i=>i.model_id===t&&i.variant===e))return null;let r=n.prices.find(i=>i.model_id===t&&i.variant===e);if(r)return r.pricing;if(n.refusals.some(i=>i.model_id===t&&i.variant===null))return null;let o=n.prices.find(i=>i.model_id===t&&i.variant===null);return o?o.pricing:null}var Lt={prices:[],refusals:[]};async function Mo(t){let e=t.fetchImpl??fetch,n=`${cr},${pr}`,r=await e(`${t.catalogUrl}/model_prices?select=${To}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(tu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return su(await r.json())}x();var et="/partners/openrouter/models",au={chat:!0,code:!0,agent:!0,vl:!0},Lo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function uu(t){let e=t.toLowerCase();return Object.hasOwn(Lo,e)?Lo[e]:null}var $o={"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 lu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let i=Object.hasOwn($o,o)?$o[o]:null;if(i===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:i,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 No={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Uo={2:"Llama2",3:"Llama3"};function du(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 i=r[o];if(Object.hasOwn(No,i))return No[i];let s=r[o+1];if(i==="llama"&&s!==void 0&&Object.hasOwn(Uo,s))return Uo[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var cu=["context_length","max_model_len"];function pu(t){let e=cu.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 nn(t){let e=t.map(pu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function fu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function mr(t){if(t.length===0)return null;let e=t.map(fu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function mu(t,e){let n=e.filter(o=>qe(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return tn(n);let r=e.filter(o=>qe(o.model_id)===t);return r.length>0?tn(r):null}function tn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:hu(t),matches:t}:null}function hu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Bo(t){return 0}function Ze(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rn(t,e,n){let r=mu(t,e);if(!r)return Ze({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:i}=r,s=nn(i),a=Mt(o.model_id,o.variant,n),u=jo(o,i),l=mr(i);return Ze({id:t,object:"model",created:Bo(o),owned_by:"urun",...s!==null?{context_length:s}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...l!==null?{capabilities:{reasoning:l}}:{}})}var gu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function jo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(i=>i.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(i=>typeof i=="string")&&n.every(i=>Array.isArray(i)&&i.length===r.length&&i.every((s,a)=>s===r[a])))return{published:[...r],defect:null};let o=n.some(i=>i!=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:[...gu],defect:o}:{published:[],defect:o}}function hr(t){let e=t.length>0?tn(t):null;return e===null?{published:[],defect:null}:jo(e.row,e.matches)}function Do(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,i=n+r,s=n.length-6+(o===""?0:Number(o));return(s<=0?`0.${"0".repeat(-s)}${i}`:`${i.slice(0,s)}.${i.slice(s).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Fo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Do(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Do(t.output)}]}}function yu(t,e,n,r){if(e.length===0)return null;let o=tn(e);if(!o)return null;let{row:i,matches:s}=o;if(!i.task||au[i.task]!==!0)return null;let a=nn(s),u=Mt(i.model_id,i.variant,n),l=du(i.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:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:Bo(i),quantization:uu(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Fo(u).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Fo(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function qo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),i=t?ht(t):[];if(i.length>0){let l=i.filter(d=>d.ready===void 0);if(l.length===i.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.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 s={datacenters:lu(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of i){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=yu(l,e.filter(y=>y.model_id===l.model_id&&y.variant===l.variant),n,s);c&&a.push(c)}return{data:a}}x();var Ho={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},gt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Go(t){let e=t.t;if(typeof e!="string"||!(e in Ho))throw new gt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ho).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 _u(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new gt(`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 gt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Go(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new gt(`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 Go(t)}function Vo(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function wu(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=s=>{r||(r=!0,e.removeEventListener("abort",i),n(s))},i=()=>o("aborted");e.addEventListener("abort",i,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Wo(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 Vo(e);let i=o.next();if(e!==void 0&&await wu(i,e)==="aborted")throw i.catch(()=>{}),Vo(e);let s=await i;if(s.done)return;yield _u(s.value)}}finally{let i=o.return?.();i&&i.catch(()=>{})}}return r()}var Y=class extends Error{},re=class extends Error{},yr="urs1.";function Jo(t,e){return yr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function vu(t){if(!t.startsWith(yr))return null;try{let e=JSON.parse(Buffer.from(t.slice(yr.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 Xo(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 Ko(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Su(t);return e===null?[]:[e]}function gr(t,e,n,r,o){if(!o)throw new pe(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new pe(`shared model "${t}" resolved without a catalog id + variant to join on`);let i=r.filter(s=>s.model_id===e&&s.variant===n);if(i.length===0)throw new pe(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function zo(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new pe(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Qo="shared:",$t="speech:";function ze(t){return t.sharedApp?Qo+t.appSlug:t.appSlug}function sn(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 Je(t,e){let n=e.filter(i=>qe(`${i.model_id}-${i.variant}`)===t);if(n.length>0)return n;let r=e.filter(i=>qe(i.model_id)===t);return new Set(r.map(i=>i.variant)).size===1?r:[]}function bu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Su(t){let e=t.map(bu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Yo={stt:"stt",tts:"tts"};function Ke(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Yo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Yo[e]:null}function ku(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Error(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var on=6e4,an=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??on;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??on;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??on;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??on;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof xe)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
3
- `),Lt}let r=Co(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
4
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(fr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Qo)||o.startsWith($t)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new Y(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=qe(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),s=this.servable(i);if(s.includes(o))return{appSlug:o};let a=s.filter(l=>l.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new Y(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(l=>l.app_slug===o||l.app_slug.startsWith(`${o}-`));if(u)throw new Y(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let i=await this.sharedBlock();if(i){let s=Oo(i,n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:i.shared_org_id}}}if(this.opts.listCatalog){let s=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===qe(a.model_id)||o===qe(`${a.model_id}-${a.variant}`));if(s)throw new Y(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${s.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=sn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return ze(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ze(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,$t+ze(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:sn(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Jo(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Jo(n,this.keyOf(r))}}async sessionForHandle(e){let n=vu(e);if(!n)throw new re(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,i=this.pool.get(r),s=i?await i.then(a=>a,()=>null):null;if(s===null)throw new re(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(s)!==o)throw new re(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:s}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(i=>i,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),i=r.rows,s=r.ok?o:Lt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
5
- `);let u=(n?ht(n):[]).map(l=>{let d=i.filter(_=>_.model_id===l.model_id&&_.variant===l.variant),c=nn(d),y=mr(d),f=Mt(l.model_id,l.variant,s),p=hr(d);return Ze({id:`${l.model_id}:${l.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...f!==null?{pricing:f}:{},...p.published.length>0?{voices:[...p.published]}:{},...y!==null?{capabilities:{reasoning:y}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>rn(l,i,s)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return qo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let i=gr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return zo(`${r.modelId}:${r.variant}`,i).includes(n)}return Ko(Je(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ke(Je(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ke(Je(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ke(Je(n.appSlug,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):Je(n.appSlug,r);return ku(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):Je(n.appSlug,r);return hr(o)}async imageModelList(){let e=await this.catalogRows(),n=Lt,r=[];for(let i of await this.availableIds()){let s=Ko(Je(i,e));s.length!==0&&r.push(Ze({...rn(i,e,n),image_modes:s}))}let o=await this.sharedBlock();if(o)for(let i of ht(o)){let s=gr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),a=zo(`${i.model_id}:${i.variant}`,s);if(a.length===0)continue;let u=Ze({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Lt,r=[];for(let i of await this.availableIds())Ke(Je(i,e))==="stt"&&r.push(rn(i,e,n));let o=await this.sharedBlock();if(o)for(let i of ht(o)){let s=gr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(Ke(s)!=="stt")continue;let a=Ze({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};function Zo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function ln(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Iu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ei(t){let e=t?.code;return typeof e=="string"&&Iu.has(e)}function Ne(t,e){try{return t.write(e),!0}catch(n){if(ei(n))return!1;throw n}}function ti(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],i=s=>{ei(s)&&(e[r]=!0);let a=s?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(s instanceof Error?s.message:s))}) \u2014 the terminal is gone; launcher output continues in this log only
6
- `)}catch{}};o.on("error",i),n.push([o,i])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}x();var _e=require("@prometheus-io/client"),xi=require("http");x();var Au={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Tu(t){return Au[t]??null}var oi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Pu(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Cu(t){return t==="surface"}function Mu(t){let e=t?.ledgerFailureReason;return oi.includes(e)?e:"unknown"}var Lu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ni=["priced","unpriced"],$u={written:ni,already_written:ni,skipped:Lu,failed:oi},ii=Object.entries($u).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Nu(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Uu(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Du=256,ri=4096,Nt=12e4,Fu=250,Bu=8e3,He=[],_r=new Set,Ut=0,yt=!1;function si(){return He.length}function ai(t=Date.now()){let e=He[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var dn=new Set;function ui(){return Ut===0&&He.length===0}function li(){if(ui()){yt=!1;for(let t of[...dn])t()}}async function di(t=pi){return ui()?!0:await new Promise(e=>{let n=null,r=()=>{dn.delete(r),n&&clearTimeout(n),e(!0)};dn.add(r),n=setTimeout(()=>{dn.delete(r),e(!1)},t),n.unref?.()})}function ci(){yt=!0;let t=[...He.splice(0,He.length),..._r];for(let e of t)e.settled||tt(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${pi}ms drain \u2014 the request was served and answered, and its billing row was never written`});return li(),t.length}var pi=5e3;function fi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
7
- `}function ju(t){Ne(process.stdout,t)}function mi(t,e){try{t(e)}catch{}}function hi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ju,o=Tu(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),mi(r,fi("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Uu(e),completed_at:e.ts,billable_outcome:Nu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(He.length>=ri){s("queue_full",`${He.length} ledger writes are already waiting (capacity ${ri}, ${Ut} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}He.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Ut<Du&&(Ut+=1,qu())}async function qu(){try{for(;;){let t=Hu();if(t===void 0)return;_r.add(t);try{await Gu(t)}finally{_r.delete(t)}}}finally{Ut-=1,li()}}function Hu(){let t=Date.now();for(;;){let e=He.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Nt)return e;tt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Nt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Gu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);tt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Pu(o);if(i!==null){tt(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Mu(o),a=Date.now()-t.queuedAt;if(yt){tt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Cu(s)&&a<Nt){if(await Wu(Vu(t.attempts)),yt||Date.now()-t.queuedAt>=Nt){let u=Date.now()-t.queuedAt;tt(t,{outcome:"failed",reason:yt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:yt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${Nt}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}tt(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Vu(t){return Math.min(Bu,Fu*2**Math.max(0,t-1))}function Wu(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function tt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;mi(t.report,fi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var pn="/v1/usage/requests",gi=1e4,Ju=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ye=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},oe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},cn=class extends oe{constructor(e){super(e),this.name="UsageWithholdingError"}},vi=1024*1024;function br(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ye(`"${e}" must be an array of uuid strings`);if(n.length>gi)throw new Ye(`"${e}" carries ${n.length} ids; at most ${gi} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Ju.test(i))throw new Ye(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function bi(t){return br(t,"inference_ids")}var Ku=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function _t(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is not a non-empty string (got ${vt(r)})`);return r}function wr(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is neither null nor a non-empty string (got ${vt(r)})`);return r}function wt(t,e,n,r){let o=t[e];if(o===null)return null;let i=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(i))throw new oe(`${n}: ${e} is not a number (got ${vt(o)})`);if(r&&!Number.isSafeInteger(i))throw new oe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(i<0)throw new oe(`${n}: ${e} is negative`);return Object.is(i,-0)?0:i}var zu=40,yi=64,_i=600;function Si(t){let e=Object.keys(t).sort(),r=e.slice(0,zu).map(o=>o.length>yi?`${o.slice(0,yi)}\u2026`:o).join(", ");return r.length>_i&&(r=`${r.slice(0,_i)}\u2026`),`${e.length} keys present: [${r}]`}function vt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function vr(t){Ne(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
8
- `)}function Yu(t,e){let n;try{n=t(e)}catch{wi(t,e);return}Xu(n)&&Promise.resolve(n).catch(()=>{wi(t,e)})}function Xu(t){return typeof t?.then=="function"}function wi(t,e){if(t!==vr)try{vr(e)}catch{}}function ki(t,e=vr){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Si(t):vt(t);throw new oe(`the usage surface answered without a "requests" array: got ${vt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let i=`usage.requests[${o}]`;try{r.push(Qu(n[o],i))}catch(s){if(s instanceof cn||!(s instanceof oe))throw s;Yu(e,{where:i,reason:s.message})}}if(n.length>0&&r.length===0)throw new oe(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Qu(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new oe(`${e} is not an object: got ${vt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new cn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Ku)if(!Object.hasOwn(n,o))throw new oe(`${e} has no "${o}" column (${Si(n)})`);let r=wt(n,"http_status",e,!0);if(r===null)throw new oe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:_t(n,"inference_id",e),model_id:_t(n,"model_id",e),identity_kind:_t(n,"identity_kind",e),variant:wr(n,"variant",e),task:_t(n,"task",e),http_status:r,started_at:_t(n,"started_at",e),completed_at:_t(n,"completed_at",e),prompt_tokens:wt(n,"prompt_tokens",e,!0),completion_tokens:wt(n,"completion_tokens",e,!0),output_units:wt(n,"output_units",e,!1),output_minutes:wt(n,"output_minutes",e,!1),cost_nano_usd:wt(n,"cost_nano_usd",e,!0),price_version:wr(n,"price_version",e),priced_at:wr(n,"priced_at",e)}}function fn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new oe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new oe(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Dt="/partners/huggingface/v1/billing/requests";function Zu(t){return br(t,"requestIds")}function el(t){return t>=200&&t<=399}function tl(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&el(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ri(t,e){let n=Zu(t),r=await e(n);return fn(r,n),tl(r)}var Sr=9464,mn="/metrics",hn="(other)",nl="(none)",rl=64,ol=128,il=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",pn,Dt,et],sl=new Set(il);function al(t){return sl.has(t)?t:hn}function ul(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var gn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?nl:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,hn):(this.admitted.add(e),e):hn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},yn=class{registry=new _e.Registry;modelLabel=new gn(rl);orgLabel=new gn(ol);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new _e.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new _e.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new _e.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new _e.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new _e.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new _e.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of ii)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new _e.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},si()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ai()/1e3)}}),this.labelCardinality=new _e.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new _e.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,_e.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=al(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?hn:e.method,status_class:ul(e.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Ei(t){return(0,xi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==mn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${mn}
2
+ "use strict";var ll=Object.create;var hs=Object.defineProperty;var dl=Object.getOwnPropertyDescriptor;var cl=Object.getOwnPropertyNames;var pl=Object.getPrototypeOf,fl=Object.prototype.hasOwnProperty;var ml=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var gl=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var hl=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cl(e))!fl.call(t,o)&&o!==n&&hs(t,o,{get:()=>e[o],enumerable:!(r=dl(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?ll(pl(t)):{},hl(e||!t||!t.__esModule?hs(n,"default",{value:t,enumerable:!0}):n,t));var k=ml(()=>{"use strict"});var ws=gl(()=>{"use strict";k();var ys;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,l){return function(d,c){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:c}),l&&l(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",u={__proto__:[]}instanceof Array,l=!a&&!u,d={create:a?function(){return Gr(Object.create(null))}:u?function(){return Gr({__proto__:null})}:function(){return Gr({})},has:l?function(_,S){return r.call(_,S)}:function(_,S){return S in _},get:l?function(_,S){return r.call(_,S)?_[S]:void 0}:function(_,S){return _[S]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ol(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:sl(),h=typeof WeakMap=="function"?WeakMap:il(),v=o?Symbol.for("@reflect-metadata:registry"):void 0,I=tl(),b=nl(I);function f(_,S,E,L){if(M(E)){if(!en(_))throw new TypeError;if(!ls(S))throw new TypeError;return P(_,S)}else{if(!en(_))throw new TypeError;if(!ne(S))throw new TypeError;if(!ne(L)&&!M(L)&&!ee(L))throw new TypeError;return ee(L)&&(L=void 0),E=Oe(E),H(_,S,E,L)}}e("decorate",f);function m(_,S){function E(L,G){if(!ne(L))throw new TypeError;if(!M(G)&&!Zu(G))throw new TypeError;Be(_,S,L,G)}return E}e("metadata",m);function w(_,S,E,L){if(!ne(E))throw new TypeError;return M(L)||(L=Oe(L)),Be(_,S,E,L)}e("defineMetadata",w);function g(_,S,E){if(!ne(S))throw new TypeError;return M(E)||(E=Oe(E)),W(_,S,E)}e("hasMetadata",g);function x(_,S,E){if(!ne(S))throw new TypeError;return M(E)||(E=Oe(E)),K(_,S,E)}e("hasOwnMetadata",x);function R(_,S,E){if(!ne(S))throw new TypeError;return M(E)||(E=Oe(E)),oe(_,S,E)}e("getMetadata",R);function A(_,S,E){if(!ne(S))throw new TypeError;return M(E)||(E=Oe(E)),te(_,S,E)}e("getOwnMetadata",A);function T(_,S){if(!ne(_))throw new TypeError;return M(S)||(S=Oe(S)),se(_,S)}e("getMetadataKeys",T);function O(_,S){if(!ne(_))throw new TypeError;return M(S)||(S=Oe(S)),ve(_,S)}e("getOwnMetadataKeys",O);function C(_,S,E){if(!ne(S))throw new TypeError;if(M(E)||(E=Oe(E)),!ne(S))throw new TypeError;M(E)||(E=Oe(E));var L=tn(S,E,!1);return M(L)?!1:L.OrdinaryDeleteMetadata(_,S,E)}e("deleteMetadata",C);function P(_,S){for(var E=_.length-1;E>=0;--E){var L=_[E],G=L(S);if(!M(G)&&!ee(G)){if(!ls(G))throw new TypeError;S=G}}return S}function H(_,S,E,L){for(var G=_.length-1;G>=0;--G){var ge=_[G],_e=ge(S,E,L);if(!M(_e)&&!ee(_e)){if(!ne(_e))throw new TypeError;L=_e}}return L}function W(_,S,E){var L=K(_,S,E);if(L)return!0;var G=qr(S);return ee(G)?!1:W(_,G,E)}function K(_,S,E){var L=tn(S,E,!1);return M(L)?!1:Ae(L.OrdinaryHasOwnMetadata(_,S,E))}function oe(_,S,E){var L=K(_,S,E);if(L)return te(_,S,E);var G=qr(S);if(!ee(G))return oe(_,G,E)}function te(_,S,E){var L=tn(S,E,!1);if(!M(L))return L.OrdinaryGetOwnMetadata(_,S,E)}function Be(_,S,E,L){var G=tn(E,L,!0);G.OrdinaryDefineOwnMetadata(_,S,E,L)}function se(_,S){var E=ve(_,S),L=qr(_);if(L===null)return E;var G=se(L,S);if(G.length<=0)return E;if(E.length<=0)return G;for(var ge=new y,_e=[],z=0,N=E;z<N.length;z++){var U=N[z],D=ge.has(U);D||(ge.add(U),_e.push(U))}for(var j=0,Y=G;j<Y.length;j++){var U=Y[j],D=ge.has(U);D||(ge.add(U),_e.push(U))}return _e}function ve(_,S){var E=tn(_,S,!1);return E?E.OrdinaryOwnMetadataKeys(_,S):[]}function V(_){if(_===null)return 1;switch(typeof _){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return _===null?1:6;default:return 6}}function M(_){return _===void 0}function ee(_){return _===null}function Qe(_){return typeof _=="symbol"}function ne(_){return typeof _=="object"?_!==null:typeof _=="function"}function re(_,S){switch(V(_)){case 0:return _;case 1:return _;case 2:return _;case 3:return _;case 4:return _;case 5:return _}var E=S===3?"string":S===5?"number":"default",L=ds(_,s);if(L!==void 0){var G=L.call(_,E);if(ne(G))throw new TypeError;return G}return ue(_,E==="default"?"number":E)}function ue(_,S){if(S==="string"){var E=_.toString;if(et(E)){var L=E.call(_);if(!ne(L))return L}var G=_.valueOf;if(et(G)){var L=G.call(_);if(!ne(L))return L}}else{var G=_.valueOf;if(et(G)){var L=G.call(_);if(!ne(L))return L}var ge=_.toString;if(et(ge)){var L=ge.call(_);if(!ne(L))return L}}throw new TypeError}function Ae(_){return!!_}function Ze(_){return""+_}function Oe(_){var S=re(_,3);return Qe(S)?S:Ze(S)}function en(_){return Array.isArray?Array.isArray(_):_ instanceof Object?_ instanceof Array:Object.prototype.toString.call(_)==="[object Array]"}function et(_){return typeof _=="function"}function ls(_){return typeof _=="function"}function Zu(_){switch(V(_)){case 3:return!0;case 4:return!0;default:return!1}}function jr(_,S){return _===S||_!==_&&S!==S}function ds(_,S){var E=_[S];if(E!=null){if(!et(E))throw new TypeError;return E}}function cs(_){var S=ds(_,i);if(!et(S))throw new TypeError;var E=S.call(_);if(!ne(E))throw new TypeError;return E}function ps(_){return _.value}function fs(_){var S=_.next();return S.done?!1:S}function ms(_){var S=_.return;S&&S.call(_)}function qr(_){var S=Object.getPrototypeOf(_);if(typeof _!="function"||_===c||S!==c)return S;var E=_.prototype,L=E&&Object.getPrototypeOf(E);if(L==null||L===Object.prototype)return S;var G=L.constructor;return typeof G!="function"||G===_?S:G}function el(){var _;!M(v)&&typeof n.Reflect<"u"&&!(v in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(_=rl(n.Reflect));var S,E,L,G=new h,ge={registerProvider:_e,getProvider:N,setProvider:D};return ge;function _e(j){if(!Object.isExtensible(ge))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case _===j:break;case M(S):S=j;break;case S===j:break;case M(E):E=j;break;case E===j:break;default:L===void 0&&(L=new y),L.add(j);break}}function z(j,Y){if(!M(S)){if(S.isProviderFor(j,Y))return S;if(!M(E)){if(E.isProviderFor(j,Y))return S;if(!M(L))for(var ie=cs(L);;){var he=fs(ie);if(!he)return;var He=ps(he);if(He.isProviderFor(j,Y))return ms(ie),He}}}if(!M(_)&&_.isProviderFor(j,Y))return _}function N(j,Y){var ie=G.get(j),he;return M(ie)||(he=ie.get(Y)),M(he)&&(he=z(j,Y),M(he)||(M(ie)&&(ie=new p,G.set(j,ie)),ie.set(Y,he))),he}function U(j){if(M(j))throw new TypeError;return S===j||E===j||!M(L)&&L.has(j)}function D(j,Y,ie){if(!U(ie))throw new Error("Metadata provider not registered.");var he=N(j,Y);if(he!==ie){if(!M(he))return!1;var He=G.get(j);M(He)&&(He=new p,G.set(j,He)),He.set(Y,ie)}return!0}}function tl(){var _;return!M(v)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&(_=n.Reflect[v]),M(_)&&(_=el()),!M(v)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,v,{enumerable:!1,configurable:!1,writable:!1,value:_}),_}function nl(_){var S=new h,E={isProviderFor:function(U,D){var j=S.get(U);return M(j)?!1:j.has(D)},OrdinaryDefineOwnMetadata:_e,OrdinaryHasOwnMetadata:G,OrdinaryGetOwnMetadata:ge,OrdinaryOwnMetadataKeys:z,OrdinaryDeleteMetadata:N};return I.registerProvider(E),E;function L(U,D,j){var Y=S.get(U),ie=!1;if(M(Y)){if(!j)return;Y=new p,S.set(U,Y),ie=!0}var he=Y.get(D);if(M(he)){if(!j)return;if(he=new p,Y.set(D,he),!_.setProvider(U,D,E))throw Y.delete(D),ie&&S.delete(U),new Error("Wrong provider for target.")}return he}function G(U,D,j){var Y=L(D,j,!1);return M(Y)?!1:Ae(Y.has(U))}function ge(U,D,j){var Y=L(D,j,!1);if(!M(Y))return Y.get(U)}function _e(U,D,j,Y){var ie=L(j,Y,!0);ie.set(U,D)}function z(U,D){var j=[],Y=L(U,D,!1);if(M(Y))return j;for(var ie=Y.keys(),he=cs(ie),He=0;;){var gs=fs(he);if(!gs)return j.length=He,j;var al=ps(gs);try{j[He]=al}catch(ul){try{ms(he)}finally{throw ul}}He++}}function N(U,D,j){var Y=L(D,j,!1);if(M(Y)||!Y.delete(U))return!1;if(Y.size===0){var ie=S.get(D);M(ie)||(ie.delete(j),ie.size===0&&S.delete(ie))}return!0}}function rl(_){var S=_.defineMetadata,E=_.hasOwnMetadata,L=_.getOwnMetadata,G=_.getOwnMetadataKeys,ge=_.deleteMetadata,_e=new h,z={isProviderFor:function(N,U){var D=_e.get(N);return!M(D)&&D.has(U)?!0:G(N,U).length?(M(D)&&(D=new y,_e.set(N,D)),D.add(U),!0):!1},OrdinaryDefineOwnMetadata:S,OrdinaryHasOwnMetadata:E,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:G,OrdinaryDeleteMetadata:ge};return z}function tn(_,S,E){var L=I.getProvider(_,S);if(!M(L))return L;if(E){if(I.setProvider(_,S,b))return b;throw new Error("Illegal state.")}}function ol(){var _={},S=[],E=(function(){function z(N,U,D){this._index=0,this._keys=N,this._values=U,this._selector=D}return z.prototype["@@iterator"]=function(){return this},z.prototype[i]=function(){return this},z.prototype.next=function(){var N=this._index;if(N>=0&&N<this._keys.length){var U=this._selector(this._keys[N],this._values[N]);return N+1>=this._keys.length?(this._index=-1,this._keys=S,this._values=S):this._index++,{value:U,done:!1}}return{value:void 0,done:!0}},z.prototype.throw=function(N){throw this._index>=0&&(this._index=-1,this._keys=S,this._values=S),N},z.prototype.return=function(N){return this._index>=0&&(this._index=-1,this._keys=S,this._values=S),{value:N,done:!0}},z})(),L=(function(){function z(){this._keys=[],this._values=[],this._cacheKey=_,this._cacheIndex=-2}return Object.defineProperty(z.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),z.prototype.has=function(N){return this._find(N,!1)>=0},z.prototype.get=function(N){var U=this._find(N,!1);return U>=0?this._values[U]:void 0},z.prototype.set=function(N,U){var D=this._find(N,!0);return this._values[D]=U,this},z.prototype.delete=function(N){var U=this._find(N,!1);if(U>=0){for(var D=this._keys.length,j=U+1;j<D;j++)this._keys[j-1]=this._keys[j],this._values[j-1]=this._values[j];return this._keys.length--,this._values.length--,jr(N,this._cacheKey)&&(this._cacheKey=_,this._cacheIndex=-2),!0}return!1},z.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=_,this._cacheIndex=-2},z.prototype.keys=function(){return new E(this._keys,this._values,G)},z.prototype.values=function(){return new E(this._keys,this._values,ge)},z.prototype.entries=function(){return new E(this._keys,this._values,_e)},z.prototype["@@iterator"]=function(){return this.entries()},z.prototype[i]=function(){return this.entries()},z.prototype._find=function(N,U){if(!jr(this._cacheKey,N)){this._cacheIndex=-1;for(var D=0;D<this._keys.length;D++)if(jr(this._keys[D],N)){this._cacheIndex=D;break}}return this._cacheIndex<0&&U&&(this._cacheIndex=this._keys.length,this._keys.push(N),this._values.push(void 0)),this._cacheIndex},z})();return L;function G(z,N){return z}function ge(z,N){return N}function _e(z,N){return[z,N]}}function sl(){var _=(function(){function S(){this._map=new p}return Object.defineProperty(S.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),S.prototype.has=function(E){return this._map.has(E)},S.prototype.add=function(E){return this._map.set(E,E),this},S.prototype.delete=function(E){return this._map.delete(E)},S.prototype.clear=function(){this._map.clear()},S.prototype.keys=function(){return this._map.keys()},S.prototype.values=function(){return this._map.keys()},S.prototype.entries=function(){return this._map.entries()},S.prototype["@@iterator"]=function(){return this.keys()},S.prototype[i]=function(){return this.keys()},S})();return _}function il(){var _=16,S=d.create(),E=L();return(function(){function N(){this._key=L()}return N.prototype.has=function(U){var D=G(U,!1);return D!==void 0?d.has(D,this._key):!1},N.prototype.get=function(U){var D=G(U,!1);return D!==void 0?d.get(D,this._key):void 0},N.prototype.set=function(U,D){var j=G(U,!0);return j[this._key]=D,this},N.prototype.delete=function(U){var D=G(U,!1);return D!==void 0?delete D[this._key]:!1},N.prototype.clear=function(){this._key=L()},N})();function L(){var N;do N="@@WeakMap@@"+z();while(d.has(S,N));return S[N]=!0,N}function G(N,U){if(!r.call(N,E)){if(!U)return;Object.defineProperty(N,E,{value:d.create()})}return N[E]}function ge(N,U){for(var D=0;D<U;++D)N[D]=Math.random()*255|0;return N}function _e(N){if(typeof Uint8Array=="function"){var U=new Uint8Array(N);return typeof crypto<"u"?crypto.getRandomValues(U):typeof msCrypto<"u"?msCrypto.getRandomValues(U):ge(U,N),U}return ge(new Array(N),N)}function z(){var N=_e(_);N[6]=N[6]&79|64,N[8]=N[8]&191|128;for(var U="",D=0;D<_;++D){var j=N[D];(D===4||D===6||D===8)&&(U+="-"),j<16&&(U+="0"),U+=j.toString(16).toLowerCase()}return U}}function Gr(_){return _.__=void 0,delete _.__,_}})})(ys||(ys={}))});k();var b_=Re(ws(),1),Ke=Re(require("process"),1);k();var Gl=Re(require("os"),1),Vl=Re(require("path"),1),Wl=require("url"),Jl=require("util");k();k();var ce=class extends Error{},yl=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function wl(t){if(typeof t!="string")return!1;let e=yl.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function _l(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ce(`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 ce(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ce(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new ce(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let l=a;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new ce(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new ce(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new ce(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",wl(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ce(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new ce(`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 ce(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new ce(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function It(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Vr(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(l=>l.model_id===o);if(a.length===0)return null;if(s!==void 0){let l=a.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(l=>l.compat_default===!0);if(u.length!==1)throw new ce(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function _s(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 ce(`catalog read failed: GET ${n} \u2192 ${r.status}`);return _l(await r.json())}k();function Ce(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}k();var Me=class extends Error{name="ModelPriceError"},Wr="per_million_input_tokens",Jr="per_million_output_tokens",bs="model_id,variant,unit,price_usd,effective_at,expires_at",vs={per_request:!0,per_minute:!0,per_output_unit:!0},vl=5e3;function bl(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Me(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ss(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Me(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Sl(t,e,n){return t===null?null:Ss(t,e,n)}function kl(t,e){if(t===Wr)return"input";if(t===Jr)return"output";if(typeof t=="string"&&Object.hasOwn(vs,t))return null;throw new Me(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Wr} | ${Jr}) nor a known GPU-time unit (${Object.keys(vs).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 Rl(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 Kr(t,e){return`${t}\0${e}`}function xl(t){if(!Array.isArray(t))throw new Me(`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 Me(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of bs.split(","))if(!Object.hasOwn(s,l))throw new Me(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=kl(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Me(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new Me(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:bl(s.price_usd,o),effective_at:Ss(s.effective_at,o,"effective_at"),expires_at:Sl(s.expires_at,o,"expires_at")})}return e}function ks(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let l=r.get(u.model_id);l||(l=new Map,r.set(u.model_id,l),o.set(u.model_id,new Map));let d=u.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(u.model_id).set(d,u.variant)),c[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,l]of r){let d=l.get(""),c=(p,y,h)=>{let v=p&&p.length>0?p:d?.[y];if(!v||v.length===0)return null;let I=Rl(v,y);return"reason"in I?I:I.rate.usd===0?y==="output"&&h!==null&&n?.has(Kr(u,h))?I.rate:{reason:`the ${y} 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`}:I.rate};for(let[p,y]of o.get(u)){let h=l.get(p),v=c(h?.input,"input",y),I=c(h?.output,"output",y);if(v!==null&&"reason"in v){i.push({model_id:u,variant:y,reason:v.reason});continue}if(I!==null&&"reason"in I){i.push({model_id:u,variant:y,reason:I.reason});continue}v===null||I===null||s.push({model_id:u,variant:y,pricing:{input:v.usd,output:I.usd}})}}let a=(u,l)=>u.model_id.localeCompare(l.model_id)||(u.variant===null?1:0)-(l.variant===null?1:0)||(u.variant??"").localeCompare(l.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function nn(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 rn={prices:[],refusals:[]};async function Rs(t){let e=t.fetchImpl??fetch,n=`${Wr},${Jr}`,r=await e(`${t.catalogUrl}/model_prices?select=${bs}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(vl)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return xl(await r.json())}k();var gt="/partners/openrouter/models",El={chat:!0,code:!0,agent:!0,vl:!0},xs={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Al(t){let e=t.toLowerCase();return Object.hasOwn(xs,e)?xs[e]:null}var Es={"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 Ol(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Es,o)?Es[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 As={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Os={2:"Llama2",3:"Llama3"};function Il(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(As,s))return As[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Os,i))return Os[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Tl=["context_length","max_model_len"];function Pl(t){let e=Tl.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 Pn(t){let e=t.map(Pl),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Cl(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function zr(t){if(t.length===0)return null;let e=t.map(Cl),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Yr(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 Ll(t,e){let n=e.filter(s=>Ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return on(n);let r=e.filter(s=>Ce(s.model_id)===t);if(r.length>0)return on(r);let o=Yr(t,e);return o.length>0?on(o):null}function on(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Ml(t),matches:t}:null}function Ml(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 it=class extends Error{name="ModelCreatedError"};function Tt(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 it(`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 it(`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 it(`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]),u=Date.UTC(s,i-1,a),l=new Date(u);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==a)throw new it(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function mt(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 Cn(t,e,n){let r=Ll(t,e);if(!r)return mt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Pn(s),a=Tt(s),u=nn(o.model_id,o.variant,n),l=Ps(o,s),d=zr(s);return mt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...u!==null?{pricing:u}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var $l=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ps(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:[...$l],defect:o}:{published:[],defect:o}}function Xr(t){let e=t.length>0?on(t):null;return e===null?{published:[],defect:null}:Ps(e.row,e.matches)}function Is(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 Ts(t){return{input:[{type:"prompt",unit:"token",cost_usd:Is(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Is(t.output)}]}}function Nl(t,e,n,r){if(e.length===0)return null;let o=on(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||El[s.task]!==!0)return null;let a=Pn(i),u=nn(s.model_id,s.variant,n),l=Il(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:Tt(i),quantization:Al(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Ts(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Ts(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Cs(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?It(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.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:Ol(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=Nl(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&a.push(c)}return{data:a}}k();var Ls={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Pt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Ms(t){let e=t.t;if(typeof e!="string"||!(e in Ls))throw new Pt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ls).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 Ul(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Pt(`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 Pt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Ms(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Pt(`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 Ms(t)}function $s(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Dl(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 Ns(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 $s(e);let s=o.next();if(e!==void 0&&await Dl(s,e)==="aborted")throw s.catch(()=>{}),$s(e);let i=await s;if(i.done)return;yield Ul(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Z=class extends Error{},X=class extends Error{},Zr="urs1.";function Mn(t,e){return Zr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Un(t){if(!t.startsWith(Zr))return null;try{let e=JSON.parse(Buffer.from(t.slice(Zr.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 Fs(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 Us(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Hl(t);return e===null?[]:[e]}function Fl(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
+ `),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
+ `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function to(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||Ce(`${r.model_id}-${r.variant}`)===e.appSlug||Ce(r.model_id)===e.appSlug)),n?Fl(n.engine_args?.pool):null}function Qr(t,e,n,r,o){if(!o)throw new ce(`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 ce(`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 ce(`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 Ds(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 ce(`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 Bs="shared:",an="speech:";function ut(t){return t.sharedApp?Bs+t.appSlug:t.appSlug}function $n(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 eo(t,e){let n=e.filter(s=>Ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ce(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Bl(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Hl(t){let e=t.map(Bl),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var jl={stt:"stt",tts:"tts"};function at(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:jl[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Hs(t,e){let n=eo(t,e);return n.length>0?n:Yr(t,e)}function sn(t,e){return Hs(t.appSlug,e)}function ql(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 ce(`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 Ln=6e4,Nn=class{constructor(e){this.opts=e}opts;pool=new Map;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.pool.set(e,Promise.resolve(n))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Ln):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Ln):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Ln):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Ln;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 Me)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
+ `),rn}let r=ks(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}
6
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Kr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Bs)||o.startsWith(an)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new Z(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Vr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,a=Ce(s),u=n.endpoints.filter(c=>Ce(c.model_id)===a&&(i===void 0||c.variant===i)),l=new Set(u.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:Vr(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=Ce(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let u=a.filter(d=>d.startsWith(`${o}-`));if(u.length===1)return{appSlug:u[0]};if(u.length>1)throw new Z(`model "${n}" is ambiguous across deployed apps ${u.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new Z(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let a=(await this.opts.listCatalog()).find(u=>n===u.model_id||n===`${u.model_id}:${u.variant}`||o===Ce(u.model_id)||o===Ce(`${u.model_id}-${u.variant}`));if(a)throw new Z(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=$n(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return to(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return ut(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ut(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,an+ut(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:$n(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Mn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Mn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Un(e);if(!n)throw new X(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new X(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new X(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:rn;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
7
+ `);let u=(n?It(n):[]).map(l=>{let d=s.filter(b=>b.model_id===l.model_id&&b.variant===l.variant),c=Pn(d),p=Tt(d),y=zr(d),h=nn(l.model_id,l.variant,i),v=Xr(d);return mt({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},...v.published.length>0?{voices:[...v.published]}:{},...y!==null?{capabilities:{reasoning:y}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>Cn(l,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Cs(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=Qr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ds(`${r.modelId}:${r.variant}`,s).includes(n)}return Us(eo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:at(sn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":at(sn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":at(sn(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return ql(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return Xr(o)}async imageModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds()){let i=Us(eo(s,e));i.length!==0&&r.push(mt({...Cn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of It(o)){let i=Qr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ds(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=mt({id:`${s.model_id}:${s.variant}`,object:"model",created:Tt(i),owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds())at(Hs(s,e))==="stt"&&r.push(Cn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of It(o)){let i=Qr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(at(i)!=="stt")continue;let a=mt({id:`${s.model_id}:${s.variant}`,object:"model",created:Tt(i),owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};function js(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function Dn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Kl=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function qs(t){let e=t?.code;return typeof e=="string"&&Kl.has(e)}function ze(t,e){try{return t.write(e),!0}catch(n){if(qs(n))return!1;throw n}}function Gs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{qs(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
8
+ `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}k();var me=require("@prometheus-io/client"),mi=require("http");k();var zl={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Yl(t){return zl[t]??null}var Js=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Xl(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ql(t){return t==="surface"}function Zl(t){let e=t?.ledgerFailureReason;return Js.includes(e)?e:"unknown"}var ed=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Vs=["priced","unpriced"],td={written:Vs,already_written:Vs,skipped:ed,failed:Js},Ks=Object.entries(td).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function nd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function rd(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var od=256,Ws=4096,un=12e4,sd=250,id=8e3,tt=[],no=new Set,ln=0,Ct=!1;function zs(){return tt.length}function Ys(t=Date.now()){let e=tt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Fn=new Set;function Xs(){return ln===0&&tt.length===0}function Qs(){if(Xs()){Ct=!1;for(let t of[...Fn])t()}}async function Zs(t=ti){return Xs()?!0:await new Promise(e=>{let n=null,r=()=>{Fn.delete(r),n&&clearTimeout(n),e(!0)};Fn.add(r),n=setTimeout(()=>{Fn.delete(r),e(!1)},t),n.unref?.()})}function ei(){Ct=!0;let t=[...tt.splice(0,tt.length),...no];for(let e of t)e.settled||yt(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${ti}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Qs(),t.length}var ti=5e3;function ni(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
+ `}function ad(t){ze(process.stdout,t)}function ri(t,e){try{t(e)}catch{}}function oi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ad,o=Yl(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ri(r,ni("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:rd(e),completed_at:e.ts,billable_outcome:nd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(tt.length>=Ws){i("queue_full",`${tt.length} ledger writes are already waiting (capacity ${Ws}, ${ln} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}tt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),ln<od&&(ln+=1,ud())}async function ud(){try{for(;;){let t=ld();if(t===void 0)return;no.add(t);try{await dd(t)}finally{no.delete(t)}}}finally{ln-=1,Qs()}}function ld(){let t=Date.now();for(;;){let e=tt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<un)return e;yt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${un}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function dd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);yt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Xl(o);if(s!==null){yt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Zl(o),a=Date.now()-t.queuedAt;if(Ct){yt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Ql(i)&&a<un){if(await pd(cd(t.attempts)),Ct||Date.now()-t.queuedAt>=un){let u=Date.now()-t.queuedAt;yt(t,{outcome:"failed",reason:Ct?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ct?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${un}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}yt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function cd(t){return Math.min(id,sd*2**Math.max(0,t-1))}function pd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function yt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ri(t.report,ni(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}k();k();var Hn="/v1/usage/requests",si=1e4,fd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,lt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},fe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Bn=class extends fe{constructor(e){super(e),this.name="UsageWithholdingError"}},li=1024*1024;function so(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new lt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new lt(`"${e}" must be an array of uuid strings`);if(n.length>si)throw new lt(`"${e}" carries ${n.length} ids; at most ${si} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!fd.test(s))throw new lt(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function di(t){return so(t,"inference_ids")}var md=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Lt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is not a non-empty string (got ${$t(r)})`);return r}function ro(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is neither null nor a non-empty string (got ${$t(r)})`);return r}function Mt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new fe(`${n}: ${e} is not a number (got ${$t(o)})`);if(r&&!Number.isSafeInteger(s))throw new fe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new fe(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var gd=40,ii=64,ai=600;function ci(t){let e=Object.keys(t).sort(),r=e.slice(0,gd).map(o=>o.length>ii?`${o.slice(0,ii)}\u2026`:o).join(", ");return r.length>ai&&(r=`${r.slice(0,ai)}\u2026`),`${e.length} keys present: [${r}]`}function $t(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function oo(t){ze(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
+ `)}function hd(t,e){let n;try{n=t(e)}catch{ui(t,e);return}yd(n)&&Promise.resolve(n).catch(()=>{ui(t,e)})}function yd(t){return typeof t?.then=="function"}function ui(t,e){if(t!==oo)try{oo(e)}catch{}}function pi(t,e=oo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?ci(t):$t(t);throw new fe(`the usage surface answered without a "requests" array: got ${$t(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(wd(n[o],s))}catch(i){if(i instanceof Bn||!(i instanceof fe))throw i;hd(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new fe(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function wd(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new fe(`${e} is not an object: got ${$t(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Bn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of md)if(!Object.hasOwn(n,o))throw new fe(`${e} has no "${o}" column (${ci(n)})`);let r=Mt(n,"http_status",e,!0);if(r===null)throw new fe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Lt(n,"inference_id",e),model_id:Lt(n,"model_id",e),identity_kind:Lt(n,"identity_kind",e),variant:ro(n,"variant",e),task:Lt(n,"task",e),http_status:r,started_at:Lt(n,"started_at",e),completed_at:Lt(n,"completed_at",e),prompt_tokens:Mt(n,"prompt_tokens",e,!0),completion_tokens:Mt(n,"completion_tokens",e,!0),output_units:Mt(n,"output_units",e,!1),output_minutes:Mt(n,"output_minutes",e,!1),cost_nano_usd:Mt(n,"cost_nano_usd",e,!0),price_version:ro(n,"price_version",e),priced_at:ro(n,"priced_at",e)}}function jn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new fe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new fe(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var dn="/partners/huggingface/v1/billing/requests";function _d(t){return so(t,"requestIds")}function vd(t){return t>=200&&t<=399}function bd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&vd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function fi(t,e){let n=_d(t),r=await e(n);return jn(r,n),bd(r)}var io=9464,qn="/metrics",Gn="(other)",Sd="(none)",kd=64,Rd=128,xd=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",Hn,dn,gt],Ed=new Set(xd);function Ad(t){return Ed.has(t)?t:Gn}function Od(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Vn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Sd:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Gn):(this.admitted.add(e),e):Gn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Wn=class{registry=new me.Registry;modelLabel=new Vn(kd);orgLabel=new Vn(Rd);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new me.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new me.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new me.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new me.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new me.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new me.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new me.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Ks)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new me.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},zs()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Ys()/1e3)}}),this.labelCardinality=new me.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new me.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new me.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new me.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new me.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new me.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new me.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&(0,me.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Ad(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Gn:e.method,status_class:Od(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function gi(t){return(0,mi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==qn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${qn}
9
11
  `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
10
- `);return}n.end()})})}x();var kr=require("crypto"),Ii=require("http"),Rr=9465,ll="x-urun-key-id",dl="x-urun-key-fingerprint",cl="urun-ratelimit-bucket:",pl="urun-ratelimit-tier:",Oi="anonymous",fl=/^urun_sk_[A-Za-z0-9_-]{43}$/;function ml(t){return(0,kr.createHash)("sha256").update(`${cl}${t}`).digest("hex")}function hl(t){return(0,kr.createHash)("sha256").update(`${pl}${t}`).digest("hex")}function gl(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return fl.test(n)?n:null}function Ai(){return(0,Ii.createServer)((t,e)=>{let n=gl(t.headers.authorization);e.setHeader(ll,n===null?Oi:ml(n)),e.setHeader(dl,n===null?Oi:hl(n)),e.writeHead(200),e.end()})}x();var yl=8080,xr="serve",nt="0.0.0.0";function _l(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Ti(t=process.env){let e=(t.PORT??"").trim(),n=e===""?yl:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=Zo(ln(_l(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?ln(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=s?{catalogUrl:ln(s,"URUN_CATALOG_URL"),anonKey:a}:null,l=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");return{port:n,baseUrl:r,apiUrl:i,catalog:u,ledgerSigning:l?{keyId:d,key:l}:void 0}}x();var Pa=require("http");x();x();var Mi="audio",Er=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let i=0;i<r;i++)o[i]=n.readInt16LE(i*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function Li(t,e,n=1e4){let r=new Er(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Mi).attach(o);let i=await wl(t,n);return await r.startInbound(i),r}function wl(t,e){let n=t.stream(Mi);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let i,s=setTimeout(()=>{i?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(s),i?.(),r(u))};i=n.on?.("track",a),n.track!=null&&a(n.track)})}var Pi="rt-video-in",Ci=256e3;function $i(t){let e=t.stream(Pi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Pi}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>Ci)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Ci}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var vl=24e3,Ft=480,bl=111;async function Sl(){let t=await import("opusscript"),e=t.default??t;return new e(vl,1,2048)}async function Ni(){let t=await import("werift"),e=await Sl();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(s.length+a.length);u.set(s,0),u.set(a,s.length);let l=0;for(;u.length-l>=Ft;){let d=u.subarray(l,l+Ft);l+=Ft;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),y=e.encode(c,Ft);o=o+1&65535,i=i+Ft>>>0;let f=new t.RtpHeader({version:2,payloadType:bl,sequenceNumber:o,timestamp:i,ssrc:r,marker:!1}),p=new t.RtpPacket(f,y);n.writeRtp(p)}s=u.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(i=>{let s;try{s=e.decode(i.payload)}catch{return}let a=new Int16Array(s.length/2);for(let u=0;u<a.length;u++)a[u]=s.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}x();var _n=require("@urun-sh/core"),Or="rt-video-out";var kl="h264";function Rl(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function xl(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Rl(o,"decodeVideoOutRecord");let i=t.subarray(2+e);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:i.slice()}}var Ui="urun.videoOut.v2-ws";function Di(t){let e=t.stream(Or);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Or}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,i=u=>{for(let l of r)l(u)},s=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${Or}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=xl(u)}catch(d){i(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let u of o)u()};return{codec:kl,onOutputFrame:u=>(n.add(u),s||(s=!0,a().catch(l=>i(l instanceof Error?l:new Error(String(l))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var Sn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",El=1007,Bi=1008,Ge=1011,kn=1008,T=class extends Error{constructor(n,r=El){super(n);this.closeCode=r}closeCode},ue=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,wn=["setup","clientContent","realtimeInput","toolResponse"];function ji(t){let e;try{e=JSON.parse(t)}catch{throw new T("client message is not valid JSON")}let n=ue(e);if(!n)throw new T("client message must be a JSON object");let r=wn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!wn.includes(a));if(o.length>0)throw new T(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${wn.join(", ")}`);if(r.length!==1)throw new T(`client message must contain exactly one of ${wn.join(", ")} (got ${r.length})`);let i=r[0],s=ue(n[i]);if(!s)throw new T(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function qi(t,e){if(typeof t=="string")return t;let n=ue(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new T(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=ue(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new T(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new T(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new T(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
11
- `)}var Ol={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},rt="urun.videoOut";function Hi(t){return{framing:Ui,codec:t}}function Gi(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[rt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Il={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Al=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",rt],Fi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Tl(t){let e=ue(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ue(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new T("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Fi.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Fi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Pl=["temperature","maxOutputTokens","responseModalities"];function Vi(t){for(let[c,y]of Object.entries(Il))if(t[c]!==void 0)throw new T(y);for(let c of Object.keys(t))if(!Al.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=ue(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new T("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!Pl.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new T("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new T("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let y of c){let f=String(y).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new T(`responseModalities ${JSON.stringify(y)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:qi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");a=[];for(let c of t.tools){let y=ue(c);if(!y)throw new T("setup.tools entries must be objects");for(let f of Object.keys(y))if(f!=="functionDeclarations")throw new T(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(y.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let f of y.functionDeclarations){let p=ue(f);if(!p||typeof p.name!="string")throw new T("functionDeclarations entries require a string name");a.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ue(t.sessionResumption);if(!c)throw new T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let y of Object.keys(c))if(y!=="handle")throw new T(`unsupported sessionResumption field "${y}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new T("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Ol:Tl(t.realtimeInputConfig),d=!1;if(t[rt]!==void 0){if(!ue(t[rt]))throw new T(`setup["${rt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function Wi(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ji(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ki(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=ue(r);if(!o)throw new T("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:qi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var vn=16e3,zi=24e3,Cl=`audio/pcm;rate=${zi}`,Yi=Buffer.alloc(960).toString("base64");function Ml(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Ll(t){let e=ue(t);if(!e)throw new T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new T("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function $l(t){let e=ue(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==vn)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${vn} Hz (audio/pcm;rate=${vn})`);if(typeof e.data!="string"||e.data.length===0)throw new T("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new T(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=Ml(o,vn,zi);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Xi(t){if(t.mediaChunks!==void 0)throw new T('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new T("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=ue(t[o]);if(!i||Object.keys(i).length!==0)throw new T(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:$l(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Ll(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Qi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ue(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new T("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Zi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function es(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Cl,data:t}}]}}}}function ts(t){let e=ue(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let d=ue(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let y=ue(c);y?.type==="output_text"&&typeof y.text=="string"&&(i+=y.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let d=ue(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new T(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Ge);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",y;try{y=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Ge)}r.push({id:d.call_id,name:d.name,args:y}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=ue(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}x();var ns=require("crypto"),rs=require("ws");var Nl=256,Ir=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Nl;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ul="local",Bt=t=>t.slice(0,120),Ar=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof Y){this.ws.close(Bi,Bt(e.message));return}if(e instanceof re){this.ws.close(kn,Bt(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,Bt(e.message));return}this.ws.close(Ge,Bt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=ji(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new T(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Ki(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Xi(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Yi);return}this.transcript.push(...Qi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=Vi(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new T("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",kn);if(i.model!==n.model)throw new T(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new T("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new T(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,kn);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(Gi(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[rt]=Hi(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ge);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(es(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ge);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new T(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new T("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new T("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,ns.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wi(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Ji(e.timeLeftMs)),this.ws.close(Ge,Bt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new T(`upstream error: ${JSON.stringify(l)}`,Ge);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=Zi(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new T("upstream produced no response.completed event",Ge);let{messages:s,assistantItems:a}=ts(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ot=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Dl(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new ot(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new ot(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new ot(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Tr(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new rs.WebSocketServer({noServer:!0}),o=new Ir;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===Sn&&(a.on("error",()=>{}),(async()=>{let d=Dl(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new ot(401,"invalid local proxy api key");c={clients:e.clients,scope:Ul}}r.handleUpgrade(s,a,u,y=>{new Ar(y,c,o)})})().catch(d=>{let c=502;(d instanceof ot||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let y=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${y}\r
12
+ `);return}n.end()})})}k();var ao=require("crypto"),yi=require("http"),uo=9465,Id="x-urun-key-id",Td="x-urun-key-fingerprint",Pd="urun-ratelimit-bucket:",Cd="urun-ratelimit-tier:",hi="anonymous",Ld=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Md(t){return(0,ao.createHash)("sha256").update(`${Pd}${t}`).digest("hex")}function $d(t){return(0,ao.createHash)("sha256").update(`${Cd}${t}`).digest("hex")}function Nd(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Ld.test(n)?n:null}function wi(){return(0,yi.createServer)((t,e)=>{let n=Nd(t.headers.authorization);e.setHeader(Id,n===null?hi:Md(n)),e.setHeader(Td,n===null?hi:$d(n)),e.writeHead(200),e.end()})}k();var Ud=8080,lo="serve",wt="0.0.0.0";function Dd(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function _i(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Ud:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=js(Dn(Dd(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?Dn(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=i?{catalogUrl:Dn(i,"URUN_CATALOG_URL"),anonKey:a}:null,l=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=l?{keyId:d,key:l}:void 0,p={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},y=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],h=y.filter((w,g)=>Object.values(p)[g]==="");if(h.length!==0&&h.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the lane plane`);let v=h.length===0?p:void 0,I={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},b=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=b.filter((w,g)=>Object.values(I)[g]==="");if(f.length!==0&&f.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let m=f.length===0?I:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:v,pooler:m}}k();var zu=require("http");k();k();var Si="audio",co=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function ki(t,e,n=1e4){let r=new co(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Si).attach(o);let s=await Fd(t,n);return await r.startInbound(s),r}function Fd(t,e){let n=t.stream(Si);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var vi="rt-video-in",bi=256e3;function Ri(t){let e=t.stream(vi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${vi}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>bi)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${bi}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Bd=24e3,cn=480,Hd=111;async function jd(){let t=await import("opusscript"),e=t.default??t;return new e(Bd,1,2048)}async function xi(){let t=await import("werift"),e=await jd();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let l=0;for(;u.length-l>=cn;){let d=u.subarray(l,l+cn);l+=cn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,cn);o=o+1&65535,s=s+cn>>>0;let y=new t.RtpHeader({version:2,payloadType:Hd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(y,p);n.writeRtp(h)}i=u.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}k();var Jn=require("@urun-sh/core"),po="rt-video-out";var qd="h264";function Gd(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function Vd(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Gd(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Ei="urun.videoOut.v2-ws";function Ai(t){let e=t.stream(po);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${po}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=u=>{for(let l of r)l(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${po}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Vd(u)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let u of o)u()};return{codec:qd,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var Xn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Wd=1007,Ii=1008,nt=1011,Qn=1008,$=class extends Error{constructor(n,r=Wd){super(n);this.closeCode=r}closeCode},ye=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Kn=["setup","clientContent","realtimeInput","toolResponse"];function Ti(t){let e;try{e=JSON.parse(t)}catch{throw new $("client message is not valid JSON")}let n=ye(e);if(!n)throw new $("client message must be a JSON object");let r=Kn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Kn.includes(a));if(o.length>0)throw new $(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Kn.join(", ")}`);if(r.length!==1)throw new $(`client message must contain exactly one of ${Kn.join(", ")} (got ${r.length})`);let s=r[0],i=ye(n[s]);if(!i)throw new $(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Pi(t,e){if(typeof t=="string")return t;let n=ye(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new $(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ye(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new $(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new $(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new $(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
+ `)}var Jd={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},_t="urun.videoOut";function Ci(t){return{framing:Ei,codec:t}}function Li(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[_t]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Kd={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},zd=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",_t],Oi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Yd(t){let e=ye(t);if(!e)throw new $("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new $(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ye(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new $("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new $(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new $("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Oi.includes(e.activityHandling))throw new $(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Oi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Xd=["temperature","maxOutputTokens","responseModalities"];function Mi(t){for(let[c,p]of Object.entries(Kd))if(t[c]!==void 0)throw new $(p);for(let c of Object.keys(t))if(!zd.includes(c))throw new $(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new $('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ye(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new $("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Xd.includes(c))throw new $(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new $("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new $("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let y=String(p).toUpperCase();if(y==="AUDIO"){o=!0;continue}if(y!=="TEXT")throw new $(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Pi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new $("setup.tools must be an array");a=[];for(let c of t.tools){let p=ye(c);if(!p)throw new $("setup.tools entries must be objects");for(let y of Object.keys(p))if(y!=="functionDeclarations")throw new $(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new $("tool.functionDeclarations must be an array");for(let y of p.functionDeclarations){let h=ye(y);if(!h||typeof h.name!="string")throw new $("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ye(t.sessionResumption);if(!c)throw new $("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new $(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new $("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Jd:Yd(t.realtimeInputConfig),d=!1;if(t[_t]!==void 0){if(!ye(t[_t]))throw new $(`setup["${_t}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function $i(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ni(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ui(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new $(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new $("clientContent.turns must be an array");let n=[];for(let r of e){let o=ye(r);if(!o)throw new $("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new $(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Pi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var zn=16e3,Di=24e3,Qd=`audio/pcm;rate=${Di}`,Fi=Buffer.alloc(960).toString("base64");function Zd(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,l=Math.floor(u);if(l>=i){o[a]=t[i];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function ec(t){let e=ye(t);if(!e)throw new $("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new $(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new $("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new $("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function tc(t){let e=ye(t);if(!e)throw new $("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new $(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==zn)throw new $(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${zn} Hz (audio/pcm;rate=${zn})`);if(typeof e.data!="string"||e.data.length===0)throw new $("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new $(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Zd(o,zn,Di);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Bi(t){if(t.mediaChunks!==void 0)throw new $('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new $("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ye(t[o]);if(!s||Object.keys(s).length!==0)throw new $(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new $(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new $(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:tc(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:ec(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new $("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new $("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Hi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new $(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new $("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ye(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new $("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function ji(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function qi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Qd,data:t}}]}}}}function Gi(t){let e=ye(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=ye(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=ye(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=ye(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new $(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,nt);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new $(`upstream function_call arguments are not valid JSON: ${c}`,nt)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ye(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return i.push(u),{messages:i,assistantItems:o}}k();var Vi=require("crypto"),Wi=require("ws");var nc=256,fo=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>nc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},rc="local",pn=t=>t.slice(0,120),mo=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof Z){this.ws.close(Ii,pn(e.message));return}if(e instanceof X){this.ws.close(Qn,pn(e.message));return}if(e instanceof $){this.ws.close(e.closeCode,pn(e.message));return}this.ws.close(nt,pn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Ti(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new $(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Ui(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Bi(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Fi);return}this.transcript.push(...Hi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new $("setup may only be sent once, as the first client message");let n=Mi(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new $("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Qn);if(s.model!==n.model)throw new $(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new $("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new $(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Qn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(l=>this.send(Li(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[_t]=Ci(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new $("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new $("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",nt);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(qi(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new $("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new $("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",nt);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new $(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new $("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new $("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Vi.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send($i(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Ni(e.timeLeftMs)),this.ws.close(nt,pn(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new $(`upstream error: ${JSON.stringify(l)}`,nt);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=ji(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new $("upstream produced no response.completed event",nt);let{messages:i,assistantItems:a}=Gi(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},vt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function oc(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new vt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new vt(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new vt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function go(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Wi.WebSocketServer({noServer:!0}),o=new fo;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=oc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new vt(401,"invalid local proxy api key");c={clients:e.clients,scope:rc}}r.handleUpgrade(i,a,u,p=>{new mo(p,c,o)})})().catch(d=>{let c=502;(d instanceof vt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",y=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
12
14
  Connection: close\r
13
15
  \r
14
- ${f}\r
15
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}x();var Qe=require("ws");x();x();var os=require("crypto"),is="Inference-Id";function jt(){return(0,os.randomUUID)()}function Pr(t){return t==="/v1"||t.startsWith("/v1/")}function ss(t,e){if(!Pr(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function qt(t){return`resp_${t}`}function as(t){return`chatcmpl-${t}`}function us(t){return`msg_${t}`}function Ee(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ls(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function ds(t){return`${JSON.stringify(t)}
16
- `}var Fl=256,Bl=128;function Se(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Bl)}var it=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Fl?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},jl=256;function ql(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var st=class extends Error{},bt=class{conversations=new Map;thread(e,n){let r=ql(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new st(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=jl)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},cs=new WeakMap;function Ht(t){let e=cs.get(t);return e||(e=new bt,cs.set(t,e)),e}function St(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function kt(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Xe=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Hl=["<tool_call>","<function="];function Gl(t){return Hl.find(e=>t.includes(e))}function at(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function ut(t,e,n){if(!(!t||e>0))return Gl(n)}function Rt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ve(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Vl(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Cr(t,e){let n=Vl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Oe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function xt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof st?new Oe(n.message,"previous_response_not_found",400,"previous_response_id"):new Oe(String(n instanceof Error?n.message:n),"invalid_input")}}function ps(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Mr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Oe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ps(e)!==void 0?{response_format:ps(e)}:{}},o)}async function Gt(t){let{body:e,clients:n,store:r,stats:o}=t,i=xt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Se(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,y=await Mr(n,e,i,!0,c?Ee(c):void 0);return{responseId:s,events:zl({events:y,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Wl(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?Kl(o[s++],u):u),...Jl(r,n)]}function Jl(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function Kl(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*zl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=G=>G.response&&typeof G.response=="object"?{...G,response:{...G.response,id:r}}:G,y=`item_${r.slice(5)}`,f=!1,p=!1,w=0;function*_(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],k=(G,I)=>{b.push({output_index:G,item:I})},h=!1,A=0,R="",v=0,O="";function*j(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:R,output_index:A,content_index:0,text:O};let G={id:R,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:O}],status:"completed"};yield{type:"response.output_item.done",output_index:A,item:G},k(A,G),O=""}let C=!1,D=0,H="",z=0,ie="",he="";function*ve(G){if(!C)return;C=!1,yield{type:"response.output_text.done",item_id:H,output_index:D,content_index:0,text:ie},yield{type:"response.content_part.done",item_id:H,output_index:D,content_index:0,part:{type:"output_text",text:ie}};let I={id:H,type:"message",role:"assistant",status:G,content:[{type:"output_text",text:ie}]};yield{type:"response.output_item.done",output_index:D,item:I},k(D,I),ie=""}let Te=new Xe,ee=null,te=-1;function*de(G){if(!ee)return;let I=ee;ee=null,yield{type:"response.function_call_arguments.done",item_id:I.fcId,output_index:I.outputIndex,arguments:I.args};let X={id:I.fcId,type:"function_call",call_id:I.callId??I.fcId,name:I.name??"",arguments:I.args,status:G};yield{type:"response.output_item.done",output_index:I.outputIndex,item:X},k(I.outputIndex,X)}let Le=!1;for await(let G of l.track(e,o,t.turn)){d.push(G);let I=String(G.type??"");if(I==="response.created"||I==="response.in_progress"){f=!0,yield c(G);continue}if(I==="response.output_item.added"){p=!0,yield c(G);continue}if(I==="response.reasoning_text.delta"&&!p){yield*_(),h||(h=!0,A=w++,v+=1,R=v===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${v}`,yield{type:"response.output_item.added",output_index:A,item:{id:R,type:"reasoning",summary:[],content:[],status:"in_progress"}}),O+=String(G.delta??""),yield{type:"response.reasoning_text.delta",item_id:R,output_index:A,content_index:0,delta:G.delta};continue}if(I==="response.output_text.delta"&&!p){yield*_(),yield*j(),C||(C=!0,D=w++,z+=1,H=z===1?y:`${y}_${z}`,yield{type:"response.output_item.added",output_index:D,item:{id:H,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:H,output_index:D,content_index:0,part:{type:"output_text",text:""}}),ie+=String(G.delta??""),he+=String(G.delta??""),yield{type:I,item_id:H,output_index:D,content_index:0,delta:G.delta};continue}let X=p?null:kt(G);if(X){if(yield*_(),yield*j(),yield*ve("completed"),Te.add(X),X.tool_index!==te){yield*de("completed"),te=X.tool_index;let Pe=w++;ee={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:Pe,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:Pe,item:{id:ee.fcId,type:"function_call",call_id:ee.callId??ee.fcId,name:ee.name??"",arguments:"",status:"in_progress"}}}ee&&(X.call_id&&(ee.callId=X.call_id),X.name&&(ee.name=X.name),ee.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:ee.fcId,output_index:ee.outputIndex,delta:X.delta});continue}if(I==="response.completed"&&!p){let Pe=St(G.response),q=ut(i,Te.size+Pe.length,he);if(q){Le=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:at(o,q)}};break}if(yield*j(),yield*ve("completed"),yield*de("completed"),Te.size===0)for(let $e of Pe){let Be=w++,ft=$e.id??$e.call_id??`fc_${Be}`,be=$e.arguments??"",Pt={id:ft,type:"function_call",call_id:$e.call_id??ft,name:$e.name??""};yield{type:"response.output_item.added",output_index:Be,item:{...Pt,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ft,output_index:Be,delta:be},yield{type:"response.function_call_arguments.done",item_id:ft,output_index:Be,arguments:be};let je={...Pt,arguments:be,status:"completed"};yield{type:"response.output_item.done",output_index:Be,item:je},k(Be,je)}let me=Wl(b,G.response);yield me.length>0?c({...G,response:{...G.response,output:me}}):c(G);continue}yield c(G)}if(yield*j(),yield*ve("incomplete"),yield*de("incomplete"),s&&!Le){let G=Ue(d);u.remember(r,n,Cr(G,Rt(d,G)),a)}}var Nr="/v1/responses",Yl=64*1024*1024,Xl=8*1024*1024,Ql=16,fs=32,ms=3600*1e3,Zl=/^[A-Za-z0-9._-]{1,256}$/;function ke(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var ed=ke(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Ur(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function td(t){for(;t.bufferedAmount>Xl&&t.readyState===Qe.WebSocket.OPEN;){let{promise:e,resolve:n}=Ur();setTimeout(n,5),await e}}var Lr=class extends bt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof st))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},$r=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Lr(Ht(n)),e.on("message",(s,a)=>this.onMessage(s,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ms/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ms).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ke(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ke(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Zl.test(o.stream_id)){this.sendFrame(ed);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=fs){this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${fs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Gt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:qt(jt())})}catch(s){this.failTurn(s,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let i=o.events;this.activeTurns.add(i);try{for await(let s of i){if(this.closed||this.ws.readyState!==Qe.WebSocket.OPEN)break;this.send(s,n),await td(this.ws)}}finally{this.activeTurns.delete(i)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=qt(jt());try{let o=xt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof Oe)return ke(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof Y)return ke(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof re)return ke(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ke(o.status,{type:o.openaiType,message:r},n):ke(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Ql;){let{promise:e,resolve:n}=Ur();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Qe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Qe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Rn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
16
+ ${y}\r
17
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}k();var pt=require("ws");k();k();var Ji=require("crypto"),Ki="Inference-Id";function fn(){return(0,Ji.randomUUID)()}function ho(t){return t==="/v1"||t.startsWith("/v1/")}function zi(t,e){if(!ho(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function mn(t){return`resp_${t}`}function Yi(t){return`chatcmpl-${t}`}function Xi(t){return`msg_${t}`}function $e(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Qi(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Zi(t){return`${JSON.stringify(t)}
18
+ `}var sc=256,ic=128;function Ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ic)}var bt=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=sc?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},ac=256;function uc(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var St=class extends Error{},Nt=class{conversations=new Map;thread(e,n){let r=uc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new St(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=ac)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},ea=new WeakMap;function gn(t){let e=ea.get(t);return e||(e=new Nt,ea.set(t,e)),e}function Ut(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ye(t){return t.find(e=>e.type==="response.completed")?.response??null}function Dt(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var dt=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},lc=["<tool_call>","<function="];function dc(t){return lc.find(e=>t.includes(e))}function kt(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Rt(t,e,n){if(!(!t||e>0))return dc(n)}function Ft(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function rt(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function cc(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function yo(t,e){let n=cc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Ne=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Bt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof St?new Ne(n.message,"previous_response_not_found",400,"previous_response_id"):new Ne(String(n instanceof Error?n.message:n),"invalid_input")}}function ta(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function wo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Ne("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ta(e)!==void 0?{response_format:ta(e)}:{}},o)}async function hn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Bt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await wo(n,e,s,!0,c?$e(c):void 0);return{responseId:i,events:gc({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function pc(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?mc(o[i++],u):u),...fc(r,n)]}function fc(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function mc(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*gc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=V=>V.response&&typeof V.response=="object"?{...V,response:{...V.response,id:r}}:V,p=`item_${r.slice(5)}`,y=!1,h=!1,v=0;function*I(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],f=(V,M)=>{b.push({output_index:V,item:M})},m=!1,w=0,g="",x=0,R="";function*A(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:g,output_index:w,content_index:0,text:R};let V={id:g,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"};yield{type:"response.output_item.done",output_index:w,item:V},f(w,V),R=""}let T=!1,O=0,C="",P=0,H="",W="";function*K(V){if(!T)return;T=!1,yield{type:"response.output_text.done",item_id:C,output_index:O,content_index:0,text:H},yield{type:"response.content_part.done",item_id:C,output_index:O,content_index:0,part:{type:"output_text",text:H}};let M={id:C,type:"message",role:"assistant",status:V,content:[{type:"output_text",text:H}]};yield{type:"response.output_item.done",output_index:O,item:M},f(O,M),H=""}let oe=new dt,te=null,Be=-1;function*se(V){if(!te)return;let M=te;te=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let ee={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:V};yield{type:"response.output_item.done",output_index:M.outputIndex,item:ee},f(M.outputIndex,ee)}let ve=!1;for await(let V of l.track(e,o,t.turn)){d.push(V);let M=String(V.type??"");if(M==="response.created"||M==="response.in_progress"){y=!0,yield c(V);continue}if(M==="response.output_item.added"){h=!0,yield c(V);continue}if(M==="response.reasoning_text.delta"&&!h){yield*I(),m||(m=!0,w=v++,x+=1,g=x===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${x}`,yield{type:"response.output_item.added",output_index:w,item:{id:g,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String(V.delta??""),yield{type:"response.reasoning_text.delta",item_id:g,output_index:w,content_index:0,delta:V.delta};continue}if(M==="response.output_text.delta"&&!h){yield*I(),yield*A(),T||(T=!0,O=v++,P+=1,C=P===1?p:`${p}_${P}`,yield{type:"response.output_item.added",output_index:O,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:O,content_index:0,part:{type:"output_text",text:""}}),H+=String(V.delta??""),W+=String(V.delta??""),yield{type:M,item_id:C,output_index:O,content_index:0,delta:V.delta};continue}let ee=h?null:Dt(V);if(ee){if(yield*I(),yield*A(),yield*K("completed"),oe.add(ee),ee.tool_index!==Be){yield*se("completed"),Be=ee.tool_index;let Qe=v++;te={fcId:`fc_${r.slice(5)}_${ee.tool_index}`,outputIndex:Qe,callId:ee.call_id,name:ee.name,args:""},yield{type:"response.output_item.added",output_index:Qe,item:{id:te.fcId,type:"function_call",call_id:te.callId??te.fcId,name:te.name??"",arguments:"",status:"in_progress"}}}te&&(ee.call_id&&(te.callId=ee.call_id),ee.name&&(te.name=ee.name),te.args+=ee.delta,yield{type:"response.function_call_arguments.delta",item_id:te.fcId,output_index:te.outputIndex,delta:ee.delta});continue}if(M==="response.completed"&&!h){let Qe=Ut(V.response),ne=Rt(s,oe.size+Qe.length,W);if(ne){ve=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:kt(o,ne)}};break}if(yield*A(),yield*K("completed"),yield*se("completed"),oe.size===0)for(let ue of Qe){let Ae=v++,Ze=ue.id??ue.call_id??`fc_${Ae}`,Oe=ue.arguments??"",en={id:Ze,type:"function_call",call_id:ue.call_id??Ze,name:ue.name??""};yield{type:"response.output_item.added",output_index:Ae,item:{...en,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ze,output_index:Ae,delta:Oe},yield{type:"response.function_call_arguments.done",item_id:Ze,output_index:Ae,arguments:Oe};let et={...en,arguments:Oe,status:"completed"};yield{type:"response.output_item.done",output_index:Ae,item:et},f(Ae,et)}let re=pc(b,V.response);yield re.length>0?c({...V,response:{...V.response,output:re}}):c(V);continue}yield c(V)}if(yield*A(),yield*K("incomplete"),yield*se("incomplete"),i&&!ve){let V=Ye(d);u.remember(r,n,yo(V,Ft(d,V)),a)}}k();k();var Ue=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},be=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};k();var ct=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},yn=class extends ct{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},_o=class extends ct{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},je=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Zn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new yn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+n-Date.now();if(u<=0)throw new _o(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};k();var vo=require("@urun-sh/core"),qe=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},bo=33e4;function na(t,e=bo){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new er),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof X||l instanceof vo.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof er?(await r.return?.(void 0),new qe("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new qe("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new qe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var er=class extends Error{constructor(){super("stream idle timeout")}};function ra(t){return t instanceof qe?!1:t instanceof X?!0:t instanceof vo.SessionFailedError?t.kind==="transport-failed":!1}var hc=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function Ve(t){return!hc.some(e=>e.test(t))}function We(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function Le(t,e){if(t instanceof X)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=oa(t);return n||{message:We(e?.inferenceId??null),redacted:!0}}function oa(t){return t instanceof it?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ce?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof Z?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof ct?{message:t.message,redacted:!1}:t instanceof qe?Ve(t.message)?{message:t.message,redacted:!1}:null:t instanceof je?{message:t.message,redacted:!1}:t instanceof be?{message:t.message,redacted:!1}:null}function Ht(t,e,n){let r=n??(i=>console.error(i)),o=oa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ve(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed while serving this request`)}function Xe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ve(e)?e:null}function Ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Ro="/v1/responses",yc=64*1024*1024,wc=8*1024*1024,_c=16,sa=32,ia=3600*1e3,vc=/^[A-Za-z0-9._-]{1,256}$/;function Ee(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var bc=Ee(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function xo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Sc(t){for(;t.bufferedAmount>wc&&t.readyState===pt.WebSocket.OPEN;){let{promise:e,resolve:n}=xo();setTimeout(n,5),await e}}var So=class extends Nt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof St))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},ko=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new So(gn(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Ee(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ia/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ia).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(Ee(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!vc.test(o.stream_id)){this.sendFrame(bc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=sa){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${sa}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=fn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await hn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==pt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Sc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=fn(),o=mn(r);try{let s=Bt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ge(e);if(e instanceof Ne)return Ee(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof Z)return Ee(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=Le(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Ee(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),Ee(s.status,{type:s.openaiType,message:o},n);let i=Le(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Ee(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Xe(o),a=i??We(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),Ee(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=_c;){let{promise:e,resolve:n}=xo();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==pt.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==pt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function tr(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
17
19
  `;t.end(`HTTP/1.1 ${e} ${r}\r
18
20
  Connection: close\r
19
21
  Content-Type: text/plain; charset=utf-8\r
20
22
  Content-Length: ${Buffer.byteLength(o)}\r
21
23
  \r
22
- ${o}`)}function Dr(t,e){let n=new Qe.WebSocketServer({noServer:!0,maxPayload:Yl}),r=new it,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,y)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Rn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),f.pathname!==Nr){s.add(c);return}i.add(c);let p=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Rn(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(_){let b=e.statusOf?.(_)??null;Rn(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(d,c,y,_=>{i.delete(c),o.add(_),_.on("close",()=>o.delete(_));try{new $r(_,w,r,e.statusOf)}catch{o.delete(_),_.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Rn(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Ur();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let y=setTimeout(()=>{for(let f of o)f.readyState!==Qe.WebSocket.CLOSED&&f.terminate()},2e3);return y.unref?.(),n.close(()=>{clearTimeout(y),c()}),d}}}x();x();var bs=require("@urun-sh/core");x();var hs=require("@urun-sh/core"),nd={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},rd={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",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 Fr(t,e){let n=rd[t.code];return e?`${n} (${e})`:n}function xn(t){if(t==null)return null;let e=nd[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 En(t){if(t.kind==="create-failed")return xn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=hs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return xn(e?"cold_start_exceeded":"queue_timeout")}var Ss=require("ws");x();var vs=require("@urun-sh/core");x();var ys=require("crypto");function N(t){return`${t}_${(0,ys.randomUUID)().replace(/-/g,"").slice(0,24)}`}var On=4*1024*1024,Br=8*1024*1024,In=512,An=20*1024*1024;function le(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Et(t,e){return{type:"server_error",code:t,message:e}}function Z(t){return{type:"error",event_id:N("event"),error:t}}function jr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var B=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},od={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},id={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},sd={format:!0,voice:!0,speed:!0};function gs(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new B(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Vt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new B("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(s=>!(s in od));if(o.length>0)throw new B(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[s,a]of Object.entries(r))switch(s){case"type":{if(a!=="realtime"&&a!=="transcription")throw new B(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new B(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new B('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new B("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new B("instructions must be a string or null","instructions");i.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new B("modalities must be a non-empty array","modalities");let u=[];for(let l of a){if(l!=="text"&&l!=="audio")throw new B(`modality ${JSON.stringify(l)} is not "text" or "audio"`,"modalities");if(l==="audio"&&!n.voice)throw new B('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(l)||u.push(l)}i.outputModalities=u;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new B("voice must be a string or null","voice");if(!n.voice)throw new B("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new B(`${s} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,s);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new B("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new B(`${s} must be a positive integer, "inf" or null`,s);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new B("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new B("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new B("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("turn_detection must be an object or null","turn_detection");let l=String(u.type??"");if(l!=="server_vad"&&l!=="semantic_vad")throw new B(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new B("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new B("input_audio_transcription must be an object or null","input_audio_transcription");for(let l of Object.keys(a))if(!["model","language","languages","prompt"].includes(l))throw new B(`input_audio_transcription field not honored by this backend: ${l} (transcription comes from the voice engine itself)`,`input_audio_transcription.${l}`,"unsupported_field");let u=a.model;if(u!=null){let l=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new B(`input_audio_transcription.model ${JSON.stringify(l)} 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(a!==null)throw new B("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let l=u.input;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.input must be an object","audio.input");for(let d of Object.keys(l))if(!(d in id))throw new B(`audio.input field not supported by this backend: ${d}`,`audio.input.${d}`,"unsupported_field");if(l.format!==void 0&&gs(l.format,"audio.input.format"),l.transcription!==null&&l.transcription!==void 0){let d=Vt({input_audio_transcription:l.transcription},i,n);i.inputAudioTranscription=d.inputAudioTranscription}if(l.turn_detection!==null&&l.turn_detection!==void 0){let d=Vt({turn_detection:l.turn_detection},i,n);i.turnDetection=d.turnDetection}if(l.noise_reduction!==null&&l.noise_reduction!==void 0)throw new B("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let l=u.output;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.output must be an object","audio.output");for(let d of Object.keys(l))if(!(d in sd))throw new B(`audio.output field not supported by this backend: ${d}`,`audio.output.${d}`,"unsupported_field");if(l.format!==void 0&&gs(l.format,"audio.output.format"),l.speed!==void 0)throw new B("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(l.voice!==void 0)if(l.voice===null)delete i.voice;else{if(typeof l.voice!="string")throw new B("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new B("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=l.voice}l.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Tn(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 qr(t,e){let n=t;if(!n||typeof n!="object")throw new B("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new B("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:N("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new B('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new B("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new B("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new B(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new B("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new B("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new B(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:N("item"),type:"message",role:r,content:o}}throw new B(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Hr(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 i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var ad=1001,ud=1011,_s=t=>t.slice(0,120),ld=/^[A-Za-z0-9+/=]*$/,dd=2;function cd(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>dd)return!1;return!0}var Wt=class{id=N("conn");ws;binding;onClosed;config=jr();sessionId=N("sess");conversationId=N("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:N("event"),session:Tn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:N("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(Z(Et("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:N("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:N("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("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:N("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("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 s=N("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:N("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:s,content_index:0,transcript:i}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(le("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>On){this.fail(le("frame_too_large",`frame exceeds the ${On}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(le("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(le("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(Z({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Et(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Vt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:N("event"),session:Tn(this.config,this.sessionId)});return;case"conversation.item.create":{let n=qr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(Z(le("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:N("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(Z(le("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:N("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(Z(le("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:N("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(Z(le("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ld.test(e.audio)){this.send(Z(le("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>An){this.send(Z(le("buffer_full",`uncommitted input audio exceeds the ${An}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:N("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(Z(le("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=N("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:N("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:i}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(Z(le("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(Z(le("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(Z(le("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Z(le("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(Z({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(Z(le("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(w=>w!=="text"&&w!=="audio")){this.send(Z(le("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(Z(le("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=N("req"),o=`resp_${r}`;this.activeResponseId=o;let i=this.items.length,{input:s,sawAudioOnlyItem:a}=Hr(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,l=typeof n.temperature=="number"?n.temperature:this.config.temperature,d=n.max_output_tokens??this.config.maxOutputTokens,c=d==="inf"||d===void 0?void 0:d,y=n.tools!==void 0?n.tools:this.config.tools,f=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:s,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...l!==void 0?{temperature:l}:{},...c!==void 0?{max_output_tokens:c}:{},...y!==void 0?{tools:y}:{},...f!==void 0?{tool_choice:f}:{}};for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],_=A=>{this.responseFlushed?this.send(A):w.push(A)},b=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:N("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(o,"in_progress")});for(let A of w)this.send(A);w.length=0,this.responseFlushed=!0}},k={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let A;try{A=await this.upstreamStream(p,r)}catch(R){this.upstreamTurnFault(R,o);return}try{for await(let R of A){if(this.cancelled)break;let v=R;if(v.type==="error"){let O=this.upstreamErrorBody(v);this.responseFlushed?this.send(Z(O)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(o,O)});return}if(v.type==="response.output_text.delta"&&typeof v.delta=="string"){b(),k.messageOpen||(this.beginMessageItem(o,k.nextOutputIndex++),k.messageOpen=!0),_({type:"response.output_text.delta",event_id:N("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:v.delta}),k.messageText+=v.delta;continue}if(v.type==="response.function_call_arguments.delta"){b();let O=typeof v.delta=="string"?v.delta:"",j=typeof v.call_id=="string"&&v.call_id.length>0?v.call_id:`${o}_fc_${k.nextOutputIndex}`,C=k.tools.get(j);if(!C){let D=typeof v.name=="string"&&v.name.length>0?v.name:void 0;C={outputIndex:k.nextOutputIndex++,name:D,args:""},k.tools.set(j,C),_({type:"response.output_item.added",event_id:N("event"),response_id:o,output_index:C.outputIndex,item:{id:j,object:"realtime.item",type:"function_call",call_id:j,name:D??"",arguments:"",status:"in_progress"}})}typeof v.name=="string"&&v.name.length>0&&(C.name=v.name),C.args+=O,_({type:"response.function_call_arguments.delta",event_id:N("event"),item_id:j,response_id:o,output_index:C.outputIndex,call_id:j,name:C.name??"",delta:O});continue}if(v.type==="response.completed"){h=v.response??null;continue}}}catch(R){this.upstreamTurnFault(R,o);return}if(this.cancelled)return;this.closeOpenItems(o,k,i),b(),this.send({type:"response.done",event_id:N("event"),response:this.doneResponse(o,i,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(cd(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Z({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:N("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:N("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("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`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:N("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:N("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let s=[];i&&s.push({type:"output_audio"}),n.messageText.length>0&&s.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:N("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Et("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof re){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof vs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Et(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(Z(r)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(Z(le("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:N("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>In&&(this.items.shift(),this.send(Z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${In} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Br){this.ws.close(ad,_s("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(Z(e)),this.ws.close(ud,_s(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ws(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ws(this.id,e)}},Gr=[];function ws(t,e){Gr.push({id:t,reason:e}),Gr.length>256&&Gr.shift()}var Jt="/v1/realtime",pd=t=>t.slice(0,120);function fd(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
24
+ ${o}`)}function Eo(t,e){let n=new pt.WebSocketServer({noServer:!0,maxPayload:yc}),r=new bt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let y;try{y=new URL(d.url??"/","http://localhost")}catch{tr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),y.pathname!==Ro){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){tr(c,401,"invalid local proxy api key");return}let v;try{v=await a(d)}catch(I){let b=e.statusOf?.(I)??null;tr(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,I=>{s.delete(c),o.add(I),I.on("close",()=>o.delete(I));try{new ko(I,v,r,e.statusOf,e.operatorLog??(b=>console.error(b)))}catch{o.delete(I),I.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&tr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=xo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let y of s)y.destroy();s.clear();for(let y of i)y.destroy();i.clear();for(let y of o)y.close(1001,"server shutting down");let p=setTimeout(()=>{for(let y of o)y.readyState!==pt.WebSocket.CLOSED&&y.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}k();k();var Lo=require("@urun-sh/core");k();var aa=require("@urun-sh/core"),kc={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},Rc={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 wn(t,e){let n=Rc[t.code];return e?`${n} (${e})`:n}function nr(t){if(t==null)return null;let e=kc[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 rr(t){if(t.kind==="create-failed")return nr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=aa.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return nr(e?"cold_start_exceeded":"queue_timeout")}var fa=require("ws");k();var pa=require("@urun-sh/core");k();var la=require("crypto");function B(t){return`${t}_${(0,la.randomUUID)().replace(/-/g,"").slice(0,24)}`}var or=4*1024*1024,Ao=8*1024*1024,sr=512,ir=20*1024*1024;function we(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function qt(t,e){return{type:"server_error",code:t,message:e}}function ae(t){return{type:"error",event_id:B("event"),error:t}}function Oo(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var q=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},xc={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},Ec={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ac={format:!0,voice:!0,speed:!0};function Oc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function jt(t,e){if(!Array.isArray(t)||t.length===0)throw new q(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new q(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ua(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new q(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ic=10;function Io(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:Ic})}function _n(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new q("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in xc));if(s.length>0)throw new q(`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=jt(o.modalities,"modalities"),u=jt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new q("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,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new q(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new q(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: 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(u==="transcription"&&!n.turns)throw new q('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=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new q(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=jt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new q('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=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Oc(u))throw new q(`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(u!==null&&typeof u!="string")throw new q("model must be a string or null","model");i.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new q("instructions must be a string or null","instructions");i.instructions=Io(u??void 0)??void 0;break;case"voice":if(u===null){delete i.voice;break}if(typeof u!="string")throw new q("voice must be a string or null","voice");if(!n.voice)throw new q("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new q(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new q("temperature must be a finite number or null","temperature");i.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new q(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new q("tools must be an array","tools");i.tools=u;break;case"tool_choice":i.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new q("metadata must be an object or null","metadata");i.metadata=u??null;break;case"turn_detection":{if(u===null){i.turnDetection=null;break}if(!n.turns)throw new q("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 l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new q(`turn_detection.type ${JSON.stringify(l.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[p,y]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new q(`turn_detection.${p} 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.${p}`,"unsupported_field");if(y!=null&&y!==c[p])throw new q(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new q("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(!u||typeof u!="object"||Array.isArray(u))throw new q("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new q(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new q(`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(u!==null)throw new q("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(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Ec))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ua(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=_n({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=_n({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new q("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ac))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ua(d.format,"audio.output.format"),d.speed!==void 0)throw new q("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 q("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new q("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 ar(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 To(t,e){let n=t;if(!n||typeof n!="object")throw new q("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 q("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:B("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 q('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new q("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 q("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 q(`${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 q("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 q("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new q(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:B("item"),type:"message",role:r,content:o}}throw new q(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ur(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 Tc=1001,Pc=1011,da=t=>t.slice(0,120),Cc=/^[A-Za-z0-9+/=]*$/,Lc=2;function Mc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Lc)return!1;return!0}var vn=class{id=B("conn");ws;binding;onClosed;operatorLog;config=Oo();sessionId=B("sess");conversationId=B("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),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.send({type:"session.created",event_id:B("event"),session:ar(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:B("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&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(ae(qt("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:B("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:B("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:B("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:B("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:B("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:B("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:B("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:B("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=B("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:B("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:B("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:B("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:B("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(we("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>or){this.fail(we("frame_too_large",`frame exceeds the ${or}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(we("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(we("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(ae({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(qt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=_n(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(ae(we("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:B("event"),session:ar(this.config,this.sessionId)});return}case"conversation.item.create":{let n=To(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:B("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(ae(we("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:B("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(ae(we("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:B("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(ae(we("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:B("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(ae(we("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Cc.test(e.audio)){this.send(ae(we("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>ir){this.send(ae(we("buffer_full",`uncommitted input audio exceeds the ${ir}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:B("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(ae(we("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=B("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:B("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:B("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:B("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:B("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(ae(we("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(ae(we("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(ae(we("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(ae(we("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(ae({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(ae(we("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?jt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?jt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new q("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((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(ae(we("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=B("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:ur(this.items),c=Io(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,h=y==="inf"||y===void 0?void 0:y,v=n.tools!==void 0?n.tools:this.config.tools,I=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,b={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},...v!==void 0?{tools:v}:{},...I!==void 0?{tool_choice:I}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],m=R=>{this.responseFlushed?this.send(R):f.push(R)},w=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:B("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:B("event"),response:this.responseObject(a,"in_progress")});for(let R of f)this.send(R);f.length=0,this.responseFlushed=!0}},g={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},x=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(C=>{this.pendingTranscriptSettled=C}),this.cancelled||this.closed))return;l=this.items.length,d=ur(this.items)}let{input:R,sawAudioOnlyItem:A}=d??{input:[],sawAudioOnlyItem:!1},T={...b,input:R,...u?this.compositeTurnAsk(n):{}};A&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let O;try{O=await this.upstreamStream(T,i)}catch(C){this.upstreamTurnFault(C,a);return}try{for await(let C of O){if(this.cancelled)break;let P=C;if(P.type==="error"){let H=this.upstreamErrorBody(P);this.responseFlushed?this.send(ae(H)):this.send({type:"response.failed",event_id:B("event"),response:this.failedResponse(a,H)});return}if(P.type==="response.output_text.delta"&&typeof P.delta=="string"){w(),g.messageOpen||(this.beginMessageItem(a,g.nextOutputIndex++),g.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:B("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:P.delta}),this.turnOutputIsAudio()&&(g.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:B("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:P.delta})),g.messageText+=P.delta;continue}if(P.type==="response.function_call_arguments.delta"){w();let H=typeof P.delta=="string"?P.delta:"",W=typeof P.call_id=="string"&&P.call_id.length>0?P.call_id:`${a}_fc_${g.nextOutputIndex}`,K=g.tools.get(W);if(!K){let oe=typeof P.name=="string"&&P.name.length>0?P.name:void 0;K={outputIndex:g.nextOutputIndex++,name:oe,args:""},g.tools.set(W,K);let te={id:W,object:"realtime.item",type:"function_call",call_id:W,name:oe??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:B("event"),response_id:a,output_index:K.outputIndex,item:te}),this.emitAssistantItemAdded(te)}typeof P.name=="string"&&P.name.length>0&&(K.name=P.name),K.args+=H,m({type:"response.function_call_arguments.delta",event_id:B("event"),item_id:W,response_id:a,output_index:K.outputIndex,call_id:W,name:K.name??"",delta:H});continue}if(P.type==="response.completed"){x=P.response??null;continue}}}catch(C){this.upstreamTurnFault(C,a);return}if(this.cancelled)return;this.closeOpenItems(a,g,l),w(),this.send({type:"response.done",event_id:B("event"),response:this.doneResponse(a,l,x)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}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.activeResponseId!==e){if(Mc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(ae({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:B("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:B("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:B("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}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:B("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:B("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:B("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:B("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:B("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:B("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:B("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:B("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:B("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:B("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 u=[];s&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:B("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.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:B("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:B("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=Xe(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??We(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ve(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(qt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof pa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=qt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(ae(r)):this.send({type:"response.failed",event_id:B("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(ae(we("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:B("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>sr&&(this.items.shift(),this.send(ae({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${sr} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Ao){this.ws.close(Tc,da("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Le(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(ae(e)),this.ws.close(Pc,da(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.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>ca(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ca(this.id,e)}},Po=[];function ca(t,e){Po.push({id:t,reason:e}),Po.length>256&&Po.shift()}var bn="/v1/realtime",$c=t=>t.slice(0,120);function Nc(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
23
25
  Connection: close\r
24
26
  Content-Type: text/plain\r
25
27
  \r
26
- ${pd(n)}\r
27
- `),t.destroy()}function md(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
28
- `}function hd(t){Ne(process.stdout,t)}function gd(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Vr(t){return t.audioSession?.audio.sessionId??void 0}function Pn(t,e){let n=new Ss.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==Jt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=N("rtup"),l=gd(o),d=R=>{(e.log??hd)(md(R))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,y=null,f=R=>{y??=R,c.abort(new Error(y))},p=()=>f("client socket closed"),w=()=>f("client socket closed (half-close)"),_=R=>f(`client socket error: ${R.message}`);i.once("close",p),i.once("end",w),i.once("error",_);let b=()=>{i.removeListener("close",p),i.removeListener("end",w),i.removeListener("error",_)},k=R=>{d({stage:"close",conn:u,model:l,...R})},h=R=>{let v=R,O=v.session!=null&&typeof v.session.sendResponseCreate=="function",j=v.clients!=null&&typeof v.clients.createResponse=="function";if(!O&&!j)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((C,D)=>{n.handleUpgrade(o,i,s,H=>{try{new Wt({ws:H,binding:R,onClosed:(z,ie)=>{k({while:"live",reason:ie.reason})}}),d({stage:"admit",conn:u,model:l,...Vr(R)===void 0?{}:{session:Vr(R)}}),C()}catch(z){D(z)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async R=>{if(c.signal.aborted){b();let v=Vr(R);try{await R.release?.()}catch(O){k({while:"queued",...v===void 0?{}:{session:v},reason:y??"client socket closed",release_failed:O instanceof Error?O.message:String(O)});return}k({while:"queued",...v===void 0?{}:{session:v},reason:y??"client socket closed",released:!0}),i.destroy();return}b(),await h(R)}).catch(R=>{let v=R instanceof bs.SessionFailedError?En(R):null,O=null;if(R!==null&&typeof R=="object"&&"status"in R){let D=R.status;typeof D=="number"&&(O=D)}let j=O??v?.status??502,C=R instanceof Error?R.message:String(R);k({while:"queued",...c.signal.aborted?{reason:y??"client socket closed"}:{reason:C,status:j}}),i.destroyed||fd(i,j,C)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}x();x();var qd=require("http");x();var Ot=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Kt=class extends Ot{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Wr=class extends Ot{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},lt=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Cn=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Kt;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Kt;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let i=n+e-Date.now();if(i<=0)throw new Wr(e);let s,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{s=setTimeout(u,i)})])}finally{clearTimeout(s);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Kt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();return n||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null)}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let i=o.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let s=i.whenLive;if(typeof s!="function")return!1;let a=r.entry;try{return await s.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n)this.endSlot(r)}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,i)=>o+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(i=>{r=i});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};x();x();var ge=class extends Error{};async function Mn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ge(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new ge(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Ln(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new ge(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof ge?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var ks="/v1/images/generations",$n="/v1/images/edits";function Rs(t){return t===ks||t===$n}var xs="/v1/images/models";async function Es(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},yd=16*1024*1024,Os=64*1024*1024;function Is(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function zt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function As(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let y of i){if(y.type==="error"){let f=y.error??{};throw new K(502,`image upstream error: ${String(f.message??"upstream reported an error")}`)}if(y.type==="response.completed"){s=y.response??null;break}}if(s===null)throw new K(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ve(s));let a=s.images;if(!Array.isArray(a)||a.length!==1||typeof a[0]!="string"||a[0].length===0)throw new K(502,`image upstream returned ${Array.isArray(a)?a.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let u=[],l=a[0].startsWith("data:")?a[0].slice(a[0].indexOf(";base64,")+8):a[0],d=Buffer.from(l,"base64");if(Is(d)===null)throw new K(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return u.push(l),{images:u}}function Ts(t){return t instanceof K?t:t instanceof Y?new K(404,t.message):new K(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ps(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return zt(r,new K(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Cs(t,e){t&&(t.outputUnits=e.images.length)}function Ms(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var _d={model:!0,prompt:!0,response_format:!0,n:!0};async function Ls(t,e,n){let r=n.maxBodyBytes??Os;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${ks}`);let o;try{o=JSON.parse((await Mn(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof ge?new K(413,c.message):new K(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new K(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!_d[c])throw new K(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new K(400,"model must be a string","model");await Es(n.turn,n.clients,a);let u=i.n??1;if(u!==1)throw new K(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let l=i.response_format??"b64_json";if(l!=="b64_json")throw new K(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await Ps(n.imageModels,a,"generation",e))return;let d=[{type:"input_text",text:s}];try{let c=await As(n.clients,a,d,n.turn?Ee(n.turn):void 0,n.turn);Cs(n.turn,c),Ms(e,c)}catch(c){throw Ts(c)}}catch(o){if(o instanceof ge){zt(e,new K(413,o.message));return}if(o instanceof K){zt(e,o);return}throw o}}var wd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function $s(t,e,n){let r=n.maxBodyBytes??Os,o=n.maxImagePartBytes??yd;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Ln(t,r)}catch(f){throw f instanceof ge?new K(413,f.message):new K(400,String(f instanceof Error?f.message:f))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string field","prompt");let u=s.get("model");if(u!==null&&typeof u!="string")throw new K(400,"model must be a string field","model");let l=u===null?void 0:u;await Es(n.turn,n.clients,l);let d=s.get("response_format")??"b64_json";if(d!=="b64_json")throw new K(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of s.keys())if(!wd[f])throw new K(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of s.getAll(f)){if(!(p instanceof File))throw new K(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new K(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let w=new Uint8Array(await p.arrayBuffer()),_=Is(w);if(_===null)throw new K(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:w,mime:_})}if(c.length===0)throw new K(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Ps(n.imageModels,l,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:f,mime:p}of c)y.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await As(n.clients,l,y,n.turn?Ee(n.turn):void 0,n.turn);Cs(n.turn,f),Ms(e,f)}catch(f){throw Ts(f)}}catch(i){if(i instanceof ge){zt(e,new K(413,i.message));return}if(i instanceof K){zt(e,i);return}throw i}}x();var Yt="/v1/audio/speech";function Gs(t){return t===Yt}var Ns=4096,Us=18e4,Ds=5e3,vd=64*1024*1024,Fs=8,Bs=5,js=1024*1024,It="voice_applied",Un="X-Urun-Voice-Applied",V=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Jr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Dn=class extends V{constructor(e){super(502,e)}};function Vs(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ws(t){return new V(502,`the runtime's ${It} receipt ${JSON.stringify(t)} cannot be relayed as the ${Un} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function bd(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Js(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Sd=2;function kd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Sd)return!1;return!0}function Rd(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var qs=new WeakMap,Nn=new WeakMap;function xd(t,e){let n=Nn.get(t)??0;if(n>=Fs)throw new V(503,`this model's speech queue is full \u2014 ${Fs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Bs}s`,void 0,Bs);Nn.set(t,n+1);let r=qs.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return qs.set(t,i),(async()=>{await r;try{return await e()}finally{Nn.set(t,(Nn.get(t)??1)-1),o()}})()}async function Ed(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof re))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function dt(t){return t instanceof V?t:t instanceof Y?new V(404,t.message):new V(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Hs(t,e,n,r,o,i,s,a,u){let l=a??(()=>{});return xd(e,async()=>{if(s?.()===!0)return null;let d=!1,c=!1,y=!1,f,p=new Promise(v=>{f=v}),w=[],_=()=>{c&&!y&&w.length>=o.quietRunFrames&&(y=!0,f())},b=e.onOutputAudio(v=>{let O=Buffer.from(v,"base64");if(O.byteLength===0)return;let j=kd(O);if(!d){if(j)return;d=!0}if(j){w.push(O),_();return}for(let C of w)l(C);w.length=0,l(O),_()}),k=null,h,A,R;try{R=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let O=new Promise(D=>{A=setTimeout(D,i.capMs)}),j=!1;for(;;){let D=R.next(),H=await Promise.race([D,O]);if(H===void 0){j=!0,D.catch(()=>{});break}if(H.done)break;let z=H.value;if(z.type==="error"){let ie=z.error??{};throw await R.return?.(),new V(502,`speech upstream error: ${String(ie.message??"upstream reported an error")}`)}if(z.type==="response.completed"){k=z.response??null,c=!0,u?.(k),_(),await R.return?.();break}}if(clearTimeout(A),j)throw new V(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(k===null)throw new V(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([p,new Promise(D=>{h=setTimeout(()=>{C=!0,D()},o.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let D=k[It];if(typeof D!="string"||D!==r.voice){let H=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof D=="string"?`${It} ${JSON.stringify(D)}`:`no ${It} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw y?new Dn(H):new V(502,H)}}if(!d)throw new V(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!y&&w.length<1)throw new V(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return k}catch(v){throw v instanceof Dn||await Ed(t,n,R,i.returnBoundMs),v}finally{h!==void 0&&clearTimeout(h),A!==void 0&&clearTimeout(A),b()}})}function Od(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Un)),t.write(a,u=>{u||(i+=a.byteLength,Js(e,i))}),t.writableLength>js&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${js} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[It];if(typeof u=="string"){if(!Vs(u))throw Ws(u);t.addTrailers({[Un]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function Id(t,e,n){let r;try{r=await t(e)}catch(o){throw dt(o)}return r?!0:(Jr(n,new V(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ad={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Td="wav, pcm";async function Ks(t,e,n){let r=n.maxBodyBytes??vd,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new V(405,`${String(t.method)} is not supported on ${Yt}`);let s;try{s=JSON.parse((await Mn(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof ge?new V(413,h.message):new V(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new V(400,"request body must be a JSON object");let a=s;for(let h of Object.keys(a))if(!Ad[h])throw new V(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new V(400,"input is required and must be a non-empty string","input");if(u.length>Ns)throw new V(400,`input is ${u.length} chars \u2014 over the ${Ns}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let l=a.model===void 0?void 0:a.model;if(l!==void 0&&typeof l!="string")throw new V(400,"model must be a string","model");let d=a.voice;if(d!==void 0&&(typeof d!="string"||d.trim().length===0))throw new V(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new V(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Yt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(l)}catch(h){throw dt(h)}if(c.defect!==null)throw new V(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof d=="string"?d:void 0;if(y!==void 0&&c.published.length>0&&!c.published.includes(y))throw new V(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=a.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new V(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Td} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new V(400,"stream_format, when present, must be a string","stream_format");let p=a.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new V(400,"speed, when present, must be a number","speed");if(p!==1)throw new V(400,`speed=${JSON.stringify(p)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let w=a.instructions;if(w!==void 0){if(typeof w!="string")throw new V(400,"instructions, when present, must be a string","instructions");if(w.trim().length>0)throw new V(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await bd(n.turn,n.clients,l);let _=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",_,_),!await Id(n.speechModels,l,e))return;if(typeof n.clients.openAudioOn!="function")throw new V(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new V(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let b;try{b=await n.clients.speechSessionHandle(l)}catch(h){throw dt(h)}let k;try{k=await n.clients.openAudioOn(b)}catch(h){throw dt(h)}n.turn&&(n.turn.sessionId=k.sessionId);try{if(f==="wav"){let h=[],A=await Hs(n.clients,k,b,{model:l,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Us,returnBoundMs:n.turnReturnBoundMs??Ds},i,v=>h.push(v),v=>{n.turn&&(n.turn.outputSeconds=Ve(v))});if(A===null||i())return;let R=Buffer.concat(h);if(y===void 0){let v=A[It];if(typeof v=="string"){if(!Vs(v))throw Ws(v);e.setHeader(Un,v)}}Js(n.turn,R.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Rd(R.byteLength),R]))}else{let h=Od(e,n.turn,i,y===void 0),A;try{A=await Hs(n.clients,k,b,{model:l,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Us,returnBoundMs:n.turnReturnBoundMs??Ds},i,h.sink,R=>{n.turn&&(n.turn.outputSeconds=Ve(R))})}catch(R){let v=dt(R);if(!h.started())throw v;n.turn&&(n.turn.streamError=!0),h.fail(v);return}if(A===null)return;try{await h.finish(A)}catch(R){let v=dt(R);n.turn&&(n.turn.streamError=!0),h.fail(v);return}}}catch(h){throw dt(h)}}catch(s){if(s instanceof ge){Jr(e,new V(413,s.message));return}if(s instanceof V){Jr(e,s);return}throw s}}x();var Fn="/v1/audio/transcriptions";function zs(t){return t===Fn}var Ys="/v1/audio/models",Pd=16*1024*1024,Cd=64*1024*1024,ne=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Kr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Xs(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Md(t){if(!Xs(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ld(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function $d(t,e){t&&(t.outputUnits=e.seconds)}async function Nd(t,e,n,r,o,i){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),a=[],u=null;for await(let l of s){if(a.push(l),l.type==="error"){let d=l.error??{},c=typeof d.type=="string"?d.type:"upstream_error",y=String(d.message??"upstream reported an error");throw new ne(c==="invalid_request_error"?400:502,`transcription upstream error: ${y}`)}if(l.type==="response.completed"){u=l.response??null;break}}if(u===null)throw new ne(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ve(u)),Rt(a,u)}function Qs(t){return t instanceof ne?t:t instanceof Y?new ne(404,t.message):new ne(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ud(t,e,n){let r;try{r=await t(e)}catch(o){throw Qs(o)}return r?!0:(Kr(n,new ne(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Dd=new Set(["file","model","language","response_format"]);async function Zs(t,e,n){let r=n.maxBodyBytes??Cd,o=n.maxAudioPartBytes??Pd;try{if(t.method!=="POST")throw new ne(405,`${String(t.method)} is not supported on ${Fn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new ne(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Ln(t,r)}catch(b){throw b instanceof ge?new ne(413,b.message):new ne(400,String(b instanceof Error?b.message:b))}let a=new Map;for(let b of s.keys()){if(!Dd.has(b))throw new ne(400,`form field "${b}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,b);a.set(b,(a.get(b)??0)+1)}for(let[b,k]of a)if(k>1)throw new ne(400,`form field "${b}" appears ${k} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,b);let u=s.get("model");if(u!==null&&typeof u!="string")throw new ne(400,"model must be a string field","model");let l=u===null?void 0:u,d=s.get("language");if(d!==null&&(typeof d!="string"||d.trim().length===0))throw new ne(400,"language, when present, must be a non-empty string","language");let c=d===null?void 0:d,y=s.get("response_format")??"json";if(y!=="json")throw new ne(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=s.get("file");if(!(f instanceof File))throw new ne(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new ne(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!Xs(p))throw new ne(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let w=Md(p);if(w===null)throw new ne(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ld(n.turn,n.clients,l),n.stats?.request("audio_transcriptions",p.length,p.length),!await Ud(n.transcriptionModels,l,e))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let b=await Nd(n.clients,l,_,c,n.turn?Ee(n.turn):void 0,n.turn);$d(n.turn,w),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw Qs(b)}}catch(i){if(i instanceof ge){Kr(e,new ne(413,i.message));return}if(i instanceof ne){Kr(e,i);return}throw i}}var Vn=require("@urun-sh/core");x();var zr=require("@urun-sh/core"),We=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},Yr=33e4;function ea(t,e=Yr){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,i=new Promise((l,d)=>{o=d}),s=setTimeout(()=>o(new Bn),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof re||l instanceof zr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof Bn?(await r.return?.(void 0),new We("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new We("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(s)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new We("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Bn=class extends Error{constructor(){super("stream idle timeout")}};function ta(t){return t instanceof We?!1:t instanceof re?!0:t instanceof zr.SessionFailedError?t.kind==="transport-failed":!1}x();var Qr="x-urun-profile",Xt="voice";var Re=class extends Error{status=400},Fd=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Bd=/\s/;function jd(t){return Fd.test(t)}function Xr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function na(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function ra(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new Re(`the ${Qr} header is empty \u2014 the only profile this lane accepts is "${Xt}" (omit the header for the ordinary lane)`);if(l!==Xt)throw new Re(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Xt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==Xt)throw new Re(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${Xt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new Re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:na(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:na(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Xr(u,"sentence_flush",!0),includeReasoning:Xr(u,"include_reasoning",!1),metadata:Xr(u,"metadata",!1)}}var jn=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&jd(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Bd.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function to(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Hd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function we(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function fe(t,e,n,r="invalid_request_error",o){we(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function no(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);we(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function De(t,e,n,r){we(t,e,{type:"error",error:{type:n,message:r}})}function At(t,e,n){if(e==="anthropic"){we(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}we(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Gd=64*1024*1024,Qt=class extends Error{};async function oa(t,e=Gd){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Qt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ct(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function sa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function qn(t){let e=sa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ia(t){let e=qn(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Vd(t,e){let n=sa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Wd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function Jd(t,e){let n=Wd(e);n&&(t.timing=n),t.outputSeconds=Ve(e)}function pt(t,e){Vd(t,e),Jd(t,e)}async function Wn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function aa(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Kd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Hn=class extends Error{};function zd(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Hn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Yd(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:zd(n.role,n.content)})}return e}function Zr(t){return St(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Xd(t,e,n,r,o,i){let s=qt(i.id),a=t.stream===!0;if(i.model=Se(t),i.stream=a,await Wn(i,e,typeof t.model=="string"?t.model:void 0),a){let b;try{b=await Gt({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(k){if(k instanceof Y){At(r,"openai",k);return}if(k instanceof Oe){fe(r,k.status,k.message);return}throw k}to(r);for await(let k of b.events)k.type==="error"&&(i.streamError=!0),k.type==="response.completed"&&pt(i,k.response),r.write(`event: ${String(k.type??"message")}
29
- data: ${JSON.stringify(k)}
28
+ ${$c(n)}\r
29
+ `),t.destroy()}function Uc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
30
+ `}function Dc(t){ze(process.stdout,t)}function Fc(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Co(t){return t.audioSession?.audio.sessionId??void 0}function lr(t,e){let n=new fa.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==bn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=B("rtup"),l=Fc(o),d=g=>{(e.log??Dc)(Uc(g))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,y=g=>{p??=g,c.abort(new Error(p))},h=()=>y("client socket closed"),v=()=>y("client socket closed (half-close)"),I=g=>y(`client socket error: ${g.message}`);s.once("close",h),s.once("end",v),s.once("error",I);let b=()=>{s.removeListener("close",h),s.removeListener("end",v),s.removeListener("error",I)},f=g=>{d({stage:"close",conn:u,model:l,...g})},m=g=>{let x=g,R=x.session!=null&&typeof x.session.sendResponseCreate=="function",A=x.clients!=null&&typeof x.clients.createResponse=="function";if(!R&&!A)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((T,O)=>{n.handleUpgrade(o,s,i,C=>{try{new vn({ws:C,binding:g,operatorLog:e.operatorLog,onClosed:(P,H)=>{f({while:"live",reason:H.reason})}}),d({stage:"admit",conn:u,model:l,...Co(g)===void 0?{}:{session:Co(g)}}),T()}catch(P){O(P)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async g=>{if(c.signal.aborted){b();let x=Co(g);try{await g.release?.()}catch(R){f({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",release_failed:R instanceof Error?R.message:String(R)});return}f({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",released:!0}),s.destroy();return}b(),await m(g)}).catch(g=>{let x=g instanceof Lo.SessionFailedError?rr(g):null,R=null;if(g!==null&&typeof g=="object"&&"status"in g){let C=g.status;typeof C=="number"&&(R=C)}let A=R??x?.status??502,T=g instanceof Error?g.message:String(g),O=R!==null?T:x!==null?wn(x,g instanceof Lo.SessionFailedError&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):Le(g).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:A}}),s.destroyed||Nc(s,A,O)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}k();var Za=require("crypto");k();var cp=require("http");k();k();var Se=class extends Error{};async function dr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Se(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new Se(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function cr(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Se(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Se?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ma="/v1/images/generations",pr="/v1/images/edits";function ga(t){return t===ma||t===pr}var ha="/v1/images/models";async function ya(t,e,n){if(t){if(t.model=Ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var Q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Bc=16*1024*1024,wa=64*1024*1024;function _a(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Sn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function va(t,e,n,r,o,s){let i=s??(h=>console.error(h)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let h of a){if(h.type==="error"){let v=h.error??{},I=typeof v.message=="string"&&v.message.length>0&&Ve(v.message)?v.message:null;throw I===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new Q(502,"the image upstream failed while serving this request")):new Q(502,`image upstream error: ${I}`)}if(h.type==="response.completed"){u=h.response??null;break}}if(u===null)throw new Q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=rt(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new Q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(_a(p)===null)throw new Q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function ba(t,e){if(t instanceof Q)return t;if(t instanceof Ue)throw t;return t instanceof Z?new Q(404,t.message):new Q(502,Ht("image",t,e))}async function Sa(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Sn(r,new Q(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function ka(t,e){t&&(t.outputUnits=e.images.length)}function Ra(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Hc={model:!0,prompt:!0,response_format:!0,n:!0};async function xa(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??wa;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${ma}`);let s;try{s=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Se?new Q(413,p.message):new Q(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new Q(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Hc[p])throw new Q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string","prompt");let u=i.model===void 0?void 0:i.model;if(u!==void 0&&typeof u!="string")throw new Q(400,"model must be a string","model");await ya(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new Q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await Sa(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await va(n.clients,u,c,n.turn?$e(n.turn):void 0,n.turn,r);ka(n.turn,p),Ra(e,p)}catch(p){throw ba(p,r)}}catch(s){if(s instanceof Se){Sn(e,new Q(413,s.message));return}if(s instanceof Q){Sn(e,s);return}throw s}}var jc={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ea(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??wa,s=n.maxImagePartBytes??Bc;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${pr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Q(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(h){throw h instanceof Se?new Q(413,h.message):new Q(400,String(h instanceof Error?h.message:h))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new Q(400,"model must be a string field","model");let d=l===null?void 0:l;await ya(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let h of a.keys())if(!jc[h])throw new Q(400,`form field "${h}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,h);let p=[];for(let h of["image","image[]"])for(let v of a.getAll(h)){if(!(v instanceof File))throw new Q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(v.size>s)throw new Q(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let I=new Uint8Array(await v.arrayBuffer()),b=_a(I);if(b===null)throw new Q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:I,mime:b})}if(p.length===0)throw new Q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Sa(n.imageModels,d,"edit",e))return;let y=[{type:"input_text",text:u}];for(let{bytes:h,mime:v}of p)y.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(h).toString("base64")}`});try{let h=await va(n.clients,d,y,n.turn?$e(n.turn):void 0,n.turn,r);ka(n.turn,h),Ra(e,h)}catch(h){throw ba(h,r)}}catch(i){if(i instanceof Se){Sn(e,new Q(413,i.message));return}if(i instanceof Q){Sn(e,i);return}throw i}}k();var kn="/v1/audio/speech";function $a(t){return t===kn}var Aa=4096,Oa=18e4,Ia=5e3,qc=64*1024*1024,Ta=8,Pa=5,Ca=1024*1024,Gt="voice_applied",mr="X-Urun-Voice-Applied",J=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Mo(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var gr=class extends J{constructor(e){super(502,e)}};function Na(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ua(t){return new J(502,`the runtime's ${Gt} receipt ${JSON.stringify(t)} cannot be relayed as the ${mr} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function Gc(t,e,n){if(t){if(t.model=Ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Da(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Vc=2;function Wc(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Vc)return!1;return!0}function Jc(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var La=new WeakMap,fr=new WeakMap;function Kc(t,e){let n=fr.get(t)??0;if(n>=Ta)throw new J(503,`this model's speech queue is full \u2014 ${Ta} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Pa}s`,void 0,Pa);fr.set(t,n+1);let r=La.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return La.set(t,s),(async()=>{await r;try{return await e()}finally{fr.set(t,(fr.get(t)??1)-1),o()}})()}async function zc(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new J(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof X))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function xt(t,e){if(t instanceof J)return t;if(t instanceof Ue)throw t;return t instanceof Z?new J(404,t.message):new J(502,Ht("speech",t,e))}async function Ma(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Kc(e,async()=>{if(i?.()===!0)return null;let p=!1,y=!1,h=!1,v,I=new Promise(A=>{v=A}),b=[],f=()=>{y&&!h&&b.length>=o.quietRunFrames&&(h=!0,v())},m=e.onOutputAudio(A=>{let T=Buffer.from(A,"base64");if(T.byteLength===0)return;let O=Wc(T);if(!p){if(O)return;p=!0}if(O){b.push(T),f();return}for(let C of b)c(C);b.length=0,c(T),f()}),w=null,g,x,R;try{R=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let T=new Promise(P=>{x=setTimeout(P,s.capMs)}),O=!1;for(;;){let P=R.next(),H=await Promise.race([P,T]);if(H===void 0){O=!0,P.catch(()=>{});break}if(H.done)break;let W=H.value;if(W.type==="error"){let K=W.error??{};await R.return?.();let oe=typeof K.message=="string"&&K.message.length>0&&Ve(K.message)?K.message:null;throw oe===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new J(502,"the speech upstream failed while serving this request")):new J(502,`speech upstream error: ${oe}`)}if(W.type==="response.completed"){w=W.response??null,y=!0,u?.(w),f(),await R.return?.();break}}if(clearTimeout(x),O)throw new J(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(w===null)throw new J(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([I,new Promise(P=>{g=setTimeout(()=>{C=!0,P()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let P=w[Gt];if(typeof P!="string"||P!==r.voice){let H=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof P=="string"?`${Gt} ${JSON.stringify(P)}`:`no ${Gt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new gr(H):new J(502,H)}}if(!p)throw new J(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!h&&b.length<1)throw new J(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return w}catch(A){throw A instanceof gr||await zc(t,n,R,s.returnBoundMs),A}finally{g!==void 0&&clearTimeout(g),x!==void 0&&clearTimeout(x),m()}})}function Yc(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",mr)),t.write(a,u=>{u||(s+=a.byteLength,Da(e,s))}),t.writableLength>Ca&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ca} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[Gt];if(typeof u=="string"){if(!Na(u))throw Ua(u);t.addTrailers({[mr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Xc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw xt(s,r)}return o?!0:(Mo(n,new J(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Qc={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Zc="wav, pcm";async function Fa(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??qc,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new J(405,`${String(t.method)} is not supported on ${kn}`);let a;try{a=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(w){throw w instanceof Se?new J(413,w.message):new J(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new J(400,"request body must be a JSON object");let u=a;for(let w of Object.keys(u))if(!Qc[w])throw new J(400,`request field "${w}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,w);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new J(400,"input is required and must be a non-empty string","input");if(l.length>Aa)throw new J(400,`input is ${l.length} chars \u2014 over the ${Aa}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new J(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new J(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new J(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${kn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(w){throw xt(w,r)}if(p.defect!==null)throw new J(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof c=="string"?c:void 0;if(y!==void 0&&p.published.length>0&&!p.published.includes(y))throw new J(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=u.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new J(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Zc} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new J(400,"stream_format, when present, must be a string","stream_format");let v=u.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new J(400,"speed, when present, must be a number","speed");if(v!==1)throw new J(400,`speed=${JSON.stringify(v)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let I=u.instructions;if(I!==void 0){if(typeof I!="string")throw new J(400,"instructions, when present, must be a string","instructions");if(I.trim().length>0)throw new J(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await Gc(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",b,b),!await Xc(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new J(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new J(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new J(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let f;try{f=await n.clients.speechSessionHandle(d)}catch(w){throw xt(w,r)}let m;try{m=await n.clients.openAudioOn(f)}catch(w){throw xt(w,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(h==="wav"){let w=[],g=await Ma(n.clients,m,f,{model:d,text:l,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Oa,returnBoundMs:n.turnReturnBoundMs??Ia},i,R=>w.push(R),R=>{n.turn&&(n.turn.outputSeconds=rt(R))},r);if(g===null||i())return;let x=Buffer.concat(w);if(y===void 0){let R=g[Gt];if(typeof R=="string"){if(!Na(R))throw Ua(R);e.setHeader(mr,R)}}Da(n.turn,x.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Jc(x.byteLength),x]))}else{let w=Yc(e,n.turn,i,y===void 0),g;try{g=await Ma(n.clients,m,f,{model:d,text:l,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Oa,returnBoundMs:n.turnReturnBoundMs??Ia},i,w.sink,x=>{n.turn&&(n.turn.outputSeconds=rt(x))},r)}catch(x){let R=xt(x,r);if(!w.started())throw R;n.turn&&(n.turn.streamError=!0),w.fail(R);return}if(g===null)return;try{await w.finish(g)}catch(x){let R=xt(x,r);n.turn&&(n.turn.streamError=!0),w.fail(R);return}}}catch(w){throw xt(w,r)}}catch(a){if(a instanceof Se){Mo(e,new J(413,a.message));return}if(a instanceof J){Mo(e,a);return}throw a}}k();var hr="/v1/audio/transcriptions";function Ba(t){return t===hr}var Ha="/v1/audio/models",ep=16*1024*1024,tp=64*1024*1024,le=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function $o(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function ja(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function np(t){if(!ja(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function rp(t,e,n){if(t){if(t.model=Ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function op(t,e){t&&(t.outputUnits=e.seconds)}async function sp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},y=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Ve(p.message)?p.message:null;throw h===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new le(y==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new le(y==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new le(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=rt(d)),Ft(l,d)}function qa(t,e){if(t instanceof le)return t;if(t instanceof Ue)throw t;return t instanceof Z?new le(404,t.message):new le(502,Ht("transcription",t,e))}async function ip(t,e,n,r){let o;try{o=await t(e)}catch(s){throw qa(s,r)}return o?!0:($o(n,new le(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var ap=new Set(["file","model","language","response_format"]);async function Ga(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??tp,s=n.maxAudioPartBytes??ep;try{if(t.method!=="POST")throw new le(405,`${String(t.method)} is not supported on ${hr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new le(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(f){throw f instanceof Se?new le(413,f.message):new le(400,String(f instanceof Error?f.message:f))}let u=new Map;for(let f of a.keys()){if(!ap.has(f))throw new le(400,`form field "${f}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,f);u.set(f,(u.get(f)??0)+1)}for(let[f,m]of u)if(m>1)throw new le(400,`form field "${f}" appears ${m} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let l=a.get("model");if(l!==null&&typeof l!="string")throw new le(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new le(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,y=a.get("response_format")??"json";if(y!=="json")throw new le(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let h=a.get("file");if(!(h instanceof File))throw new le(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new le(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await h.arrayBuffer());if(!ja(v))throw new le(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let I=np(v);if(I===null)throw new le(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await rp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await ip(n.transcriptionModels,d,e,r))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let f=await sp(n.clients,d,b,p,n.turn?$e(n.turn):void 0,n.turn,r);op(n.turn,I),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw qa(f,r)}}catch(i){if(i instanceof Se){$o(e,new le(413,i.message));return}if(i instanceof le){$o(e,i);return}throw i}}var vr=require("@urun-sh/core");k();var Uo="x-urun-profile",Rn="voice";var Te=class extends Error{status=400},up=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,lp=/\s/;function dp(t){return up.test(t)}function No(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Te(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Va(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Te(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Te(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Te(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Wa(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Te(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new Te(`the ${Uo} header is empty \u2014 the only profile this lane accepts is "${Rn}" (omit the header for the ordinary lane)`);if(l!==Rn)throw new Te(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Rn)throw new Te(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Te("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Te("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Va(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Va(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:No(u,"sentence_flush",!0),includeReasoning:No(u,"include_reasoning",!1),metadata:No(u,"metadata",!1)}}var Vt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&dp(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(lp.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Bo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function pp(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function xe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function de(t,e,n,r="invalid_request_error",o){xe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Ho(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Xe(r),a=i??We(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),xe(t,l,{error:{message:a,type:o,code:u}})}function Je(t,e,n,r){xe(t,e,{type:"error",error:{type:n,message:r}})}function Wt(t,e,n){if(e==="anthropic"){xe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}xe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var fp=64*1024*1024,xn=class extends Error{};async function Ja(t,e=fp){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new xn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Et(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function za(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function yr(t){let e=za(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Ka(t){let e=yr(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function mp(t,e){let n=za(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function gp(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function hp(t,e){let n=gp(e);n&&(t.timing=n),t.outputSeconds=rt(e)}function At(t,e){mp(t,e),hp(t,e)}async function br(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Ya(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function yp(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var wr=class extends Error{};function wp(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new wr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function _p(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:wp(n.role,n.content)})}return e}function Do(t){return Ut(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function vp(t,e,n,r,o,s,i){let a=mn(s.id),u=t.stream===!0;if(s.model=Ie(t),s.stream=u,await br(s,e,typeof t.model=="string"?t.model:void 0),u){let f;try{f=await hn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(m){if(m instanceof Z){Wt(r,"openai",m);return}if(m instanceof Ne){de(r,m.status,m.message);return}if(m instanceof je||m instanceof be){r.setHeader("retry-after","2"),de(r,503,m.message,"capacity_error");return}throw m}Bo(r);for await(let m of f.events){if(m.type==="error"){s.streamError=!0;let w=m.error,g=Xe(w),x=g??We(s.id);g===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(m)}`),r.write(`event: error
31
+ data: ${JSON.stringify({error:{message:x,type:w?.type??"upstream_error",code:w?.code??null}})}
30
32
 
31
- `);r.write(`data: [DONE]
33
+ `),r.end();return}m.type==="response.completed"&&At(s,m.response),r.write(`event: ${String(m.type??"message")}
34
+ data: ${JSON.stringify(m)}
32
35
 
33
- `),r.end();return}let u;try{u=xt(n,t)}catch(b){if(b instanceof Oe){fe(r,b.status,b.message);return}throw b}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let l=t.store!==!1,d=Se(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await Mr(e,t,u,!1,Ee(i))}catch(b){if(b instanceof Y){At(r,"openai",b);return}if(b instanceof Oe){fe(r,b.status,b.message);return}throw b}let f=[],p=null;for await(let b of o.track(y,d,i)){if(f.push(b),b.type==="error"){no(r,b);return}b.type==="response.completed"&&(p=b.response)}if(p==null){fe(r,502,"upstream produced no response.completed event","upstream_error");return}pt(i,p);let w=Rt(f,p),_=ut(c,St(p).length,w);if(_){fe(r,502,at(d,_),"upstream_error");return}l&&n.remember(s,u,Cr(p,w),l),we(r,200,{...p,id:s})}async function Qd(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){fe(n,400,"chat/completions requires a messages array");return}let a;try{a=ra(i,t)}catch(C){if(C instanceof Re){fe(n,C.status,C.message);return}throw C}let u=String(t.model??"urun"),l=as(o.id),d;try{d=Yd(s)}catch(C){if(C instanceof Hn){fe(n,400,C.message);return}throw C}let c=Se(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Wn(o,e,typeof t.model=="string"?t.model:void 0);let y=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:d,stream:!0,tools:Kd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},Ee(o))}catch(C){if(C instanceof Y){At(n,"openai",C);return}throw C}if(t.stream===!0){a?Hd(n):to(n);let C=[],D=new Xe,H="",z=a?new jn(a,he=>{n.write(`data: ${JSON.stringify(ct(l,u,{content:he},null))}
36
+ `)}r.write(`data: [DONE]
34
37
 
35
- `)}):null,ie=he=>{z?.flush(),n.write(he),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:l,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
38
+ `),r.end();return}let l;try{l=Bt(n,t)}catch(f){if(f instanceof Ne){de(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Ie(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await wo(e,t,l,!1,$e(s))}catch(f){if(f instanceof Z){Wt(r,"openai",f);return}if(f instanceof Ne){de(r,f.status,f.message);return}if(f instanceof je||f instanceof be){r.setHeader("retry-after","2"),de(r,503,f.message,"capacity_error");return}throw f}let h=[],v=null;for await(let f of o.track(y,c,s)){if(h.push(f),f.type==="error"){Ho(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(v=f.response)}if(v==null){de(r,502,"upstream produced no response.completed event","upstream_error");return}At(s,v);let I=Ft(h,v),b=Rt(p,Ut(v).length,I);if(b){de(r,502,kt(c,b),"upstream_error");return}d&&n.remember(a,l,yo(v,I),d),xe(r,200,{...v,id:a})}async function bp(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){de(n,400,"chat/completions requires a messages array");return}let u;try{u=Wa(s,t)}catch(O){if(O instanceof Te){de(n,O.status,O.message);return}throw O}let l=String(t.model??"urun"),d=Yi(o.id),c;try{c=_p(a)}catch(O){if(O instanceof wr){de(n,400,O.message);return}throw O}let p=Ie(t);r.model(p),o.model=p,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let y=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:yp(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},$e(o))}catch(O){if(O instanceof Z){Wt(n,"openai",O);return}if(O instanceof je||O instanceof be){n.setHeader("retry-after","2"),de(n,503,O.message,"capacity_error");return}throw O}if(t.stream===!0){u?pp(n):Bo(n);let O=[],C=new dt,P="",H=u?new Vt(u,K=>{n.write(`data: ${JSON.stringify(Et(d,l,{content:K},null))}
36
39
 
37
- `),n.write(`data: ${JSON.stringify(ct(l,u,{role:"assistant"},null))}
40
+ `)}):null,W=K=>{H?.flush(),n.write(K),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
38
41
 
39
- `);for await(let te of r.track(f,c,o)){C.push(te);let de=kt(te);if(te.type==="response.output_text.delta"&&typeof te.delta=="string")H+=te.delta,z?z.push(te.delta):n.write(`data: ${JSON.stringify(ct(l,u,{content:te.delta},null))}
42
+ `),n.write(`data: ${JSON.stringify(Et(d,l,{role:"assistant"},null))}
40
43
 
41
- `);else if(te.type==="response.reasoning_text.delta"&&typeof te.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(ct(l,u,{reasoning_content:te.delta},null))}
44
+ `);for await(let se of r.track(h,p,o)){O.push(se);let ve=Dt(se);if(se.type==="response.output_text.delta"&&typeof se.delta=="string")P+=se.delta,H?H.push(se.delta):n.write(`data: ${JSON.stringify(Et(d,l,{content:se.delta},null))}
42
45
 
43
- `);else if(de){z?.flush();let{call:Le,isNew:G}=D.add(de),I=G?{index:de.tool_index,id:Le.id??`call_${de.tool_index}`,type:"function",function:{name:Le.name??"",arguments:de.delta}}:{index:de.tool_index,function:{arguments:de.delta}};n.write(`data: ${JSON.stringify(ct(l,u,{tool_calls:[I]},null))}
46
+ `);else if(se.type==="response.reasoning_text.delta"&&typeof se.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(Et(d,l,{reasoning_content:se.delta},null))}
44
47
 
45
- `)}else if(te.type==="error"){o.streamError=!0,ie(`data: ${JSON.stringify({error:te})}
48
+ `);else if(ve){H?.flush();let{call:V,isNew:M}=C.add(ve),ee=M?{index:ve.tool_index,id:V.id??`call_${ve.tool_index}`,type:"function",function:{name:V.name??"",arguments:ve.delta}}:{index:ve.tool_index,function:{arguments:ve.delta}};n.write(`data: ${JSON.stringify(Et(d,l,{tool_calls:[ee]},null))}
46
49
 
47
- `);return}}let he=Zr(Ue(C)),ve=ut(y,D.size+he.length,H);if(ve){o.streamError=!0,ie(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:at(c,ve)}})}
50
+ `)}else if(se.type==="error"){o.streamError=!0;let V=se.error??{},M=Xe(V),ee=M??We(o.id);M===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(se)}`),W(`data: ${JSON.stringify({error:{message:ee,type:V.type??"upstream_error",code:V.code??null}})}
48
51
 
49
- `);return}z?.flush(),D.size===0&&he.length>0&&n.write(`data: ${JSON.stringify(ct(l,u,{tool_calls:he},null))}
52
+ `);return}}let K=Do(Ye(O)),oe=Rt(y,C.size+K.length,P);if(oe){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:kt(p,oe)}})}
50
53
 
51
- `);let Te=D.size>0||he.length>0;n.write(`data: ${JSON.stringify(ct(l,u,{},Te?"tool_calls":"stop"))}
54
+ `);return}H?.flush(),C.size===0&&K.length>0&&n.write(`data: ${JSON.stringify(Et(d,l,{tool_calls:K},null))}
52
55
 
53
- `);let ee=qn(Ue(C));pt(o,Ue(C)),ee&&n.write(`data: ${JSON.stringify({id:l,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:ia(Ue(C))})}
56
+ `);let te=C.size>0||K.length>0;n.write(`data: ${JSON.stringify(Et(d,l,{},te?"tool_calls":"stop"))}
57
+
58
+ `);let Be=yr(Ye(O));At(o,Ye(O)),Be&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Ka(Ye(O))})}
54
59
 
55
60
  `),n.write(`data: [DONE]
56
61
 
57
- `),n.end();return}finally{z?.flush(),z?.dispose()}}let p="",w="",_=[],b=new Xe;for await(let C of r.track(f,c,o)){_.push(C),C.type==="response.output_text.delta"&&typeof C.delta=="string"&&(p+=C.delta),C.type==="response.reasoning_text.delta"&&typeof C.delta=="string"&&(w+=C.delta);let D=kt(C);if(D&&b.add(D),C.type==="error"){no(n,C);return}}let k=Ue(_);pt(o,k);let h=Zr(k),A=h.length>0?h:Zr({output:b.items()}),R=ut(y,A.length,p);if(R){fe(n,502,at(c,R),"upstream_error");return}let v=A.map(({index:C,...D})=>D),O={role:"assistant",content:p||null},j=w||aa(k);j&&(O.reasoning_content=j),v.length>0&&(O.tool_calls=v),we(n,200,{id:l,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:O,finish_reason:v.length>0?"tool_calls":"stop"}],usage:ia(k)})}var ro="sense-latest";async function Zd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){fe(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:ro,s=Se({model:i});if(o.model=s,o.stream=!1,t.state===void 0||t.state===null){fe(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){fe(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){fe(n,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let l=performance.now();r.model(s),await Wn(o,e,i),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Ee(o))}catch(b){if(b instanceof Y){At(n,"openai",b);return}if(b instanceof lt){n.setHeader("retry-after","2"),fe(n,503,b.message,"capacity_error");return}throw b}u.dial_ms=Math.round(performance.now()-c);let y=[],f=null;try{for await(let b of r.track(d,s,o))if(f===null&&(f=performance.now(),u.first_event_ms=Math.round(f-c)),y.push(b),b.type==="error"){no(n,b);return}}catch(b){if(b instanceof Y){f!==null&&(u.stream_ms=Math.round(performance.now()-f)),At(n,"openai",b);return}if(b instanceof lt){f!==null&&(u.stream_ms=Math.round(performance.now()-f)),n.setHeader("retry-after","2"),fe(n,503,b.message,"capacity_error");return}throw f!==null&&(u.stream_ms=Math.round(performance.now()-f)),b}f!==null&&(u.stream_ms=Math.round(performance.now()-f));let p=Ue(y);if(p==null){fe(n,502,"upstream produced no response.completed event","upstream_error");return}pt(o,p);let w=Rt(y,p),_;try{_=JSON.parse(w)}catch{fe(n,502,"systemone answer was not valid JSON","upstream_error");return}if(_===null||typeof _!="object"||Array.isArray(_)){fe(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof _=="object"&&_!==null&&!Array.isArray(_)&&"timing"in _){let b=_.timing;if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"question_fwd_ms"in b&&"head_ms"in b){let k=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=k(b.question_fwd_ms),u.head_ms=k(b.head_ms)}}we(n,200,_)}function ec(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Zt=class extends Error{};function Gn(t){return new Zt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function tc(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function nc(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Zt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function rc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Gn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Gn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function oc(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Gn(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:rc(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Gn(a)}}return i(),r}function eo(t){return St(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function ic(t,e,n,r,o){let i=t.messages;if(!Array.isArray(i)){De(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){De(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){De(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(O=>typeof O!="string"))){De(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(t.model??"urun"),a=us(o.id),u=[],l;try{t.system&&u.push({role:"system",content:ec(t.system)});for(let O of i)u.push(...oc(O));l=nc(t.tool_choice)}catch(O){if(O instanceof Zt){De(n,400,"invalid_request_error",O.message);return}throw O}let d=Se(t);r.model(d),o.model=d,o.stream=t.stream===!0,await Wn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:u,stream:!0,tools:tc(t.tools),tool_choice:l,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Ee(o))}catch(O){if(O instanceof Y){At(n,"anthropic",O);return}throw O}let f=(O,j)=>{n.destroyed||n.write(`event: ${O}
58
- data: ${JSON.stringify({type:O,...j})}
62
+ `),n.end();return}finally{H?.flush(),H?.dispose()}}let v="",I="",b=[],f=new dt;for await(let O of r.track(h,p,o)){b.push(O),O.type==="response.output_text.delta"&&typeof O.delta=="string"&&(v+=O.delta),O.type==="response.reasoning_text.delta"&&typeof O.delta=="string"&&(I+=O.delta);let C=Dt(O);if(C&&f.add(C),O.type==="error"){Ho(n,O,{inferenceId:o.id,operatorError:i});return}}let m=Ye(b);At(o,m);let w=Do(m),g=w.length>0?w:Do({output:f.items()}),x=Rt(y,g.length,v);if(x){de(n,502,kt(p,x),"upstream_error");return}let R=g.map(({index:O,...C})=>C),A={role:"assistant",content:v||null},T=I||Ya(m);T&&(A.reasoning_content=T),R.length>0&&(A.tool_calls=R),xe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:A,finish_reason:R.length>0?"tool_calls":"stop"}],usage:Ka(m)})}var jo="sense-latest";async function Sp(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:jo,a=Ie({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){de(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){de(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){de(n,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=l;let d=performance.now();r.model(a),await br(o,e,i),l.resolve_ms=Math.round(performance.now()-d);let c,p=performance.now();try{c=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},$e(o))}catch(f){if(f instanceof Z){Wt(n,"openai",f);return}if(f instanceof je){n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}if(f instanceof be){n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}throw f}l.dial_ms=Math.round(performance.now()-p);let y=[],h=null;try{for await(let f of r.track(c,a,o))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-p)),y.push(f),f.type==="error"){Ho(n,f,{inferenceId:o.id,operatorError:s});return}}catch(f){if(f instanceof Z){h!==null&&(l.stream_ms=Math.round(performance.now()-h)),Wt(n,"openai",f);return}if(f instanceof je){h!==null&&(l.stream_ms=Math.round(performance.now()-h)),n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}if(f instanceof be){h!==null&&(l.stream_ms=Math.round(performance.now()-h)),n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),f}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let v=Ye(y);if(v==null){de(n,502,"upstream produced no response.completed event","upstream_error");return}At(o,v);let I=Ft(y,v),b;try{b=JSON.parse(I)}catch{de(n,502,"systemone answer was not valid JSON","upstream_error");return}if(b===null||typeof b!="object"||Array.isArray(b)){de(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"timing"in b){let f=b.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let m=w=>typeof w=="number"&&Number.isFinite(w)&&w>=0?Math.round(w):null;l.question_fwd_ms=m(f.question_fwd_ms),l.head_ms=m(f.head_ms)}}xe(n,200,b)}function kp(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var En=class extends Error{};function _r(t){return new En(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Rp(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function xp(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new En(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ep(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw _r(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw _r(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Ap(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw _r(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Ep(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw _r(a)}}return s(),r}function Fo(t){return Ut(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function Op(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Je(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){Je(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Je(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(A=>typeof A!="string"))){Je(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=Xi(o.id),l=[],d;try{t.system&&l.push({role:"system",content:kp(t.system)});for(let A of i)l.push(...Ap(A));d=xp(t.tool_choice)}catch(A){if(A instanceof En){Je(n,400,"invalid_request_error",A.message);return}throw A}let c=Ie(t);r.model(c),o.model=c,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:l,stream:!0,tools:Rp(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},$e(o))}catch(A){if(A instanceof Z){Wt(n,"anthropic",A);return}if(A instanceof je||A instanceof be){n.setHeader("retry-after","2"),Je(n,503,"capacity_error",A.message);return}throw A}let h=(A,T)=>{n.destroyed||n.write(`event: ${A}
63
+ data: ${JSON.stringify({type:A,...T})}
64
+
65
+ `)};if(t.stream===!0){let A=r.track(y,c,o);Bo(n),h("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let T=0,O="",C=0,P="none",H=()=>P,W=-1,K=-1,oe=new dt,te=[],Be=()=>{P!=="none"&&(P="none",h("content_block_stop",{index:W}))},se=(re,ue)=>{Be(),P=re,W=C++,h("content_block_start",{index:W,content_block:ue})};for await(let re of A){if(n.destroyed)break;te.push(re);let ue=Dt(re);if(re.type==="response.reasoning_text.delta"&&typeof re.delta=="string")H()!=="thinking"&&se("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:re.delta}});else if(re.type==="response.output_text.delta"&&typeof re.delta=="string")H()!=="text"&&se("text",{type:"text",text:""}),T+=1,O+=re.delta,h("content_block_delta",{index:W,delta:{type:"text_delta",text:re.delta}});else if(ue){let{call:Ae}=oe.add(ue);(H()!=="tool"||ue.tool_index!==K)&&(K=ue.tool_index,se("tool",{type:"tool_use",id:Ae.id??`call_${ue.tool_index}`,name:Ae.name??"",input:{}})),ue.delta&&h("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:ue.delta}})}else if(re.type==="error"){o.streamError=!0;let Ae=re.error,Ze=Xe(Ae);Ze===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(re)}`),h("error",{error:{type:"api_error",message:Ze??We(o.id)}}),n.end();return}}if(n.destroyed)return;let ve=Ye(te),V=Ut(ve),M=Rt(p,oe.size+V.length,O);if(M){o.streamError=!0,h("error",{error:{type:"api_error",message:kt(c,M)}}),n.end();return}Be();let ee=[];if(oe.size===0)try{ee=Fo(ve)}catch(re){o.streamError=!0;let ue=Le(re,{inferenceId:o.id});ue.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(re instanceof Error?re.message:re)}`),h("error",{error:{type:"api_error",message:ue.message}}),n.end();return}C===0&&ee.length===0&&(se("text",{type:"text",text:""}),Be()),ee.forEach(re=>{let ue=C++;h("content_block_start",{index:ue,content_block:{...re,input:{}}}),h("content_block_delta",{index:ue,delta:{type:"input_json_delta",partial_json:JSON.stringify(re.input??{})}}),h("content_block_stop",{index:ue})});let Qe=oe.size>0||ee.length>0,ne=yr(ve);At(o,ve),h("message_delta",{delta:{stop_reason:Qe?"tool_use":"end_turn"},usage:ne?{input_tokens:ne.input_tokens,output_tokens:ne.output_tokens}:{output_tokens:T}}),h("message_stop",{}),n.end();return}let v="",I="",b=[],f=new dt;for await(let A of r.track(y,c,o)){b.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(v+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(I+=A.delta);let T=Dt(A);if(T&&f.add(T),A.type==="error"){let O=A.error,C=O?.type==="invalid_request_error",P=Xe(O);P===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),Je(n,C?400:502,C?"invalid_request_error":"api_error",P??We(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=Ye(b);At(o,m);let w;try{w=Fo(m),w.length===0&&f.size>0&&(w=Fo({output:f.items()}))}catch(A){let T=Le(A,{inferenceId:o.id});T.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),Je(n,502,"api_error",T.message);return}let g=Rt(p,w.length,v);if(g){Je(n,502,"api_error",kt(c,g));return}let x=[],R=I||Ya(m);R&&x.push({type:"thinking",thinking:R}),(v||w.length===0)&&x.push({type:"text",text:v}),x.push(...w),xe(n,200,{id:u,type:"message",role:"assistant",content:x,model:a,stop_reason:w.length>0?"tool_use":"end_turn",usage:yr(m)??{input_tokens:0,output_tokens:0}})}function Ip(t){ze(process.stdout,t)}function Xa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Ip,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new bt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),y=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(m,w,g,x,R)=>y?Je(c,m,x,w):de(c,m,w,g,R),v=ho(p.pathname),I=p.pathname.startsWith("/partners/"),b=v||I?{id:fn(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;b&&(c.setHeader(Ki,b.id),c.once("close",()=>{let m=Qi({turn:b,method:d.method??"",path:p.pathname,res:c});i(Zi(m)),u?.(m),oi({record:m,ledger:t.ledger??null,req:d})}));let f=()=>zi(p.pathname,b);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){xe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){xe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=p.pathname===Hn?"canonical":p.pathname===dn?"huggingface":null;if(m){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let R=t.usage;if(!R){h(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let A=R.authorize(d),T;try{T=await Ja(d,li)}catch(P){if(P instanceof xn){h(413,P.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let O=P=>R.lookup(A,P),C;try{if(m==="canonical"){let P=di(T),H=await O(P);jn(H,P),C={requests:H}}else C=await fi(T,O)}catch(P){if(P instanceof lt){h(P.status,P.message,"invalid_request_error","invalid_request_error");return}throw P}xe(c,200,C);return}if(d.method==="GET"&&p.pathname===gt){let R=await s(d);if(b&&(b.org=R.tenant??null),!R.openRouterModels){h(501,`GET ${gt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}xe(c,200,await R.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${dn} and GET ${gt}`,"invalid_request_error","not_found_error");return}let w=await s(d);if(b&&(b.org=w.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:gt}),c.end();return}xe(c,200,await w.listModels());return}if(d.method==="GET"&&p.pathname===ha){if(!w.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}xe(c,200,await w.listImageModels());return}if(ga(p.pathname)){if(!w.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let R={clients:w,imageModels:w.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===pr?await Ea(d,c,R):await xa(d,c,R);return}if(d.method==="GET"&&p.pathname===Ha){if(!w.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}xe(c,200,await w.listSpeechToTextModels());return}if(Ba(p.pathname)){if(!w.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${hr}`,"not_implemented","not_implemented_error");return}let R={clients:w,transcriptionModels:w.supportsTranscription,stats:l,turn:f(),operatorLog:a};await Ga(d,c,R);return}if($a(p.pathname)){if(!w.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${kn}`,"not_implemented","not_implemented_error");return}let R={clients:w,speechModels:w.supportsSpeech,stats:l,turn:f(),operatorLog:a};await Fa(d,c,R);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let g;try{g=await Ja(d)}catch(R){if(R instanceof xn){h(413,R.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=Buffer.byteLength(JSON.stringify(g));if(p.pathname==="/v1/responses"){l.request("responses",x,x),await vp(g,w,gn(w),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",x,x),await bp(g,w,c,l,f(),d.headers[Uo],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",x,x),await Sp(g,w,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",x,x),await Op(g,w,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",x,x),Je(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let w=String(m instanceof Error?m.message:m);if(!c.headersSent){let R=o?.(m)??null;if(R){R.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${R.operatorDetail}`),h(R.status,w,R.openaiType,R.anthropicType);return}if(m instanceof vr.SessionAllocationError){let T=nr(m.code);if(T){let O=m.retryAfterSeconds??(T.status===429?30:void 0);O!==void 0&&c.setHeader("Retry-After",String(O)),h(T.status,wn(T,m.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(m instanceof vr.SessionFailedError){let T=rr(m);if(T){let O=T.status===429?30:void 0;O!==void 0&&c.setHeader("Retry-After",String(O)),h(T.status,wn(T,m.status.sessionId?`session ${m.status.sessionId}`:void 0),T.openaiType,T.anthropicType,T.code);return}}if(m instanceof fe){h(502,w,"upstream_error","api_error");return}if(m instanceof qe){m.retryable&&c.setHeader("Retry-After","1");let T=Le(m,{inferenceId:b?.id??null});T.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),h(502,T.message,"upstream_error","api_error",m.code);return}if(m instanceof ct){c.setHeader("Retry-After",String(m.retryAfterSeconds)),h(m.status,w,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let A=Le(m,{inferenceId:b?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),h(500,A.message,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let g=m instanceof qe?m.code:null,x=Le(m,{inferenceId:b?.id??null});x.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),c.destroyed||(y?c.write(`event: error
66
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:x.message}})}
59
67
 
60
- `)};if(t.stream===!0){let O=r.track(y,d,o);to(n),f("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let j=0,C="",D=0,H="none",z=()=>H,ie=-1,he=-1,ve=new Xe,Te=[],ee=()=>{H!=="none"&&(H="none",f("content_block_stop",{index:ie}))},te=(q,me)=>{ee(),H=q,ie=D++,f("content_block_start",{index:ie,content_block:me})};for await(let q of O){if(n.destroyed)break;Te.push(q);let me=kt(q);if(q.type==="response.reasoning_text.delta"&&typeof q.delta=="string")z()!=="thinking"&&te("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:ie,delta:{type:"thinking_delta",thinking:q.delta}});else if(q.type==="response.output_text.delta"&&typeof q.delta=="string")z()!=="text"&&te("text",{type:"text",text:""}),j+=1,C+=q.delta,f("content_block_delta",{index:ie,delta:{type:"text_delta",text:q.delta}});else if(me){let{call:$e}=ve.add(me);(z()!=="tool"||me.tool_index!==he)&&(he=me.tool_index,te("tool",{type:"tool_use",id:$e.id??`call_${me.tool_index}`,name:$e.name??"",input:{}})),me.delta&&f("content_block_delta",{index:ie,delta:{type:"input_json_delta",partial_json:me.delta}})}else if(q.type==="error"){o.streamError=!0,f("error",{error:{type:"api_error",message:JSON.stringify(q)}}),n.end();return}}if(n.destroyed)return;let de=Ue(Te),Le=St(de),G=ut(c,ve.size+Le.length,C);if(G){o.streamError=!0,f("error",{error:{type:"api_error",message:at(d,G)}}),n.end();return}ee();let I=[];if(ve.size===0)try{I=eo(de)}catch(q){o.streamError=!0,f("error",{error:{type:"api_error",message:String(q instanceof Error?q.message:q)}}),n.end();return}D===0&&I.length===0&&(te("text",{type:"text",text:""}),ee()),I.forEach(q=>{let me=D++;f("content_block_start",{index:me,content_block:{...q,input:{}}}),f("content_block_delta",{index:me,delta:{type:"input_json_delta",partial_json:JSON.stringify(q.input??{})}}),f("content_block_stop",{index:me})});let X=ve.size>0||I.length>0,Pe=qn(de);pt(o,de),f("message_delta",{delta:{stop_reason:X?"tool_use":"end_turn"},usage:Pe?{input_tokens:Pe.input_tokens,output_tokens:Pe.output_tokens}:{output_tokens:j}}),f("message_stop",{}),n.end();return}let p="",w="",_=[],b=new Xe;for await(let O of r.track(y,d,o)){_.push(O),O.type==="response.output_text.delta"&&typeof O.delta=="string"&&(p+=O.delta),O.type==="response.reasoning_text.delta"&&typeof O.delta=="string"&&(w+=O.delta);let j=kt(O);if(j&&b.add(j),O.type==="error"){let C=O.error,D=C?.type==="invalid_request_error";De(n,D?400:502,D?"invalid_request_error":"api_error",C?.message??JSON.stringify(O));return}if(n.destroyed)break}if(n.destroyed)return;let k=Ue(_);pt(o,k);let h;try{h=eo(k),h.length===0&&b.size>0&&(h=eo({output:b.items()}))}catch(O){De(n,502,"api_error",String(O instanceof Error?O.message:O));return}let A=ut(c,h.length,p);if(A){De(n,502,"api_error",at(d,A));return}let R=[],v=w||aa(k);v&&R.push({type:"thinking",thinking:v}),(p||h.length===0)&&R.push({type:"text",text:p}),R.push(...h),we(n,200,{id:a,type:"message",role:"assistant",content:R,model:s,stop_reason:h.length>0?"tool_use":"end_turn",usage:qn(k)??{input_tokens:0,output_tokens:0}})}function sc(t){Ne(process.stdout,t)}function ua(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??sc,a=t.observe,u=new it;return(l,d)=>{let c=new URL(l.url??"/","http://localhost"),y=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),f=(k,h,A,R,v)=>y?De(d,k,R,h):fe(d,k,h,A,v),p=Pr(c.pathname),w=c.pathname.startsWith("/partners/"),_=p||w?{id:jt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;_&&(d.setHeader(is,_.id),d.once("close",()=>{let k=ls({turn:_,method:l.method??"",path:c.pathname,res:d});s(ds(k)),a?.(k),hi({record:k,ledger:t.ledger??null,req:l})}));let b=()=>ss(c.pathname,_);(async()=>{if(l.method==="GET"&&c.pathname==="/healthz"){we(d,200,{ok:!0});return}if(l.method==="GET"&&c.pathname==="/stats"){we(d,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(l.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let k=c.pathname===pn?"canonical":c.pathname===Dt?"huggingface":null;if(k){if(l.method!=="POST"){f(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){f(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let O=v.authorize(l),j;try{j=await oa(l,vi)}catch(H){if(H instanceof Qt){f(413,H.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let C=H=>v.lookup(O,H),D;try{if(k==="canonical"){let H=bi(j),z=await C(H);fn(z,H),D={requests:z}}else D=await Ri(j,C)}catch(H){if(H instanceof Ye){f(H.status,H.message,"invalid_request_error","invalid_request_error");return}throw H}we(d,200,D);return}if(l.method==="GET"&&c.pathname===et){let v=await i(l);if(_&&(_.org=v.tenant??null),!v.openRouterModels){f(501,`GET ${et} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}we(d,200,await v.openRouterModels());return}if(c.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${l.method} ${c.pathname} \u2014 the partner surface currently carries ${Dt} and GET ${et}`,"invalid_request_error","not_found_error");return}let h=await i(l);if(_&&(_.org=h.tenant??null),l.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){d.writeHead(308,{location:et}),d.end();return}we(d,200,await h.listModels());return}if(l.method==="GET"&&c.pathname===xs){if(!h.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listImageModels());return}if(Rs(c.pathname)){if(!h.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:h,imageModels:h.supportsImages,stats:u,turn:b()};c.pathname===$n?await $s(l,d,v):await Ls(l,d,v);return}if(l.method==="GET"&&c.pathname===Ys){if(!h.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listSpeechToTextModels());return}if(zs(c.pathname)){if(!h.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Fn}`,"not_implemented","not_implemented_error");return}let v={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:b()};await Zs(l,d,v);return}if(Gs(c.pathname)){if(!h.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Yt}`,"not_implemented","not_implemented_error");return}let v={clients:h,speechModels:h.supportsSpeech,stats:u,turn:b()};await Ks(l,d,v);return}if(l.method!=="POST"){f(404,`no route for ${l.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let A;try{A=await oa(l)}catch(v){if(v instanceof Qt){f(413,v.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=Buffer.byteLength(JSON.stringify(A));if(c.pathname==="/v1/responses"){u.request("responses",R,R),await Xd(A,h,Ht(h),d,u,b());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",R,R),await Qd(A,h,d,u,b(),l.headers[Qr]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",R,R),await Zd(A,h,d,u,b());return}if(c.pathname==="/v1/messages"){u.request("messages",R,R),await ic(A,h,d,u,b());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",R,R),De(d,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}f(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(k=>{let h=String(k instanceof Error?k.message:k);if(!d.headersSent){let R=o?.(k)??null;if(R){f(R.status,h,R.openaiType,R.anthropicType);return}if(k instanceof Vn.SessionAllocationError){let v=xn(k.code);if(v){let O=k.retryAfterSeconds??(v.status===429?30:void 0);O!==void 0&&d.setHeader("Retry-After",String(O)),f(v.status,Fr(v,k.code??void 0),v.openaiType,v.anthropicType,v.code);return}}if(k instanceof Vn.SessionFailedError){let v=En(k);if(v){let O=v.status===429?30:void 0;O!==void 0&&d.setHeader("Retry-After",String(O)),f(v.status,Fr(v,k.status.sessionId?`session ${k.status.sessionId}`:void 0),v.openaiType,v.anthropicType,v.code);return}}if(k instanceof oe){f(502,h,"upstream_error","api_error");return}if(k instanceof We){k.retryable&&d.setHeader("Retry-After","1"),f(502,h,"upstream_error","api_error",k.code);return}if(k instanceof Ot){d.setHeader("Retry-After",String(k.retryAfterSeconds)),f(k.status,h,k.status===429?"capacity_error":"upstream_error",k.status===429?"rate_limit_error":"overloaded_error",k.code);return}f(500,h,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0);let A=k instanceof We?k.code:null;d.destroyed||(y?d.write(`event: error
61
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
68
+ `):c.write(`data: ${JSON.stringify({error:{message:x.message,type:"upstream_error",code:g}})}
62
69
 
63
- `):d.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error",code:A}})}
70
+ `)),c.end()})}}k();var ot=(t,e)=>Object.assign(new Error(e),{status:t}),Cp='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Go=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),qo=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof Z?ot(404,n.message):n}};async function Qa(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ot(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Cp}`);if(o==="transcription")throw ot(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw ot(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw ot(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(y){throw y instanceof Z?ot(404,y.message):y}if(!p)throw ot(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(y){throw y instanceof Z?ot(404,y.message):y}if(p!=="stt")throw ot(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await qo(t,n.stt),i=await qo(t,e),a=await qo(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let y=new AbortController;return d=y,Lp({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,y.signal,()=>{d===y&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(y){throw y instanceof X?Go("stt",n.stt,y):y}},composite:!0};return e!==void 0&&(c.model=e),c}function Vo(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Sr=class extends Error{};async function*Lp(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),y=!1,h=null,v=null,I=[],b=null,f=new Promise((C,P)=>{n&&n.addEventListener("abort",()=>P(new Sr),{once:!0})}),m=()=>y||n?.aborted===!0,w=async C=>{if(m())return;let P;try{P=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:C}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(W){throw W instanceof X?Go("tts",u.tts,W):W}let H=P[Symbol.asyncIterator]();v=H;try{for(;;){let W=H.next(),K;try{K=await Promise.race([W,f])}catch(te){if(W.catch(()=>{}),te instanceof Sr)return;throw te}if(K.done)return;let oe=K.value;if(oe.type==="error"){let te=oe.error&&typeof oe.error.message=="string"?oe.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${te}`)}if(oe.type==="response.completed")return}}finally{v===H&&(v=null)}},g=async()=>{for(;I.length>0&&!m();){let C=I.shift();await w(C)}},x=C=>{if(C===""||m()||(I.push(C),b!==null))return;let P=g();b=P,P.then(()=>{b===P&&(b=null)},H=>{b===P&&(b=null),h??=H})},R=()=>{y=!0,I.length=0;let C=v;if(v=null,C){let P=C.return?.();P&&P.catch(()=>{})}},A=async()=>{for(;I.length>0||b!==null;){let C=b;if(C===null){await w(I.shift());continue}await C}},T=p?new Vt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},C=>x(C)):null,O=null;try{let C;try{C=await o.createResponseOn(s,d)}catch(P){throw P instanceof X?Go("chat",a,P):P}for await(let P of C){if(m())return;let H=P;if(H.type==="error"){yield P;return}if(H.type==="response.output_text.delta"&&typeof H.delta=="string"){yield P,T?.push(H.delta);continue}if(H.type==="response.function_call_arguments.delta"){T?.flush(),yield P;continue}if(H.type==="response.completed"){O=P.response;continue}}T?.flush(),T?.dispose(),p&&await A(),O!==null&&(yield{type:"response.completed",response:O})}finally{T?.dispose(),R();try{if(h instanceof X)throw h}finally{r?.()}}}var De=(t,e)=>Object.assign(new Error(e),{status:t});function eu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function tu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Mp='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function nu(t,e,n,r){if(!t.supportsAudio)throw De(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof Z?De(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof Z?De(404,c.message):c}if(d!==null)return await Qa(t,e,d,n,r);throw De(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw De(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof Z?De(404,d.message):d}if(s&&!t.openTurnsOn)throw De(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof Z?De(404,c.message):c}if(d!=="stt")throw De(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw De(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Mp}`);if(r==="transcription"&&!s)throw De(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof be?De(503,d.message):d}let a=`conn_${(0,Za.randomUUID)()}`,u={audio:await t.openAudioOn(i,n,a)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,a)},voice:o,audioSession:u};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}k();var cu=require("@urun-sh/core/internal"),pu=Re(require("ws"),1);k();k();k();k();function ru(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function kr(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}k();k();function ou(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var $p="llm-resp";async function*xr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,u=r.get(a)??{};i.id&&(u.id=i.id),i.function?.name&&(u.name=i.function.name),r.set(a,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:u.id,name:u.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield ou(s);return}}}async function*Wo(t,e){let n=`${$p}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*xr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Er=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=kr(e,n,this.consumerId);return this.write(r),Wo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=ru(e,n,r,this.consumerId);return this.write(o),Wo(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var su=0;function Np(){return su+=1,`req_${Date.now().toString(36)}_${su.toString(36)}`}var Ot=class{transport;constructor(e){this.transport=new Er(e)}responses={create:async e=>{let n=Np(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};k();var Jt=Re(require("yjs"),1),iu=require("@urun-sh/core/internal"),Up=3e4;function Dp(t){return(e,n,r)=>{let o=t(e);Jt.applyUpdate(n,Jt.encodeStateAsUpdate(o));let s=a=>Jt.applyUpdate(o,a),i=a=>Jt.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}async function*Fp(t,e){let n=[],r=!1,o=null,s="",i=u=>{if(!("responses"in u)||typeof u.responses!="object"||u.responses===null)return null;let l=u.responses;if(!(e in l))return null;let d=l[e];if(d===null||typeof d!="object"||!("error"in d))return{body:d,error:null};let c=d.error;return c===null?{body:d,error:null}:{body:d,error:c}},a=u=>{let l={};for(let[c,p]of Object.entries(u)){let y=p;l[c]=typeof y?.toJSON=="function"?y.toJSON():p}if("tokens"in l&&typeof l.tokens=="object"&&l.tokens!==null){let c=l.tokens[e];typeof c=="string"&&c.length>s.length&&(n.push({t:"delta",delta:c.slice(s.length)}),s=c)}let d=i(l);if(d!==null){d.error!==null?n.push({t:"error",body:d.error}):n.push({t:"response",body:d.body}),r=!0,o?.(),o=null;return}if("progress"in l&&typeof l.progress=="object"&&l.progress!==null){let c=l.progress[e];if(typeof c=="object"&&c!==null&&"state"in c&&c.state==="error"){let y="error"in c&&typeof c.error=="string"?c.error:"lane request failed";n.push({t:"error",body:{message:y}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(a(t.get()??{}),!r){let u=t.on("change",a);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(l=>{o=l})}}finally{u()}}for(;n.length>0;)yield n.shift()}function Jo(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Dp(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=u=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let l=r.get(u);return l||(l=new iu.SessionDocumentImpl(u,e,n),r.set(u,l)),l},i=u=>{let l="llm-resp:";if(!u.startsWith(l))throw new Error(`lane session exposes no stream "${u}" \u2014 only the llm reply lanes (${l}<rid>)`);let d=u.slice(l.length);return{messages:()=>Fp(s("llm"),d),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(u){return s(u)},stream:i,async end(){},async whenLive(u){let l=s("llm");if(l.synced===!0)return;let d=u?.timeout??t.whenLiveTimeoutMs??Up;await new Promise((c,p)=>{let y=setTimeout(()=>{h(),p(new Error(`lane ${e} llm doc never synced within ${d}ms`))},d),h=l.onSynced(()=>{clearTimeout(y),u?.signal?.removeEventListener("abort",v),c()}),v=()=>{clearTimeout(y),h(),p(u?.signal?.reason instanceof Error?u.signal.reason:new Error("aborted"))};u?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let u of r.values())u.dispose();r.clear()}}}k();var ft=require("crypto"),Bp=["sfu","urun-doc"],uu="runtime:lease",Hp="lane:join",jp="urun-runtime-key-v1";function Ko(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,ft.createHmac)("sha256",t).update(`${jp}|${e}`).digest("base64url")}var qp=120;function au(t){return Buffer.from(t).toString("base64url")}function Gp(t,e,n){let r=au(JSON.stringify(t)),o=au(JSON.stringify(e)),s=(0,ft.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function lu(t,e,n=qp,r=Hp,o){let s=Math.floor(Date.now()/1e3),i=o?Ko(e,o):e;return Gp({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,ft.randomUUID)()},i)}function du(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,u]=s,l,d;try{l=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(l.alg!=="HS256")return null;let c;try{c=Buffer.from(u,"base64url")}catch{return null}let p=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,y=[];if(p!==void 0?(y.push(Ko(n,p)),o&&y.push(Ko(o,p))):(y.push(n),o&&y.push(o)),!y.some(f=>{let m=(0,ft.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===m.length&&(0,ft.timingSafeEqual)(c,m)}))return null;let h=d.exp;if(typeof h!="number"||h<=r)return null;let v=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(v!==void 0&&Bp.some(f=>f===v||Array.isArray(v)&&v.includes(f))))return null;let b=d.session_id??d.sub;return typeof b!="string"||b!==e?null:{sessionId:b,aud:v,scope:typeof d.scope=="string"?d.scope:void 0,tenant:p,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:h}}k();var Vp=3,Wp="llm",Jp=new Set(["paused","error"]);function Ar(t,e,n){let r=t.doc(Wp),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,a=!1,u=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...u])p(c);u.clear()}};return o&&l.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Vp||d(new X(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{a=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Jp.has(c.name)&&d(new X(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(u.add(c),()=>u.delete(c))},dispose(){u.clear();for(let c of l.splice(0))c()}}}async function*zo(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function Kp(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Ue(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function fu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,y,h,v,I)=>{let b=h?Jo({laneId:p,roomDoc:w=>t.roomDoc(p,w)}):Jo({laneId:p,connector:(0,cu.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:p,token:()=>lu(p,t.tokenSecret,void 0,void 0,I),WebSocketPolyfill:pu.default})}),f=h?a(p):Ar(b,`lane:${p}`,{armOnFirstSync:!0}),m={session:b,responses:new Ot(b),gone:f,goneWatch:f,laneId:p,pool:y,inFlight:0,laneSession:b,self:h,host:v??""};return n.set(p,m),f.onGone(()=>u(m)),m},a=p=>{let y=null,h=!1,v=new Set,I=f=>{if(!y){y=f;for(let m of[...v])m(f);v.clear()}},b=t.hostedSignal?.(p,f=>{if(f){h=!0;return}h&&I(new X(`the lane ${p} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>y,onGone(f){return y?(f(y),()=>{}):(v.add(f),()=>v.delete(f))},dispose(){b?.(),v.clear()}}},u=p=>{l(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose())},l=p=>{let y=p.laneId;return typeof y=="string"&&n.get(y)===p},d=(p,y)=>{throw t.metrics?.observeLane503Fast(y??""),s.set(p,e()),new be(p)},c=async(p,y)=>{let h=Kp(y);o.add(h);let v=e();try{let I=await t.laneWarmWaitMsFor?.(p,y)??t.laneColdWakeDefaultMs??0,b=await t.plane.pick({pool:h,model:p,holdMs:I});t.metrics?.observeLaneReady(p??"",b.length);let m=b.map(g=>({laneId:g.laneId,self:g.host===t.selfAddress,host:g.host})).sort((g,x)=>g.self!==x.self?g.self?-1:1:(r.get(g.laneId)??0)-(r.get(x.laneId)??0))[0];m||d(h,p);let w=n.get(m.laneId);return w?.goneWatch?.gone()&&(u(w),w=void 0),w&&(w.pool!==h||w.self!==m.self||w.host!==m.host)&&(u(w),w=void 0),w||(w=i(m.laneId,h,m.self,m.host,y.sharedOrgId??void 0)),w.inFlight+=1,r.set(m.laneId,(r.get(m.laneId)??0)+1),{app:h,entry:w,identity:{kind:"catalog",model_id:y.modelId??p??"",variant:y.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-v)}};return{sessionFor(p,y){return c(p,y)},release(p){l(p)&&(p.inFlight=Math.max(0,p.inFlight-1),r.set(p.laneId,p.inFlight))},owns(p){return l(p)},entryFor(p){return n.get(p)??null},evict(p){l(p)&&(p.gone.dispose(),n.delete(p.laneId),r.set(p.laneId,0),p.laneSession.destroy())},async status(){let p=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),y=await t.plane.status().catch(()=>[]),h=new Map(zp(y));return Promise.all(p.map(async v=>{let I=h.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:I.lanes,lastDemandAt:I.lastDemandAt,local:[...n.values()].filter(b=>b.pool===v).map(b=>({laneId:b.laneId,inFlight:b.inFlight,self:b.self,host:b.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let p of n.values())p.gone.dispose(),p.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(p=>({pool:p.pool,laneId:p.laneId,inFlight:p.inFlight}))}}}function zp(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}k();var hu=require("http");var Yp="/pooler/v1/lanes/pick",Xp="/pooler/v1/lanes/status",Qp=1e4;function mu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),u=r===void 0?void 0:Buffer.from(JSON.stringify(r)),l=(0,hu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...u===void 0?{}:{"content-type":"application/json","content-length":String(u.byteLength)}},timeout:o},d=>{let c=[];d.on("data",p=>c.push(p)),d.on("end",()=>{let p=Buffer.concat(c).toString("utf8"),y=null;try{y=p===""?null:JSON.parse(p)}catch{y=null}s({status:d.statusCode??0,json:y})}),d.on("error",i)});l.on("timeout",()=>{l.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),l.on("error",i),l.end(u)})}function gu(t,e,n){if(t===503)return new be(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function yu(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await mu(t,"POST",Yp,{pool:e,model:n,hold_ms:r},r+Qp);if(o.status!==200)throw gu(o.status,o.json,e);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let e=await mu(t,"GET",Xp,void 0,5e3);if(e.status!==200)throw gu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}k();var Ru=require("ws");k();var _u=Re(require("yjs"),1),Yt=Re(require("y-protocols/sync"),1),st=Re(require("y-protocols/awareness"),1),pe=Re(require("lib0/encoding"),1),Xt=Re(require("lib0/decoding"),1),vu=Re(require("lib0/map"),1),bu=Re(require("lodash.debounce"),1);k();var wu=()=>{};var ef=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,tf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,nf=0,rf=1;var of=process.env.GC!=="false"&&process.env.GC!=="0",sf=process.env.YPERSISTENCE,Or=null;if(typeof sf=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var zt=new Map,Ir=0,Xo=1,af=(t,e,n)=>{let r=pe.createEncoder();pe.writeVarUint(r,Ir),Yt.writeUpdate(r,t);let o=pe.toUint8Array(r);n.conns.forEach((s,i)=>An(n,i,o))},Yo=class extends _u.Doc{constructor(e){super({gc:of}),this.name=e,this.conns=new Map,this.awareness=new st.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let u=pe.createEncoder();pe.writeVarUint(u,Xo),pe.writeVarUint8Array(u,st.encodeAwarenessUpdate(this.awareness,a));let l=pe.toUint8Array(u);this.conns.forEach((d,c)=>{An(this,c,l)})};this.awareness.on("update",n),this.on("update",af),!1}},Qo=(t,e=!0)=>vu.setIfUndefined(zt,t,()=>{let n=new Yo(t);return n.gc=e,Or!==null&&Or.bindState(t,n),zt.set(t,n),n}),uf=(t,e,n)=>{try{let r=pe.createEncoder(),o=Xt.createDecoder(n);switch(Xt.readVarUint(o)){case Ir:pe.writeVarUint(r,Ir),Yt.readSyncMessage(o,r,e,t),pe.length(r)>1&&An(e,t,pe.toUint8Array(r));break;case Xo:{st.applyAwarenessUpdate(e.awareness,Xt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Kt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),st.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Or!==null&&(Or.writeState(t.name,t).then(()=>{t.destroy()}),zt.delete(t.name))}e.close()},An=(t,e,n)=>{e.readyState!==nf&&e.readyState!==rf&&Kt(t,e);try{e.send(n,r=>{r!=null&&Kt(t,e)})}catch{Kt(t,e)}},lf=3e4,Su=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Qo(n,r);o.conns.set(t,new Set),t.on("message",a=>uf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Kt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Kt(o,t),clearInterval(i)}}},lf);t.on("close",()=>{Kt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=pe.createEncoder();pe.writeVarUint(a,Ir),Yt.writeSyncStep1(a,o),An(o,t,pe.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=pe.createEncoder();pe.writeVarUint(l,Xo),pe.writeVarUint8Array(l,st.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),An(o,t,pe.toUint8Array(l))}}};var Zo="/doc/",xu=30,df=1e4,ku="llm";function cf(t){if(!t.startsWith(Zo))return null;let e=t.slice(Zo.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function On(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
71
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
72
+ Connection: close\r
73
+ Content-Type: text/plain; charset=utf-8\r
74
+ Content-Length: ${Buffer.byteLength(o)}\r
75
+ \r
76
+ ${o}`)}function Eu(t,e){let n=new Ru.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=b=>o.get(`${b}/${ku}`)??0,a=b=>s.get(b)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=!1,y=(b,f,m)=>{let w=i(b)>0,g=a(b),x=g>0,R=`${b}/${f}`,A=o.get(R)??0;m>0?o.set(R,m):o.delete(R);let T=g+m-A;T>0?s.set(b,T):s.delete(b);let O=i(b)>0,C=T>0;if(w!==O){O?h(b):v(b);for(let P of u.get(b)??[])P(O)}x&&!C&&queueMicrotask(()=>{let P=`${b}/`;for(let[H,W]of[...zt.entries()])!H.startsWith(P)||W.conns.size>0||(zt.delete(H),W.destroy())})},h=b=>{if(!e.hostRegistry||l.has(b))return;let f=()=>{e.hostRegistry?.setHost(b,e.selfAddress).catch(()=>{})};f();let m=setInterval(f,df);m.unref?.(),l.set(b,m)},v=b=>{let f=l.get(b);f&&(clearInterval(f),l.delete(b)),e.hostRegistry&&e.hostRegistry.delHost(b,e.selfAddress).catch(()=>{})},I=(b,f,m)=>{let w;try{w=new URL(b.url??"/","http://localhost")}catch{On(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let g=cf(w.pathname);if(!g){if(w.pathname.startsWith(Zo)){On(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let x=!1;(async()=>{let R=w.searchParams.get("token")??"",A=null;try{A=R===""?null:await e.verifyToken(R,g.laneId,g.docName)}catch{A=null}if(A===null){On(f,401,"invalid or missing lane doc token");return}let T=A;if(T.tenant!==void 0&&e.laneTenantOf){let O=null;try{O=await e.laneTenantOf(g.laneId)}catch{O=null}if(O==null||O==="")e.onLaneTenantMissing?.();else if(T.tenant!==O){On(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(x=!0,n.handleUpgrade(b,f,m,O=>{d.delete(f),r.add(O),O.on("close",()=>r.delete(O));let C=T.scope===uu||T.scope===void 0&&typeof T.app=="string"&&typeof T.fn=="string"&&T.aud==="sfu";if(C){let H=`${g.laneId}/${g.docName}`,W=(o.get(H)??0)+1;y(g.laneId,g.docName,W),W>1&&g.docName===ku&&e.hostRegistry?.setHost(g.laneId,e.selfAddress).catch(()=>{})}O.on("close",()=>{if(!C)return;let H=`${g.laneId}/${g.docName}`;y(g.laneId,g.docName,Math.max(0,(o.get(H)??1)-1))}),Su(O,b,{docName:`${g.laneId}/${g.docName}`,gc:!0})}))})().catch(()=>{!x&&!f.destroyed&&On(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",I),{async close(){p=!0,t.off("upgrade",I);for(let f of[...l.keys()])v(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let m=r.size+d.size,w=()=>{m-=1,m<=0&&f()};for(let g of r)g.once("close",w);for(let g of d)g.once("close",w);for(let g of r)g.close(1001,"lane doc host shutting down");for(let g of d)g.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(b,f){return Qo(`${b}/${f}`,!0)},isHosted(b){return i(b)>0},onHostedChange(b,f){let m=u.get(b);return m||(m=new Set,u.set(b,m)),m.add(f),f(i(b)>0),()=>{m.delete(f)}}}}k();var pf="urun:catalog:v1";function Au(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let u=await t.redis.hgetall(pf),l=[];for(let d of Object.values(u))try{l.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
77
+ `)}return r=l,o=n(),l},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var Yu=Re(require("ioredis"),1);k();var Pr=require("@urun-sh/core"),Fe=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Qt=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function In(t){let e=(t??"").trim();if(e==="")throw new Fe("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Fe("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var ff=60,mf=6e4,gf=4096;function hf(t){return t===401||t===403}var Tr=class{constructor(e){this.opts=e;this.mint=e.mint??Pr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Fe("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<mf)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:ff})).orgId}catch(o){throw o instanceof Pr.ClientTokenError&&hf(o.status)?(this.cache.delete(e),new Fe("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Qt("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Qt("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=gf){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};k();var Tn=require("crypto");k();var Pe=require("@urun-sh/core");k();async function Ou(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}k();var Iu=require("@urun-sh/core"),es=2;function yf(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function wf(t){let e=t?.type;return e==="response.completed"||e==="error"}function Tu(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=es;i++){let{app:a,entry:u,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(u)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(u,n);for await(let y of p){if(wf(y)&&(d=!0),yf(y)){if(i>1)continue}else c=!0;yield y}}catch(p){if(p instanceof Iu.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,u,p)}catch{}throw p}if(i<es&&!c){await t.evict(a,u);continue}throw p}if(d)return;if(i<es&&!c){await t.evict(a,u);continue}return}})()}}var $u=require("crypto");k();var _f="audio";var Pu=new WeakMap;function Cu(t,e,n){let r=t.doc(_f),o=[],s=0,i=0;return{sessionId:e,appendInputAudio(a){let u=Buffer.from(a,"base64");if(u.byteLength===0||(o.push(u),s+=u.byteLength,s<4800))return;let l=Buffer.concat(o,s).toString("base64");if(o=[],s=0,n===void 0){let d=(Pu.get(t)??0)+1;Pu.set(t,d),r.set({frames:{[String(d%32)]:{s:d,pcm16:l}}})}else{let d=++i;r.set({frames:{[`${n}:${d%32}`]:{s:d,pcm16:l,c:n}}})}},onOutputAudio(){return()=>{}}}}var bf=0,Sf=4,kf=4;function Nu(t,e){let n=(i,a)=>{let u=(t[i]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):bf;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Sf));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",kf),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Lu(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Uu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=v=>({session:v,responses:new Ot(v),gone:Ar(v,n)});if(i.lane==="jwt"){let v=(0,Pe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Lu(v,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,y=(typeof t.subject=="function"?t.subject():t.subject)??(0,$u.randomUUID)(),h=(0,Pe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Pe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:y,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Lu(h,e.appSlug,a,l))}function Rf(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function Du(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var xf=new Set(["error","paused"]);function ts(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Uu(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new Nn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Fs({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Ou(n):null),listPrices:n?()=>Rs(n):null,shared:e.lane==="api-key"?()=>_s({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Rf});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ut({appSlug:t.defaultApp}))),s}function Fu(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,a=d=>{process.stderr.write(`[decision-pool] ${d}
78
+ `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let y=new Zn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let v=Uu(t,d,c,{concurrencyKey:h.concurrencyKey});return v.gone.onGone(()=>y.markSessionDead(v)),await Lr(v.session),a(`slot attached pool=${c} slot=${h.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,v)=>a(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${v}`),terminalOpenFailure:h=>h instanceof Pe.SessionFailedError&&Du(h)});return s.set(c,{target:d,env:n}),o.set(c,y),y},l=async(d,c)=>{let p=s.get(c);if(p)try{let y=await e.poolTuningFor(d);u(d,c).retune({min:y?.min??p.env.min,max:y?.max??p.env.max,inFlightCap:y?.in_flight_cap??p.env.inFlightCap,idleGraceMs:y?.idle_grace_s!==void 0?y.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:y?.warm_wait_s!==void 0?y.warm_wait_s*1e3:void 0})}catch(y){a(`pool tuning refresh failed pool=${c} reason=${y instanceof Error?y.message:String(y)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,ut(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=ut(c),y=u(c,p);await l(c,p);let h=await y.acquire({timeoutMs:y.requestWaitMs}),v=i.get(h.entry)??[];return v.push(h),i.set(h.entry,v),{app:p,entry:h.entry,identity:$n(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,ut(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Ef(t){return(0,Pe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Pe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Pe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Pe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Lr(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Ef(t.phase),signal:e})}async function Mu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Cr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ns(t,e=xi,n,r,o=bo,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let m=f.session.id;return typeof m=="string"&&m.length>0?m:null},p="lane",y=f=>{let m=Un(f);if(!s||!m||m.app!==p)return null;let w=s.entryFor(m.key);if(!w)throw new X(`the lane behind this handle (${m.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:m.key,entry:w}},h=async f=>y(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let m=i.get(f);if(!m){let w={waiting:0,gone:new AbortController};d.set(f,w),m=(async()=>{if(await Lr(f.session,w.gone.signal),w.gone.signal.aborted)throw Cr(w.gone.signal);d.get(f)===w&&d.delete(f);let g=await ki(f.session,await e());return Object.assign(g,{sessionId:f.session.id})})(),i.set(f,m),m.catch(()=>{i.get(f)===m&&i.delete(f)}),m.then(()=>{d.get(f)===w&&d.delete(f)},()=>{d.get(f)===w&&d.delete(f)})}return m},I=f=>{let m=l.get(f);return m||(m=(async()=>{let w=await v(f);return{appendInputAudio:g=>w.appendInputAudio(g),onOutputAudio:g=>w.onOutputAudio(g),sessionId:c(f)}})(),l.set(f,m),m.catch(()=>{l.get(f)===m&&l.delete(f)})),m},b=async(f,m,w)=>{if(w?.aborted){let R=d.get(f);throw(i.get(f)===void 0||R!==void 0&&R.waiting===0)&&await Mu(f.session),Cr(w)}let g=m(f),x=d.get(f);return x!==void 0&&x.waiting++,w===void 0?g:new Promise((R,A)=>{let T=()=>{x!==void 0&&--x.waiting===0&&d.get(f)===x&&(x.gone.abort(),d.delete(f),i.delete(f),l.delete(f),Mu(f.session).catch(()=>{})),A(Cr(w))};w.addEventListener("abort",T,{once:!0});let O=()=>w.removeEventListener("abort",T);g.then(C=>{O(),R(C)},C=>{O(),A(C)})})};return{createResponse:Tu({sessionFor:s?async f=>{let m=await t.resolveTargetFor(f);if(m.sharedApp){let w=await s.sessionFor(f,m);return{app:w.app,entry:w.entry,identity:w.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,m)=>{s&&s.owns(m)?s.evict(m):r?r.evict(m):t.evict(f,m)},onAdmissionVerdict:(f,m,w)=>{Du(w)&&(s&&s.owns(m)?s.evict(m):r?r.markSessionDead(m):t.evict(f,m),n?.(f,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,m)=>{try{await Lr(f.session);let w=na(zo(await f.responses.responses.create(m),f.gone),o);if(!r&&!s)return w;let g=f;return(async function*(){try{yield*w}catch(R){throw ra(R)&&(s&&s.owns(g)?s.evict(g):r&&(R instanceof X?r.markSessionDead(g):r.evict(g))),R}finally{s&&s.owns(g)?s.release(g):r?.end(g)}})()}catch(w){throw s&&s.owns(f)?s.release(f):r&&r.end(f),w}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,m)=>t.supportsImages(f,m),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,m)=>{let{entry:w}=await t.sessionFor(f);return await b(w,v,m)},openAudioOn:async(f,m,w)=>{let g=y(f);if(g)return Cu(g.entry.session,g.laneId,w);let{entry:x}=await t.sessionForHandle(f);return await b(x,I,m)},openTurnsOn:async function*(f,m){if(m?.aborted)throw Cr(m);let w=await h(f);yield*Ns(w.session,m)},openVideo:async f=>{let{entry:m}=await t.sessionFor(f),w=a.get(m);return w||(w=Ri(m.session),a.set(m,w)),w},openVideoOut:async f=>{let{entry:m}=await t.sessionFor(f),w=u.get(m);return w||(w=Ai(m.session),u.set(m,w)),w},sessionHandle:async f=>{if(s){let m=await t.resolveTargetFor(f);if(m.sharedApp){let w=await s.sessionFor(f,m),g=c(w.entry);if(g===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Mn(p,g)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let m=Un(f);if(!s||m?.app!==p)return;let w=s.entryFor(m.key);w&&s.release(w)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:m,entry:w}=await t.sessionForHandle(f);await t.evict(m,w)},createResponseOn:async(f,m,w)=>{let g=await h(f);await Lr(g.session);let x=w!==void 0&&y(f)?new Ot({...g.session,consumerId:w}):g.responses;return zo(await x.responses.create(m),g.gone)},onSessionEnd:async(f,m)=>{let w=y(f);if(w)return w.entry.gone.onGone(A=>m({timeLeftMs:null,reason:A.message}));let{entry:g}=await t.sessionForHandle(f),x=g.session;if(typeof x.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let R=!1;return x.onPhase(A=>{if(R||!xf.has(A.name))return;R=!0;let T=x.endsAt??null;m({timeLeftMs:T?Math.max(0,T.getTime()-Date.now()):null,reason:A.reason??`session ${A.name}`})})}}}k();var Hu=require("http");var Af="/pooler/v1/inference",Zt=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Of=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},If=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},ju=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Tf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await ju(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Zt(t.status,e,n,t.retryAfterSeconds)};async function Pf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Af}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Of(e),firstMessage:If(e)}});return new Promise((a,u)=>{let l=(0,Hu.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});l.on("error",d=>u(new Zt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var Bu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Cf(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
64
79
 
65
- `)),d.end()})}}var Fe=(t,e)=>Object.assign(new Error(e),{status:t});function la(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function da(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ac='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ca(t,e,n,r){if(!t.supportsAudio)throw Fe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(l){throw l instanceof Y?Fe(404,l.message):l}if(!o)throw Fe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw Fe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(l){throw l instanceof Y?Fe(404,l.message):l}if(i&&!t.openTurnsOn)throw Fe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let l;try{l=await t.transcriptStreamFor(e)}catch(d){throw d instanceof Y?Fe(404,d.message):d}if(l!=="stt")throw Fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(l)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ac}`);if(r==="transcription"&&!i)throw Fe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},u={clients:{createResponse:async l=>await t.createResponseOn(s,l)},voice:o,audioSession:a};return i&&(u.turns=l=>t.openTurnsOn(s,l)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}x();var Kn=require("@urun-sh/core"),Ie=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Tt=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function en(t){let e=(t??"").trim();if(e==="")throw new Ie("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Ie("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var uc=60,lc=6e4,dc=4096;function cc(t){return t===401||t===403}var Jn=class{constructor(e){this.opts=e;this.mint=e.mint??Kn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Ie("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<lc)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:uc})).orgId}catch(o){throw o instanceof Kn.ClientTokenError&&cc(o.status)?(this.cache.delete(e),new Ie("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Tt(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Tt("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=dc){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};x();var rr=require("crypto");x();var Ae=require("@urun-sh/core");x();x();x();x();function pa(t,e,n,r){let o=t.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function fa(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}x();x();function ma(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var pc="llm-resp";async function*oo(t,e){let n=`${pc}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let i of t.stream(n).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,l=o.get(u)??{};a.id&&(l.id=a.id),a.function?.name&&(l.name=a.function.name),o.set(u,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:l.id,name:l.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...s.body}};return}else if(s.t==="error"){yield ma(s);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Yn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,i)=>{let s=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{s(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=fa(e,n,this.consumerId);return this.write(r),oo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=pa(e,n,r,this.consumerId);return this.write(o),oo(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var ha=0;function fc(){return ha+=1,`req_${Date.now().toString(36)}_${ha.toString(36)}`}var Xn=class{transport;constructor(e){this.transport=new Yn(e)}responses={create:async e=>{let n=fc(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();async function ga(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}x();var ya=require("@urun-sh/core"),io=2;function mc(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function hc(t){let e=t?.type;return e==="response.completed"||e==="error"}function _a(t){return async function(n,r){return(async function*(){for(let i=1;i<=io;i++){let{app:s,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let l=!1,d=!1;try{let c=await t.createStream(a,n);for await(let y of c){if(hc(y)&&(l=!0),mc(y)){if(i>1)continue}else d=!0;yield y}}catch(c){if(c instanceof ya.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(s,a,c)}catch{}throw c}if(i<io&&!d){await t.evict(s,a);continue}throw c}if(l)return;if(i<io&&!d){await t.evict(s,a);continue}return}})()}}var Sa=require("crypto");x();var gc=3,yc="llm",_c=new Set(["paused","error"]);function wa(t,e){let n=t.doc(yc),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,s=!1,a=new Set,u=[],l=d=>{if(!i){i=d;for(let c of[...a])c(d);a.clear()}};return r&&u.push(n.onConnectionState(d=>{s&&(d.consecutiveFailures<gc||l(new re(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(d=>{if(d.name==="live"){s=!0;return}s&&_c.has(d.name)&&l(new re(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(d){return i?(d(i),()=>{}):(a.add(d),()=>a.delete(d))},dispose(){a.clear();for(let d of u.splice(0))d()}}}async function*so(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,i=new Promise((s,a)=>{o=e.onGone(u=>a(u))});i.catch(()=>{});try{for(;;){let s=await Promise.race([r.next(),i]);if(s.done)return;yield s.value}}finally{o?.(),r.return?.(void 0)}}var vc=1,bc=4,Sc=4;function ka(t,e){let n=(s,a)=>{let u=(t[s]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${s} must be a positive integer (got ${JSON.stringify(t[s])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):vc;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let i=n("URUN_DECISION_POOL_MAX",Math.max(o,bc));return{min:o,max:i,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Sc),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function va(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let i=r?o(void 0,r):o();if(typeof i.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return i}function Ra(t,e,n,r){let{baseUrl:o,orgId:i,auth:s}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=w=>({session:w,responses:new Xn(w),gone:wa(w,n)});if(s.lane==="jwt"){let w=(0,Ae.App)(e.appSlug,{baseUrl:o,orgId:i,jwt:s.jwt});return d(va(w,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:y}=s,f=(typeof t.subject=="function"?t.subject():t.subject)??(0,Sa.randomUUID)(),p=(0,Ae.App)(e.appSlug,{baseUrl:o,orgId:i,getAccessToken:async()=>(await(0,Ae.createClientToken)(c,{baseUrl:y,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:f,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(va(p,e.appSlug,a,l))}function kc(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function Rc(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var xc=new Set(["error","paused"]);function ao(t){let{auth:e,catalog:n}=t,r=null,o=(s,a)=>{let u=Ra(t,s,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},i=new an({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async s=>{if(s.gone.dispose(),t.release==="detach"){if(typeof s.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');s.session.detach();return}await s.session.end()},listApps:e.lane==="api-key"?()=>Xo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>ga(n):null,listPrices:n?()=>Mo(n):null,shared:e.lane==="api-key"?()=>Io({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:kc});return r=i,t.defaultApp!==null&&i.seed(t.defaultApp,o({appSlug:t.defaultApp},ze({appSlug:t.defaultApp}))),i}function xa(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,i=new Map,s=u=>{process.stderr.write(`[decision-pool] ${u}
66
- `)},a=(u,l)=>{let d=o.get(l);if(d)return d;let c=new Cn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async y=>{let f=Ra(t,u,l,{concurrencyKey:y.concurrencyKey});return f.gone.onGone(()=>c.evict(f)),await Zn(f.session),s(`slot attached pool=${l} slot=${y.concurrencyKey} session=${f.session.id??"(no id)"}`),f},closeSlot:async y=>{y.gone.dispose(),await y.session.end()},onDetach:(y,f)=>s(`slot detached pool=${l} slot=${y.concurrencyKey} reason=${f}`)});return o.set(l,c),c};return{async boot(){if(t.defaultApp===null)return;let u={appSlug:t.defaultApp};await a(u,ze(u)).boot()},async sessionFor(u){let l=await e.resolveTargetFor(u),d=ze(l),c=a(l,d).tryAcquireReady();if(!c)throw new lt(a(l,d).stats().lastMissAgeMs);let y=i.get(c.entry)??[];return y.push(c),i.set(c.entry,y),{app:d,entry:c.entry,identity:sn(l)}},async warmFor(u){let l=await e.resolveTargetFor(u);await a(l,ze(l)).boot()},end(u){let l=i.get(u)?.shift();l&&(i.get(u)?.length===0&&i.delete(u),l.release())},evict(u){for(let l of o.values())l.evict(u)},reap(){for(let u of o.values())u.reap()},async pingReady(u){for(let l of o.values())if(await l.pingReady(u))return!0;return!1},stats(){return[...o.entries()].map(([u,l])=>({poolKey:u,...l.stats()}))},async drain(u){await Promise.all([...o.values()].map(l=>l.drain({timeoutMs:u})))},async close(){await Promise.all([...o.values()].map(u=>u.close()))}}}function Ec(t){return(0,Ae.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ae.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ae.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ae.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Zn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Ec(t.phase),signal:e})}async function ba(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Qn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function uo(t,e=Ni,n,r,o=Yr){let i=new WeakMap,s=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=p=>{let w=p.session.id;return typeof w=="string"&&w.length>0?w:null},c=p=>{let w=i.get(p);if(!w){let _={waiting:0,gone:new AbortController};l.set(p,_),w=(async()=>{if(await Zn(p.session,_.gone.signal),_.gone.signal.aborted)throw Qn(_.gone.signal);l.get(p)===_&&l.delete(p);let b=await Li(p.session,await e());return Object.assign(b,{sessionId:p.session.id})})(),i.set(p,w),w.catch(()=>{i.get(p)===w&&i.delete(p)}),w.then(()=>{l.get(p)===_&&l.delete(p)},()=>{l.get(p)===_&&l.delete(p)})}return w},y=p=>{let w=u.get(p);return w||(w=(async()=>{let _=await c(p);return{appendInputAudio:b=>_.appendInputAudio(b),onOutputAudio:b=>_.onOutputAudio(b),sessionId:d(p)}})(),u.set(p,w),w.catch(()=>{u.get(p)===w&&u.delete(p)})),w},f=async(p,w,_)=>{if(_?.aborted){let h=l.get(p);throw(i.get(p)===void 0||h!==void 0&&h.waiting===0)&&await ba(p.session),Qn(_)}let b=w(p),k=l.get(p);return k!==void 0&&k.waiting++,_===void 0?b:new Promise((h,A)=>{let R=()=>{k!==void 0&&--k.waiting===0&&l.get(p)===k&&(k.gone.abort(),l.delete(p),i.delete(p),u.delete(p),ba(p.session).catch(()=>{})),A(Qn(_))};_.addEventListener("abort",R,{once:!0});let v=()=>_.removeEventListener("abort",R);b.then(O=>{v(),h(O)},O=>{v(),A(O)})})};return{createResponse:_a({sessionFor:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>d(p),evict:(p,w)=>{r?r.evict(w):t.evict(p,w)},onAdmissionVerdict:(p,w,_)=>{Rc(_)&&(r?r.evict(w):t.evict(p,w),n?.(p,_.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,w)=>{try{await Zn(p.session);let _=ea(so(await p.responses.responses.create(w),p.gone),o);if(!r)return _;let b=p;return(async function*(){try{yield*_}catch(h){throw ta(h)&&r.evict(b),h}finally{r.end(b)}})()}catch(_){throw r&&r.end(p),_}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,w)=>t.supportsImages(p,w),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,w)=>{let{entry:_}=await t.sessionFor(p);return await f(_,c,w)},openAudioOn:async(p,w)=>{let{entry:_}=await t.sessionForHandle(p);return await f(_,y,w)},openTurnsOn:async function*(p,w){if(w?.aborted)throw Qn(w);let{entry:_}=await t.sessionForHandle(p);yield*Wo(_.session,w)},openVideo:async p=>{let{entry:w}=await t.sessionFor(p),_=s.get(w);return _||(_=$i(w.session),s.set(w,_)),_},openVideoOut:async p=>{let{entry:w}=await t.sessionFor(p),_=a.get(w);return _||(_=Di(w.session),a.set(w,_)),_},sessionHandle:async p=>(await t.handleFor(p)).handle,speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:w,entry:_}=await t.sessionForHandle(p);await t.evict(w,_)},createResponseOn:async(p,w)=>{let{entry:_}=await t.sessionForHandle(p);return await Zn(_.session),so(await _.responses.responses.create(w),_.gone)},onSessionEnd:async(p,w)=>{let{entry:_}=await t.sessionForHandle(p),b=_.session;if(typeof b.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let k=!1;return b.onPhase(h=>{if(k||!xc.has(h.name))return;k=!0;let A=b.endsAt??null;w({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})}}}var Oc=512;function lo(t){return`urun-inference-proxy-${(0,rr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var er=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:xr,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ka(process.env,process.env.HOSTNAME)??void 0},r=ao(n),o=n.decisionPool?xa(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(uo(r,void 0,void 0,o??void 0),e),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Oc;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ea=512,Ic=1024,tr=class extends Error{constructor(){super(`conversation capacity reached (${Ea} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Ac(t){return{sessionStartOptions:e=>{if(e.startsWith($t))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith($t)||t.set(e,n)}}}function Tc(t,e,n,r){let o=ao({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:xr,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...Ac(r)});return{clients:uo(o),release:async()=>{await o.closeAll()}}}var nr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${lo(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Tc(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Ea;){let e=this.byCaller.keys().next();if(e.done)throw new tr;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new tr;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,rr.randomUUID)())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),createResponseOn:(s,a)=>o().backhaul.clients.createResponseOn(s,a),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(s,a)},i.openTurnsOn=(s,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Ic;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==e.apiKey)throw new re("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};x();var or="/inference-usage",Oa=25e3;var Pc=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ia(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Pc.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var ir=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${or}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Oa)})}catch(s){throw new oe(`the uRun usage surface (POST ${or}) could not be reached within ${Oa}ms: ${Ia(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Ie("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new oe(`the uRun usage surface (POST ${or}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new oe(`the uRun usage surface (POST ${or}) answered HTTP ${o.status} with a body that is not JSON: ${Ia(s)}`)}return ki(i,this.opts.onRejectedRow)}};x();var Cc="/inference-ledger",Mc=1e4,sr=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},fo=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ye=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},mo=class extends Ie{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ho=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Lc=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",co],["output_minutes",co],["cost_nano_usd",co],["price_version",t=>t===null||typeof t=="string"]];function $c(t){for(let[e,n]of Lc){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Nc(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:$c(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function co(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function po(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Uc(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Aa(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Dc(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Aa(t.started_at,n.started_at)&&Aa(t.completed_at,n.completed_at)&&po(t.prompt_tokens,n.prompt_tokens)&&po(t.completion_tokens,n.completion_tokens)&&po(t.output_units,n.output_units)&&Uc(t.output_minutes,n.output_minutes)}function Fc(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v1",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(n),t.started_at,t.completed_at].join(`
67
- `)}async function Bc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Fc(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function jc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ye(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new ye(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ye(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new ye(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=l=>{if(!(l in n))throw new ye(`${e} answered a row with no ${l} field: ${JSON.stringify(t)}`);let d=n[l];if(d===null)return null;if(typeof d!="string")throw new ye(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ye(`${e} answered a BLANK ${l} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},s=i("price_version"),a=i("unpriced_reason"),u=o!=null;if(u&&(s===null||a!==null))throw new ye(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new ye(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var ar=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Cc}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Bc(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new ye(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Mc)})}catch(l){throw new ye(`the uRun ledger surface at ${r} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(i.status===409){let l=await i.text().catch(()=>""),d=Nc(l);throw d.status==="found"&&Dc(n,d.row)?new fo(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new sr(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new sr(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${l.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new mo("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!i.ok){let l=await i.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(l);if(c!==null&&typeof c=="object"&&"error"in c){let y=c.error;y!==null&&typeof y=="object"&&"code"in y&&(d=y.code)}}catch{}throw d==="ledger_signature_invalid"?new ho(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+l.slice(0,400)):new ye(`the uRun ledger surface at ${r} answered HTTP ${i.status}: ${l.slice(0,400)}`)}let s;try{s=await i.json()}catch(l){throw new ye(`the uRun ledger surface at ${r} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=s?.recorded;if(a===void 0)throw new ye(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=jc(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new ye(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var qc=5e3,Hc=1e3,Gc=1500,Vc=3e3,Wc="/api/client-tokens";function go(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ta(t,e,n,r){go(t,e,{error:{message:n,type:r}})}async function Jc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Wc}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Vc)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Ca(t){let e=t.resolver??new Jn({gatewayUrl:t.baseUrl}),n=t.registry??new er({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Jc(t.baseUrl)),o=async()=>{let h=null;for(let v of n.decisionPools()){h=v;break}if(!h)return null;let A=h.stats();if(A.some(v=>v.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(v=>v.attached===0&&v.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await h.pingReady(Gc);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},i=t.usageClient??new ir({apiUrl:t.apiUrl}),s=t.ledgerClient??new ar({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),a=process.env.URUN_SHARED_ORG_ID?.trim(),u=process.env.URUN_SHARED_ORG_API_KEY?.trim();a&&u&&(async()=>{try{await n.decisionWarmerFor({orgId:a,apiKey:u})?.warmFor(ro)}catch(h){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(h instanceof Error?h.message:h)}
68
- `)}})();let l=new yn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async h=>e.resolve(en(h.headers.authorization)),c=h=>h instanceof Ie?{status:h.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:h instanceof Tt?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,y=ua({clients:async h=>n.clientsFor(await d(h)),usage:{authorize:h=>en(h.headers.authorization),lookup:(h,A)=>i.lookup(h,A)},statusOf:c,...t.requestLog?{requestLog:t.requestLog}:{},observe:h=>l.observe(h),ledger:{write:(h,A)=>s.write(en(h.headers.authorization),A),observe:h=>l.observeLedger(h),...t.ledgerLog?{report:t.ledgerLog}:{}}}),f=null,p=null,w=(0,Pa.createServer)((h,A)=>{let R=new URL(h.url??"/","http://localhost");(async()=>{if(h.method==="GET"&&R.pathname==="/healthz"){go(A,200,{ok:!0});return}if(h.method==="GET"&&R.pathname==="/readyz"){let j=Date.now();if((!f||j-f.at>=qc)&&(f={at:j,...await r()}),!p||j-p.at>=Hc){let H=await o();p=H===null?{at:j,ok:!0,detail:null}:{at:j,ok:H.ok,detail:H.detail}}let C=(f?.ready??!1)&&p.ok,D=p.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${p.detail}`;go(A,C?200:503,{ok:C,control_plane:D});return}let v=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),O=R.pathname.startsWith("/partners/");if(!v&&!O){Ta(A,404,`no route for ${h.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}y(h,A)})().catch(v=>{if(!A.headersSent){Ta(A,500,String(v instanceof Error?v.message:v),"proxy_error");return}A.end()})}),_=t.conversations??new nr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),b=[Tr(w,{authenticate:async h=>{let A=await e.resolve(h),R=_.connectionFor(A);return{clients:R.clients,scope:lo(A.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),Dr(w,{clients:async h=>n.clientsFor(await d(h)),statusOf:c}).close,Pn(w,{resolver:{resolve:async(h,A)=>{let R=await e.resolve(en(h.headers.authorization)),v=_.connectionFor(R),O;try{O=await ca(v.clients,la(h),A,da(h))}catch(j){throw v.release().catch(()=>{}),j}return{...O,release:v.release}}}})];w.on("upgrade",(h,A)=>{let R=new URL(h.url??"/","http://localhost");R.pathname===Sn||R.pathname===Nr||R.pathname===Jt||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
80
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Bu(s);i!==null&&(yield i)}let n=Bu(e);n!==null&&(yield n)}async function qu(t,e,n,r){let o=kr(e,n,r),s=o.model??"";if(s==="")throw new Zt(400,"missing_model","the pooler submit requires a model");let i=await Pf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Tf(i);let a=e.stream===!0?xr(n,Cf(i)):await Lf(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Lf(t,e){let n=await ju(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Zt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return xr(e,(async function*(){yield o})())}var Mf=512;function rs(t){return`urun-inference-proxy-${(0,Tn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Mr=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){let r=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${(0,Tn.randomUUID)()}`;return qu(o,s,a,a)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:lo,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Nu(process.env,process.env.HOSTNAME)??void 0},r=ts(n),o=n.decisionPool?Fu(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ns(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Mf;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Gu=512,$f=1024,$r=class extends Error{constructor(){super(`conversation capacity reached (${Gu} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Nf(t){return{sessionStartOptions:e=>{if(e.startsWith(an))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(an)||t.set(e,n)}}}function Uf(t,e,n,r){let o=ts({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:lo,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Nf(r)});return{clients:ns(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Nr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${rs(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Uf(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Gu;){let e=this.byCaller.keys().next();if(e.done)throw new $r;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new $r;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,Tn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,u)=>o().backhaul.clients.createResponseOn(i,a,u),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async(i,a,u)=>{let l=o().backhaul.clients.openAudioOn;if(l===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return l(i,a,u)},s.openTurnsOn=(i,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(i,a)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},s.supportsTranscription=async i=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(i)},s.transcriptStreamFor=async i=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=$f;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==e.apiKey)throw new X("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};k();var Ur="/inference-usage",Vu=25e3;var Df=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Wu(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Df.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Dr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ur}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Vu)})}catch(i){throw new fe(`the uRun usage surface (POST ${Ur}) could not be reached within ${Vu}ms: ${Wu(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Fe("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new fe(`the uRun usage surface (POST ${Ur}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new fe(`the uRun usage surface (POST ${Ur}) answered HTTP ${o.status} with a body that is not JSON: ${Wu(i)}`)}return pi(s,this.opts.onRejectedRow)}};k();var Ff="/inference-ledger",Bf=1e4,Fr=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},is=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ke=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},as=class extends Fe{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},us=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Hf=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",os],["output_minutes",os],["cost_nano_usd",os],["price_version",t=>t===null||typeof t=="string"]];function jf(t){for(let[e,n]of Hf){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function qf(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:jf(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function os(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ss(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Gf(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ju(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Vf(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Ju(t.started_at,n.started_at)&&Ju(t.completed_at,n.completed_at)&&ss(t.prompt_tokens,n.prompt_tokens)&&ss(t.completion_tokens,n.completion_tokens)&&ss(t.output_units,n.output_units)&&Gf(t.output_minutes,n.output_minutes)}function Wf(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
81
+ `)}async function Jf(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Wf(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Kf(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ke(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new ke(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ke(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new ke(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=l=>{if(!(l in n))throw new ke(`${e} answered a row with no ${l} field: ${JSON.stringify(t)}`);let d=n[l];if(d===null)return null;if(typeof d!="string")throw new ke(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ke(`${e} answered a BLANK ${l} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new ke(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new ke(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var Br=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ff}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Jf(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new ke(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Bf)})}catch(l){throw new ke(`the uRun ledger surface at ${r} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(s.status===409){let l=await s.text().catch(()=>""),d=qf(l);throw d.status==="found"&&Vf(n,d.row)?new is(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new Fr(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new Fr(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${l.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new as("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let l=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(l);if(c!==null&&typeof c=="object"&&"error"in c){let p=c.error;p!==null&&typeof p=="object"&&"code"in p&&(d=p.code)}}catch{}throw d==="ledger_signature_invalid"?new us(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+l.slice(0,400)):new ke(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${l.slice(0,400)}`)}let i;try{i=await s.json()}catch(l){throw new ke(`the uRun ledger surface at ${r} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=i?.recorded;if(a===void 0)throw new ke(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=Kf(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new ke(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var zf=5e3,Yf=1e3,Xf=1500,Qf=3e3,Zf="/api/client-tokens";function Hr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ku(t,e,n,r){Hr(t,e,{error:{message:n,type:r}})}async function em(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Zf}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Qf)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Xu(t){let e=t.resolver??new Tr({gatewayUrl:t.baseUrl}),n=new Wn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),r=null,o=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let g=new Yu.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),x=Au({redis:g});return{registry:fu({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:yu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(A,T)=>r?.onHostedChange(A,T)??(()=>()=>{}),roomDoc:(A,T)=>{if(!r)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return r.roomDoc(A,T)},metrics:n,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(A,T)=>x.rows().then(O=>{let C=to(O,T);return C?.warm_wait_s!==void 0?C.warm_wait_s*1e3:void 0})}),catalog:x,redis:g}})(),s=t.registry??new Mr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry,pooler:t.pooler}),i=t.probeControlPlane??(()=>em(t.baseUrl)),a=async()=>{let g=null;for(let A of s.decisionPools()){g=A;break}if(!g)return null;let x=g.stats();if(x.some(A=>A.draining))return{ok:!1,detail:"decision pool draining"};if(x.every(A=>A.attached===0&&A.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await g.pingReady(Xf);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},u=t.usageClient??new Dr({apiUrl:t.apiUrl}),l=t.ledgerClient??new Br({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),d=process.env.URUN_SHARED_ORG_ID?.trim(),c=process.env.URUN_SHARED_ORG_API_KEY?.trim();d&&c&&(async()=>{try{await s.decisionWarmerFor({orgId:d,apiKey:c})?.warmFor(jo)}catch(g){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(g instanceof Error?g.message:g)}
82
+ `)}})();let p=async g=>e.resolve(In(g.headers.authorization)),y=g=>g instanceof Fe?{status:g.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:g instanceof Qt?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:g.detail}:null,h=Xa({clients:async g=>s.clientsFor(await p(g)),usage:{authorize:g=>In(g.headers.authorization),lookup:(g,x)=>u.lookup(g,x)},statusOf:y,...t.requestLog?{requestLog:t.requestLog}:{},observe:g=>n.observe(g),ledger:{write:(g,x)=>l.write(In(g.headers.authorization),x),observe:g=>n.observeLedger(g),...t.ledgerLog?{report:t.ledgerLog}:{}}}),v=null,I=null,b=(0,zu.createServer)((g,x)=>{let R=new URL(g.url??"/","http://localhost");(async()=>{if(g.method==="GET"&&R.pathname==="/healthz"){Hr(x,200,{ok:!0});return}if(g.method==="GET"&&R.pathname==="/readyz"){let O=Date.now();if((!v||O-v.at>=zf)&&(v={at:O,...await i()}),!I||O-I.at>=Yf){let H=await a();I=H===null?{at:O,ok:!0,detail:null}:{at:O,ok:H.ok,detail:H.detail}}let C=(v?.ready??!1)&&I.ok,P=I.detail===null?v?.detail??"control plane not yet probed":`${v?.detail??"control plane not yet probed"}; ${I.detail}`;Hr(x,C?200:503,{ok:C,control_plane:P});return}if(g.method==="GET"&&R.pathname==="/lanez"){Hr(x,200,{pools:o?await o.registry.status():null});return}let A=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),T=R.pathname.startsWith("/partners/");if(!A&&!T){Ku(x,404,`no route for ${g.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}h(g,x)})().catch(A=>{if(!x.headersSent){Ku(x,500,String(A instanceof Error?A.message:A),"proxy_error");return}x.end()})}),f=t.conversations??new Nr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry}),m=[go(b,{authenticate:async g=>{let x=await e.resolve(g),R=f.connectionFor(x);return{clients:R.clients,scope:rs(x.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),Eo(b,{clients:async g=>s.clientsFor(await p(g)),statusOf:y}).close,lr(b,{resolver:{resolve:async(g,x)=>{let R=await e.resolve(In(g.headers.authorization)),A=f.connectionFor(R),T;try{T=await nu(Vo(A.clients,t.realtimeCompanions),eu(g),x,tu(g))}catch(C){throw A.release().catch(()=>{}),C}let O=T.release;return{...T,release:async()=>{await O?.(),await A.release()}}}}})];if(t.lane&&o){let g=t.lane,x=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;r=Eu(b,{verifyToken:(A,T)=>du(A,T,g.tokenSecret,void 0,x),selfAddress:g.selfAddress,laneTenantOf:A=>o.redis.get(`lane_tenant:${A}`),onLaneTenantMissing:()=>n.observeLaneDocTenantMissing(),previousTokenSecret:x,hostRegistry:{setHost:(A,T)=>o.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${A}`,T,String(xu)),delHost:A=>o.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${A}`,g.selfAddress)}});let R=o;m.push(async()=>{await r.close(),await R.registry.close(),R.redis.quit().catch(()=>{})})}b.on("upgrade",(g,x)=>{let R=new URL(g.url??"/","http://localhost");R.pathname===Xn||R.pathname===Ro||R.pathname===bn||r!==null&&R.pathname.startsWith("/doc/")||x.destroyed||(x.write(`HTTP/1.1 404 Not Found\r
69
83
  Connection: close\r
70
84
  \r
71
- no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let k=async()=>{for(let h of b)await h();await _.detachAll()};return{server:w,metricsServer:Ei(l),metrics:l,edgeIdentityServer:Ai(),registry:n,closeAll:()=>n.closeAll(),closeWebSockets:k}}async function Ma(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await di()||ci(),await e()}function Kc(){let t=null;return t=ti({streams:Me.default,note:e=>{t?.isDead("stderr")!==!0&&Ne(Me.default.stderr,e)}}),t}async function zc(){Kc();let t=Ti(Me.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:i}=Ca(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,nt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(Sr,nt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(Rr,nt,a)}),Me.default.stdout.write(`inference-proxy listening on http://${nt}:${t.port}/v1 (metrics http://${nt}:${Sr}${mn}, edge identity http://${nt}:${Rr}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
72
- `);let s=async a=>{Me.default.stdout.write(`inference-proxy: ${a} \u2014 draining
73
- `),await Ma(e,o,i),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Me.default.once("SIGINT",()=>{s("SIGINT").finally(a)}),Me.default.once("SIGTERM",()=>{s("SIGTERM").finally(a)})})}zc().then(()=>Me.default.exit(0),t=>{Me.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
74
- `),Me.default.exit(1)});
85
+ no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),x.destroy())});let w=async()=>{for(let g of m)await g();await f.detachAll()};return{server:b,metricsServer:gi(n),metrics:n,edgeIdentityServer:wi(),registry:s,closeAll:()=>s.closeAll(),closeWebSockets:w}}async function Qu(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Zs()||ei(),await e()}function tm(){let t=null;return t=Gs({streams:Ke.default,note:e=>{t?.isDead("stderr")!==!0&&ze(Ke.default.stderr,e)}}),t}async function nm(){tm();let t=_i(Ke.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Xu(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,wt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(io,wt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(uo,wt,a)}),Ke.default.stdout.write(`inference-proxy listening on http://${wt}:${t.port}/v1 (metrics http://${wt}:${io}${qn}, edge identity http://${wt}:${uo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
86
+ `);let i=async a=>{Ke.default.stdout.write(`inference-proxy: ${a} \u2014 draining
87
+ `),await Qu(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Ke.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Ke.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}nm().then(()=>Ke.default.exit(0),t=>{Ke.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
88
+ `),Ke.default.exit(1)});
75
89
  /*! Bundled license information:
76
90
 
77
91
  reflect-metadata/Reflect.js: