@urun-sh/openai 0.6.42 → 0.6.44

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 (61) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
  3. package/dist/chunk-64VO62LW.js +1 -0
  4. package/dist/chunk-BA3NCMS5.js +6 -0
  5. package/dist/chunk-DMRZZTYI.js +4 -0
  6. package/dist/chunk-FNAZ2XBE.js +20 -0
  7. package/dist/chunk-G6AFKOVS.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-HB5KNEY5.js} +1 -1
  9. package/dist/chunk-J3KCHTSA.js +6 -0
  10. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  11. package/dist/chunk-VQSCBUKT.js +66 -0
  12. package/dist/{chunk-QTHFMDZY.js → chunk-X5BLQXHK.js} +1 -1
  13. package/dist/chunk-XNRPTMSL.js +1 -0
  14. package/dist/chunk-Y774TOE7.js +2 -0
  15. package/dist/{composite-B-F2J0NK.d.cts → composite-DM2sT1Sp.d.cts} +320 -4
  16. package/dist/{composite-B--rGI5m.d.ts → composite-DNNAm0PY.d.ts} +91 -4
  17. package/dist/gemini-live.cjs +2 -2
  18. package/dist/gemini-live.d.cts +4 -4
  19. package/dist/gemini-live.d.ts +4 -4
  20. package/dist/gemini-live.js +1 -1
  21. package/dist/hosted/bin.cjs +49 -47
  22. package/dist/hosted/bin.js +1 -1
  23. package/dist/hosted/index.cjs +45 -43
  24. package/dist/hosted/index.d.cts +54 -10
  25. package/dist/hosted/index.d.ts +11 -5
  26. package/dist/hosted/index.js +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.d.cts +4 -4
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.js +1 -1
  31. package/dist/pi-extension/index.cjs +7 -7
  32. package/dist/pi-extension/index.d.cts +2 -2
  33. package/dist/pi-extension/index.d.ts +2 -2
  34. package/dist/pi-extension/index.js +1 -1
  35. package/dist/pi-extension/standalone.cjs +55 -55
  36. package/dist/pooler/bin.cjs +40 -41
  37. package/dist/pooler/bin.js +39 -40
  38. package/dist/proxy/cli.cjs +55 -53
  39. package/dist/proxy/cli.js +1 -1
  40. package/dist/proxy/conformance-probe.cjs +1 -1
  41. package/dist/proxy/conformance-probe.js +1 -1
  42. package/dist/proxy/index.cjs +34 -32
  43. package/dist/proxy/index.d.cts +37 -214
  44. package/dist/proxy/index.d.ts +17 -65
  45. package/dist/proxy/index.js +1 -1
  46. package/dist/{translator-Dox25ky9.d.cts → translator-C6MpaZS-.d.cts} +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-CaOqL-V8.d.ts} +1 -1
  48. package/dist/{types-CHPtJx6d.d.cts → types-DiYzfHYN.d.cts} +2 -0
  49. package/dist/{types-CHPtJx6d.d.ts → types-DiYzfHYN.d.ts} +2 -0
  50. package/dist/{video-out-DnCKUUO2.d.cts → video-out-A8qMuI36.d.cts} +17 -3
  51. package/dist/{video-out-REmiQMBJ.d.ts → video-out-IoTqIbAw.d.ts} +6 -2
  52. package/package.json +2 -2
  53. package/dist/chunk-G7CSAISC.js +0 -1
  54. package/dist/chunk-GX243AIV.js +0 -1
  55. package/dist/chunk-HPUX2H65.js +0 -6
  56. package/dist/chunk-IFYB6QUQ.js +0 -64
  57. package/dist/chunk-KKCUIOL4.js +0 -1
  58. package/dist/chunk-OZ7HE3VG.js +0 -23
  59. package/dist/chunk-QNJKRB7Q.js +0 -2
  60. package/dist/chunk-XKCWX72M.js +0 -6
  61. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -1,101 +1,103 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ed=Object.create;var Gs=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var nd=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,od=Object.prototype.hasOwnProperty;var sd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var id=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var ad=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nd(e))!od.call(t,o)&&o!==n&&Gs(t,o,{get:()=>e[o],enumerable:!(r=td(e,o))||r.enumerable});return t};var ke=(t,e,n)=>(n=t!=null?ed(rd(t)):{},ad(e||!t||!t.__esModule?Gs(n,"default",{value:t,enumerable:!0}):n,t));var E=sd(()=>{"use strict"});var Vs=id(()=>{"use strict";E();var Ws;(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 co(Object.create(null))}:u?function(){return co({__proto__:null})}:function(){return co({})},has:l?function(v,R){return r.call(v,R)}:function(v,R){return R in v},get:l?function(v,R){return r.call(v,R)?v[R]:void 0}:function(v,R){return v[R]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:zl(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Yl(),m=typeof WeakMap=="function"?WeakMap:Xl(),_=o?Symbol.for("@reflect-metadata:registry"):void 0,S=Vl(),b=Jl(S);function A(v,R,C,L){if($(C)){if(!cn(v))throw new TypeError;if(!Us(R))throw new TypeError;return I(v,R)}else{if(!cn(v))throw new TypeError;if(!ie(R))throw new TypeError;if(!ie(L)&&!$(L)&&!re(L))throw new TypeError;return re(L)&&(L=void 0),C=Me(C),M(v,R,C,L)}}e("decorate",A);function f(v,R){function C(L,W){if(!ie(L))throw new TypeError;if(!$(W)&&!Gl(W))throw new TypeError;Te(v,R,L,W)}return C}e("metadata",f);function g(v,R,C,L){if(!ie(C))throw new TypeError;return $(L)||(L=Me(L)),Te(v,R,C,L)}e("defineMetadata",g);function y(v,R,C){if(!ie(R))throw new TypeError;return $(C)||(C=Me(C)),G(v,R,C)}e("hasMetadata",y);function k(v,R,C){if(!ie(R))throw new TypeError;return $(C)||(C=Me(C)),V(v,R,C)}e("hasOwnMetadata",k);function T(v,R,C){if(!ie(R))throw new TypeError;return $(C)||(C=Me(C)),Z(v,R,C)}e("getMetadata",T);function w(v,R,C){if(!ie(R))throw new TypeError;return $(C)||(C=Me(C)),Y(v,R,C)}e("getOwnMetadata",w);function O(v,R){if(!ie(v))throw new TypeError;return $(R)||(R=Me(R)),oe(v,R)}e("getMetadataKeys",O);function x(v,R){if(!ie(v))throw new TypeError;return $(R)||(R=Me(R)),Se(v,R)}e("getOwnMetadataKeys",x);function P(v,R,C){if(!ie(R))throw new TypeError;if($(C)||(C=Me(C)),!ie(R))throw new TypeError;$(C)||(C=Me(C));var L=pn(R,C,!1);return $(L)?!1:L.OrdinaryDeleteMetadata(v,R,C)}e("deleteMetadata",P);function I(v,R){for(var C=v.length-1;C>=0;--C){var L=v[C],W=L(R);if(!$(W)&&!re(W)){if(!Us(W))throw new TypeError;R=W}}return R}function M(v,R,C,L){for(var W=v.length-1;W>=0;--W){var we=v[W],be=we(R,C,L);if(!$(be)&&!re(be)){if(!ie(be))throw new TypeError;L=be}}return L}function G(v,R,C){var L=V(v,R,C);if(L)return!0;var W=lo(R);return re(W)?!1:G(v,W,C)}function V(v,R,C){var L=pn(R,C,!1);return $(L)?!1:Le(L.OrdinaryHasOwnMetadata(v,R,C))}function Z(v,R,C){var L=V(v,R,C);if(L)return Y(v,R,C);var W=lo(R);if(!re(W))return Z(v,W,C)}function Y(v,R,C){var L=pn(R,C,!1);if(!$(L))return L.OrdinaryGetOwnMetadata(v,R,C)}function Te(v,R,C,L){var W=pn(C,L,!0);W.OrdinaryDefineOwnMetadata(v,R,C,L)}function oe(v,R){var C=Se(v,R),L=lo(v);if(L===null)return C;var W=oe(L,R);if(W.length<=0)return C;if(C.length<=0)return W;for(var we=new h,be=[],X=0,U=C;X<U.length;X++){var F=U[X],H=we.has(F);H||(we.add(F),be.push(F))}for(var B=0,ee=W;B<ee.length;B++){var F=ee[B],H=we.has(F);H||(we.add(F),be.push(F))}return be}function Se(v,R){var C=pn(v,R,!1);return C?C.OrdinaryOwnMetadataKeys(v,R):[]}function J(v){if(v===null)return 1;switch(typeof v){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return v===null?1:6;default:return 6}}function $(v){return v===void 0}function re(v){return v===null}function rt(v){return typeof v=="symbol"}function ie(v){return typeof v=="object"?v!==null:typeof v=="function"}function ae(v,R){switch(J(v)){case 0:return v;case 1:return v;case 2:return v;case 3:return v;case 4:return v;case 5:return v}var C=R===3?"string":R===5?"number":"default",L=Ds(v,s);if(L!==void 0){var W=L.call(v,C);if(ie(W))throw new TypeError;return W}return de(v,C==="default"?"number":C)}function de(v,R){if(R==="string"){var C=v.toString;if(st(C)){var L=C.call(v);if(!ie(L))return L}var W=v.valueOf;if(st(W)){var L=W.call(v);if(!ie(L))return L}}else{var W=v.valueOf;if(st(W)){var L=W.call(v);if(!ie(L))return L}var we=v.toString;if(st(we)){var L=we.call(v);if(!ie(L))return L}}throw new TypeError}function Le(v){return!!v}function ot(v){return""+v}function Me(v){var R=ae(v,3);return rt(R)?R:ot(R)}function cn(v){return Array.isArray?Array.isArray(v):v instanceof Object?v instanceof Array:Object.prototype.toString.call(v)==="[object Array]"}function st(v){return typeof v=="function"}function Us(v){return typeof v=="function"}function Gl(v){switch(J(v)){case 3:return!0;case 4:return!0;default:return!1}}function uo(v,R){return v===R||v!==v&&R!==R}function Ds(v,R){var C=v[R];if(C!=null){if(!st(C))throw new TypeError;return C}}function Fs(v){var R=Ds(v,i);if(!st(R))throw new TypeError;var C=R.call(v);if(!ie(C))throw new TypeError;return C}function Hs(v){return v.value}function js(v){var R=v.next();return R.done?!1:R}function Bs(v){var R=v.return;R&&R.call(v)}function lo(v){var R=Object.getPrototypeOf(v);if(typeof v!="function"||v===c||R!==c)return R;var C=v.prototype,L=C&&Object.getPrototypeOf(C);if(L==null||L===Object.prototype)return R;var W=L.constructor;return typeof W!="function"||W===v?R:W}function Wl(){var v;!$(_)&&typeof n.Reflect<"u"&&!(_ in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(v=Kl(n.Reflect));var R,C,L,W=new m,we={registerProvider:be,getProvider:U,setProvider:H};return we;function be(B){if(!Object.isExtensible(we))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case v===B:break;case $(R):R=B;break;case R===B:break;case $(C):C=B;break;case C===B:break;default:L===void 0&&(L=new h),L.add(B);break}}function X(B,ee){if(!$(R)){if(R.isProviderFor(B,ee))return R;if(!$(C)){if(C.isProviderFor(B,ee))return R;if(!$(L))for(var le=Fs(L);;){var _e=js(le);if(!_e)return;var Ge=Hs(_e);if(Ge.isProviderFor(B,ee))return Bs(le),Ge}}}if(!$(v)&&v.isProviderFor(B,ee))return v}function U(B,ee){var le=W.get(B),_e;return $(le)||(_e=le.get(ee)),$(_e)&&(_e=X(B,ee),$(_e)||($(le)&&(le=new p,W.set(B,le)),le.set(ee,_e))),_e}function F(B){if($(B))throw new TypeError;return R===B||C===B||!$(L)&&L.has(B)}function H(B,ee,le){if(!F(le))throw new Error("Metadata provider not registered.");var _e=U(B,ee);if(_e!==le){if(!$(_e))return!1;var Ge=W.get(B);$(Ge)&&(Ge=new p,W.set(B,Ge)),Ge.set(ee,le)}return!0}}function Vl(){var v;return!$(_)&&ie(n.Reflect)&&Object.isExtensible(n.Reflect)&&(v=n.Reflect[_]),$(v)&&(v=Wl()),!$(_)&&ie(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,_,{enumerable:!1,configurable:!1,writable:!1,value:v}),v}function Jl(v){var R=new m,C={isProviderFor:function(F,H){var B=R.get(F);return $(B)?!1:B.has(H)},OrdinaryDefineOwnMetadata:be,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:we,OrdinaryOwnMetadataKeys:X,OrdinaryDeleteMetadata:U};return S.registerProvider(C),C;function L(F,H,B){var ee=R.get(F),le=!1;if($(ee)){if(!B)return;ee=new p,R.set(F,ee),le=!0}var _e=ee.get(H);if($(_e)){if(!B)return;if(_e=new p,ee.set(H,_e),!v.setProvider(F,H,C))throw ee.delete(H),le&&R.delete(F),new Error("Wrong provider for target.")}return _e}function W(F,H,B){var ee=L(H,B,!1);return $(ee)?!1:Le(ee.has(F))}function we(F,H,B){var ee=L(H,B,!1);if(!$(ee))return ee.get(F)}function be(F,H,B,ee){var le=L(B,ee,!0);le.set(F,H)}function X(F,H){var B=[],ee=L(F,H,!1);if($(ee))return B;for(var le=ee.keys(),_e=Fs(le),Ge=0;;){var qs=js(_e);if(!qs)return B.length=Ge,B;var Ql=Hs(qs);try{B[Ge]=Ql}catch(Zl){try{Bs(_e)}finally{throw Zl}}Ge++}}function U(F,H,B){var ee=L(H,B,!1);if($(ee)||!ee.delete(F))return!1;if(ee.size===0){var le=R.get(H);$(le)||(le.delete(B),le.size===0&&R.delete(le))}return!0}}function Kl(v){var R=v.defineMetadata,C=v.hasOwnMetadata,L=v.getOwnMetadata,W=v.getOwnMetadataKeys,we=v.deleteMetadata,be=new m,X={isProviderFor:function(U,F){var H=be.get(U);return!$(H)&&H.has(F)?!0:W(U,F).length?($(H)&&(H=new h,be.set(U,H)),H.add(F),!0):!1},OrdinaryDefineOwnMetadata:R,OrdinaryHasOwnMetadata:C,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:we};return X}function pn(v,R,C){var L=S.getProvider(v,R);if(!$(L))return L;if(C){if(S.setProvider(v,R,b))return b;throw new Error("Illegal state.")}}function zl(){var v={},R=[],C=(function(){function X(U,F,H){this._index=0,this._keys=U,this._values=F,this._selector=H}return X.prototype["@@iterator"]=function(){return this},X.prototype[i]=function(){return this},X.prototype.next=function(){var U=this._index;if(U>=0&&U<this._keys.length){var F=this._selector(this._keys[U],this._values[U]);return U+1>=this._keys.length?(this._index=-1,this._keys=R,this._values=R):this._index++,{value:F,done:!1}}return{value:void 0,done:!0}},X.prototype.throw=function(U){throw this._index>=0&&(this._index=-1,this._keys=R,this._values=R),U},X.prototype.return=function(U){return this._index>=0&&(this._index=-1,this._keys=R,this._values=R),{value:U,done:!0}},X})(),L=(function(){function X(){this._keys=[],this._values=[],this._cacheKey=v,this._cacheIndex=-2}return Object.defineProperty(X.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),X.prototype.has=function(U){return this._find(U,!1)>=0},X.prototype.get=function(U){var F=this._find(U,!1);return F>=0?this._values[F]:void 0},X.prototype.set=function(U,F){var H=this._find(U,!0);return this._values[H]=F,this},X.prototype.delete=function(U){var F=this._find(U,!1);if(F>=0){for(var H=this._keys.length,B=F+1;B<H;B++)this._keys[B-1]=this._keys[B],this._values[B-1]=this._values[B];return this._keys.length--,this._values.length--,uo(U,this._cacheKey)&&(this._cacheKey=v,this._cacheIndex=-2),!0}return!1},X.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=v,this._cacheIndex=-2},X.prototype.keys=function(){return new C(this._keys,this._values,W)},X.prototype.values=function(){return new C(this._keys,this._values,we)},X.prototype.entries=function(){return new C(this._keys,this._values,be)},X.prototype["@@iterator"]=function(){return this.entries()},X.prototype[i]=function(){return this.entries()},X.prototype._find=function(U,F){if(!uo(this._cacheKey,U)){this._cacheIndex=-1;for(var H=0;H<this._keys.length;H++)if(uo(this._keys[H],U)){this._cacheIndex=H;break}}return this._cacheIndex<0&&F&&(this._cacheIndex=this._keys.length,this._keys.push(U),this._values.push(void 0)),this._cacheIndex},X})();return L;function W(X,U){return X}function we(X,U){return U}function be(X,U){return[X,U]}}function Yl(){var v=(function(){function R(){this._map=new p}return Object.defineProperty(R.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),R.prototype.has=function(C){return this._map.has(C)},R.prototype.add=function(C){return this._map.set(C,C),this},R.prototype.delete=function(C){return this._map.delete(C)},R.prototype.clear=function(){this._map.clear()},R.prototype.keys=function(){return this._map.keys()},R.prototype.values=function(){return this._map.keys()},R.prototype.entries=function(){return this._map.entries()},R.prototype["@@iterator"]=function(){return this.keys()},R.prototype[i]=function(){return this.keys()},R})();return v}function Xl(){var v=16,R=d.create(),C=L();return(function(){function U(){this._key=L()}return U.prototype.has=function(F){var H=W(F,!1);return H!==void 0?d.has(H,this._key):!1},U.prototype.get=function(F){var H=W(F,!1);return H!==void 0?d.get(H,this._key):void 0},U.prototype.set=function(F,H){var B=W(F,!0);return B[this._key]=H,this},U.prototype.delete=function(F){var H=W(F,!1);return H!==void 0?delete H[this._key]:!1},U.prototype.clear=function(){this._key=L()},U})();function L(){var U;do U="@@WeakMap@@"+X();while(d.has(R,U));return R[U]=!0,U}function W(U,F){if(!r.call(U,C)){if(!F)return;Object.defineProperty(U,C,{value:d.create()})}return U[C]}function we(U,F){for(var H=0;H<F;++H)U[H]=Math.random()*255|0;return U}function be(U){if(typeof Uint8Array=="function"){var F=new Uint8Array(U);return typeof crypto<"u"?crypto.getRandomValues(F):typeof msCrypto<"u"?msCrypto.getRandomValues(F):we(F,U),F}return we(new Array(U),U)}function X(){var U=be(v);U[6]=U[6]&79|64,U[8]=U[8]&191|128;for(var F="",H=0;H<v;++H){var B=U[H];(H===4||H===6||H===8)&&(F+="-"),B<16&&(F+="0"),F+=B.toString(16).toLowerCase()}return F}}function co(v){return v.__=void 0,delete v.__,v}})})(Ws||(Ws={}))});E();var Xv=ke(Vs(),1),Qe=ke(require("process"),1);E();var $d=ke(require("os"),1),Nd=ke(require("path"),1),Ud=require("url"),Dd=require("util");E();var mi=require("crypto");E();var ce=class extends Error{},ud=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ld(t){if(typeof t!="string")return!1;let e=ud.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 dd(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",ld(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 Ut(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Js(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new ce(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let u=o[a];if(typeof u!="string"||u===""||u.includes(":"))throw i(`"${a}" ${JSON.stringify(u)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function po(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 Ks(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 dd(await r.json())}E();function Ne(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}E();var De=class extends Error{name="ModelPriceError"},fo="per_million_input_tokens",mo="per_million_output_tokens",Ys="model_id,variant,unit,price_usd,effective_at,expires_at",zs={per_request:!0,per_minute:!0,per_output_unit:!0},cd=5e3;function pd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new De(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Xs(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new De(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function fd(t,e,n){return t===null?null:Xs(t,e,n)}function md(t,e){if(t===fo)return"input";if(t===mo)return"output";if(typeof t=="string"&&Object.hasOwn(zs,t))return null;throw new De(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${fo} | ${mo}) nor a known GPU-time unit (${Object.keys(zs).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 gd(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 go(t,e){return`${t}\0${e}`}function hd(t){if(!Array.isArray(t))throw new De(`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 De(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Ys.split(","))if(!Object.hasOwn(s,l))throw new De(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=md(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new De(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new De(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:pd(s.price_usd,o),effective_at:Xs(s.effective_at,o,"effective_at"),expires_at:fd(s.expires_at,o,"expires_at")})}return e}function Qs(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,h,m)=>{let _=p&&p.length>0?p:d?.[h];if(!_||_.length===0)return null;let S=gd(_,h);return"reason"in S?S:S.rate.usd===0?h==="output"&&m!==null&&n?.has(go(u,m))?S.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:S.rate};for(let[p,h]of o.get(u)){let m=l.get(p),_=c(m?.input,"input",h),S=c(m?.output,"output",h);if(_!==null&&"reason"in _){i.push({model_id:u,variant:h,reason:_.reason});continue}if(S!==null&&"reason"in S){i.push({model_id:u,variant:h,reason:S.reason});continue}_===null||S===null||s.push({model_id:u,variant:h,pricing:{input:_.usd,output:S.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 fn(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 mn={prices:[],refusals:[]};async function Zs(t){let e=t.fetchImpl??fetch,n=`${fo},${mo}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ys}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(cd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return hd(await r.json())}E();var vt="/partners/openrouter/models",yd={chat:!0,code:!0,agent:!0,vl:!0},ei={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function wd(t){let e=t.toLowerCase();return Object.hasOwn(ei,e)?ei[e]:null}var ti={"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 _d(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ti,o)?ti[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 ni={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},ri={2:"Llama2",3:"Llama3"};function vd(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(ni,s))return ni[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(ri,i))return ri[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var bd=["context_length","max_model_len"];function Sd(t){let e=bd.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 Gn(t){let e=t.map(Sd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function kd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function ho(t){if(t.length===0)return null;let e=t.map(kd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function yo(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 Rd(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return gn(n);let r=e.filter(s=>Ne(s.model_id)===t);if(r.length>0)return gn(r);let o=yo(t,e);return o.length>0?gn(o):null}function gn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Ed(t),matches:t}:null}function Ed(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 ct=class extends Error{name="ModelCreatedError"};function Dt(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 ct(`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 ct(`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 ct(`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 ct(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function _t(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 Wn(t,e,n){let r=Rd(t,e);if(!r)return _t({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Gn(s),a=Dt(s),u=fn(o.model_id,o.variant,n),l=ii(o,s),d=ho(s);return _t({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 xd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function ii(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:[...xd],defect:o}:{published:[],defect:o}}function wo(t){let e=t.length>0?gn(t):null;return e===null?{published:[],defect:null}:ii(e.row,e.matches)}function oi(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 si(t){return{input:[{type:"prompt",unit:"token",cost_usd:oi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:oi(t.output)}]}}function Ad(t,e,n,r){if(e.length===0)return null;let o=gn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||yd[s.task]!==!0)return null;let a=Gn(i),u=fn(s.model_id,s.variant,n),l=vd(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:Dt(i),quantization:wd(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:si(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:si(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function ai(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?Ut(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:_d(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=Ad(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&a.push(c)}return{data:a}}E();var ui={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Ft=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function li(t){let e=t.t;if(typeof e!="string"||!(e in ui))throw new Ft(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ui).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 Od(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Ft(`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 Ft(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Ft(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return li(t)}function di(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Id(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 ci(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 di(e);let s=o.next();if(e!==void 0&&await Id(s,e)==="aborted")throw s.catch(()=>{}),di(e);let i=await s;if(i.done)return;yield Od(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ne=class extends Error{},Q=class extends Error{},vo="urs1.";function yn(t,e){return vo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function wn(t){if(!t.startsWith(vo))return null;try{let e=JSON.parse(Buffer.from(t.slice(vo.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 gi(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 pi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Cd(t);return e===null?[]:[e]}function Td(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var bd=Object.create;var ri=Object.defineProperty;var Sd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var Rd=Object.getPrototypeOf,Ed=Object.prototype.hasOwnProperty;var xd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Ad=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Id=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kd(e))!Ed.call(t,o)&&o!==n&&ri(t,o,{get:()=>e[o],enumerable:!(r=Sd(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?bd(Rd(t)):{},Id(e||!t||!t.__esModule?ri(n,"default",{value:t,enumerable:!0}):n,t));var I=xd(()=>{"use strict"});var si=Ad(()=>{"use strict";I();var oi;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(d,c)}}function s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return _o(Object.create(null))}:l?function(){return _o({__proto__:null})}:function(){return _o({})},has:u?function(S,A){return r.call(S,A)}:function(S,A){return A in S},get:u?function(S,A){return r.call(S,A)?S[A]:void 0}:function(S,A){return S[A]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:hd(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:yd(),m=typeof WeakMap=="function"?WeakMap:wd(),_=o?Symbol.for("@reflect-metadata:registry"):void 0,R=fd(),v=md(R);function b(S,A,L,U){if(N(L)){if(!hn(S))throw new TypeError;if(!Ys(A))throw new TypeError;return w(S,A)}else{if(!hn(S))throw new TypeError;if(!ue(A))throw new TypeError;if(!ue(U)&&!N(U)&&!te(U))throw new TypeError;return te(U)&&(U=void 0),L=$e(L),T(S,A,L,U)}}e("decorate",b);function p(S,A){function L(U,K){if(!ue(U))throw new TypeError;if(!N(K)&&!cd(K))throw new TypeError;se(S,A,U,K)}return L}e("metadata",p);function g(S,A,L,U){if(!ue(L))throw new TypeError;return N(U)||(U=$e(U)),se(S,A,L,U)}e("defineMetadata",g);function y(S,A,L){if(!ue(A))throw new TypeError;return N(L)||(L=$e(L)),$(S,A,L)}e("hasMetadata",y);function k(S,A,L){if(!ue(A))throw new TypeError;return N(L)||(L=$e(L)),M(S,A,L)}e("hasOwnMetadata",k);function O(S,A,L){if(!ue(A))throw new TypeError;return N(L)||(L=$e(L)),F(S,A,L)}e("getMetadata",O);function x(S,A,L){if(!ue(A))throw new TypeError;return N(L)||(L=$e(L)),G(S,A,L)}e("getOwnMetadata",x);function P(S,A){if(!ue(S))throw new TypeError;return N(A)||(A=$e(A)),X(S,A)}e("getMetadataKeys",P);function E(S,A){if(!ue(S))throw new TypeError;return N(A)||(A=$e(A)),ae(S,A)}e("getOwnMetadataKeys",E);function C(S,A,L){if(!ue(A))throw new TypeError;if(N(L)||(L=$e(L)),!ue(A))throw new TypeError;N(L)||(L=$e(L));var U=yn(A,L,!1);return N(U)?!1:U.OrdinaryDeleteMetadata(S,A,L)}e("deleteMetadata",C);function w(S,A){for(var L=S.length-1;L>=0;--L){var U=S[L],K=U(A);if(!N(K)&&!te(K)){if(!Ys(K))throw new TypeError;A=K}}return A}function T(S,A,L,U){for(var K=S.length-1;K>=0;--K){var ve=S[K],ke=ve(A,L,U);if(!N(ke)&&!te(ke)){if(!ue(ke))throw new TypeError;U=ke}}return U}function $(S,A,L){var U=M(S,A,L);if(U)return!0;var K=wo(A);return te(K)?!1:$(S,K,L)}function M(S,A,L){var U=yn(A,L,!1);return N(U)?!1:Le(U.OrdinaryHasOwnMetadata(S,A,L))}function F(S,A,L){var U=M(S,A,L);if(U)return G(S,A,L);var K=wo(A);if(!te(K))return F(S,K,L)}function G(S,A,L){var U=yn(A,L,!1);if(!N(U))return U.OrdinaryGetOwnMetadata(S,A,L)}function se(S,A,L,U){var K=yn(L,U,!0);K.OrdinaryDefineOwnMetadata(S,A,L,U)}function X(S,A){var L=ae(S,A),U=wo(S);if(U===null)return L;var K=X(U,A);if(K.length<=0)return L;if(L.length<=0)return K;for(var ve=new h,ke=[],Z=0,B=L;Z<B.length;Z++){var j=B[Z],W=ve.has(j);W||(ve.add(j),ke.push(j))}for(var J=0,ne=K;J<ne.length;J++){var j=ne[J],W=ve.has(j);W||(ve.add(j),ke.push(j))}return ke}function ae(S,A){var L=yn(S,A,!1);return L?L.OrdinaryOwnMetadataKeys(S,A):[]}function z(S){if(S===null)return 1;switch(typeof S){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return S===null?1:6;default:return 6}}function N(S){return S===void 0}function te(S){return S===null}function ot(S){return typeof S=="symbol"}function ue(S){return typeof S=="object"?S!==null:typeof S=="function"}function de(S,A){switch(z(S)){case 0:return S;case 1:return S;case 2:return S;case 3:return S;case 4:return S;case 5:return S}var L=A===3?"string":A===5?"number":"default",U=Xs(S,s);if(U!==void 0){var K=U.call(S,L);if(ue(K))throw new TypeError;return K}return fe(S,L==="default"?"number":L)}function fe(S,A){if(A==="string"){var L=S.toString;if(it(L)){var U=L.call(S);if(!ue(U))return U}var K=S.valueOf;if(it(K)){var U=K.call(S);if(!ue(U))return U}}else{var K=S.valueOf;if(it(K)){var U=K.call(S);if(!ue(U))return U}var ve=S.toString;if(it(ve)){var U=ve.call(S);if(!ue(U))return U}}throw new TypeError}function Le(S){return!!S}function st(S){return""+S}function $e(S){var A=de(S,3);return ot(A)?A:st(A)}function hn(S){return Array.isArray?Array.isArray(S):S instanceof Object?S instanceof Array:Object.prototype.toString.call(S)==="[object Array]"}function it(S){return typeof S=="function"}function Ys(S){return typeof S=="function"}function cd(S){switch(z(S)){case 3:return!0;case 4:return!0;default:return!1}}function yo(S,A){return S===A||S!==S&&A!==A}function Xs(S,A){var L=S[A];if(L!=null){if(!it(L))throw new TypeError;return L}}function Qs(S){var A=Xs(S,i);if(!it(A))throw new TypeError;var L=A.call(S);if(!ue(L))throw new TypeError;return L}function Zs(S){return S.value}function ei(S){var A=S.next();return A.done?!1:A}function ti(S){var A=S.return;A&&A.call(S)}function wo(S){var A=Object.getPrototypeOf(S);if(typeof S!="function"||S===c||A!==c)return A;var L=S.prototype,U=L&&Object.getPrototypeOf(L);if(U==null||U===Object.prototype)return A;var K=U.constructor;return typeof K!="function"||K===S?A:K}function pd(){var S;!N(_)&&typeof n.Reflect<"u"&&!(_ in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(S=gd(n.Reflect));var A,L,U,K=new m,ve={registerProvider:ke,getProvider:B,setProvider:W};return ve;function ke(J){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case S===J:break;case N(A):A=J;break;case A===J:break;case N(L):L=J;break;case L===J:break;default:U===void 0&&(U=new h),U.add(J);break}}function Z(J,ne){if(!N(A)){if(A.isProviderFor(J,ne))return A;if(!N(L)){if(L.isProviderFor(J,ne))return A;if(!N(U))for(var pe=Qs(U);;){var be=ei(pe);if(!be)return;var We=Zs(be);if(We.isProviderFor(J,ne))return ti(pe),We}}}if(!N(S)&&S.isProviderFor(J,ne))return S}function B(J,ne){var pe=K.get(J),be;return N(pe)||(be=pe.get(ne)),N(be)&&(be=Z(J,ne),N(be)||(N(pe)&&(pe=new f,K.set(J,pe)),pe.set(ne,be))),be}function j(J){if(N(J))throw new TypeError;return A===J||L===J||!N(U)&&U.has(J)}function W(J,ne,pe){if(!j(pe))throw new Error("Metadata provider not registered.");var be=B(J,ne);if(be!==pe){if(!N(be))return!1;var We=K.get(J);N(We)&&(We=new f,K.set(J,We)),We.set(ne,pe)}return!0}}function fd(){var S;return!N(_)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(S=n.Reflect[_]),N(S)&&(S=pd()),!N(_)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,_,{enumerable:!1,configurable:!1,writable:!1,value:S}),S}function md(S){var A=new m,L={isProviderFor:function(j,W){var J=A.get(j);return N(J)?!1:J.has(W)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:K,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:Z,OrdinaryDeleteMetadata:B};return R.registerProvider(L),L;function U(j,W,J){var ne=A.get(j),pe=!1;if(N(ne)){if(!J)return;ne=new f,A.set(j,ne),pe=!0}var be=ne.get(W);if(N(be)){if(!J)return;if(be=new f,ne.set(W,be),!S.setProvider(j,W,L))throw ne.delete(W),pe&&A.delete(j),new Error("Wrong provider for target.")}return be}function K(j,W,J){var ne=U(W,J,!1);return N(ne)?!1:Le(ne.has(j))}function ve(j,W,J){var ne=U(W,J,!1);if(!N(ne))return ne.get(j)}function ke(j,W,J,ne){var pe=U(J,ne,!0);pe.set(j,W)}function Z(j,W){var J=[],ne=U(j,W,!1);if(N(ne))return J;for(var pe=ne.keys(),be=Qs(pe),We=0;;){var ni=ei(be);if(!ni)return J.length=We,J;var _d=Zs(ni);try{J[We]=_d}catch(vd){try{ti(be)}finally{throw vd}}We++}}function B(j,W,J){var ne=U(W,J,!1);if(N(ne)||!ne.delete(j))return!1;if(ne.size===0){var pe=A.get(W);N(pe)||(pe.delete(J),pe.size===0&&A.delete(pe))}return!0}}function gd(S){var A=S.defineMetadata,L=S.hasOwnMetadata,U=S.getOwnMetadata,K=S.getOwnMetadataKeys,ve=S.deleteMetadata,ke=new m,Z={isProviderFor:function(B,j){var W=ke.get(B);return!N(W)&&W.has(j)?!0:K(B,j).length?(N(W)&&(W=new h,ke.set(B,W)),W.add(j),!0):!1},OrdinaryDefineOwnMetadata:A,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:U,OrdinaryOwnMetadataKeys:K,OrdinaryDeleteMetadata:ve};return Z}function yn(S,A,L){var U=R.getProvider(S,A);if(!N(U))return U;if(L){if(R.setProvider(S,A,v))return v;throw new Error("Illegal state.")}}function hd(){var S={},A=[],L=(function(){function Z(B,j,W){this._index=0,this._keys=B,this._values=j,this._selector=W}return Z.prototype["@@iterator"]=function(){return this},Z.prototype[i]=function(){return this},Z.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var j=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=A,this._values=A):this._index++,{value:j,done:!1}}return{value:void 0,done:!0}},Z.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=A,this._values=A),B},Z.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=A,this._values=A),{value:B,done:!0}},Z})(),U=(function(){function Z(){this._keys=[],this._values=[],this._cacheKey=S,this._cacheIndex=-2}return Object.defineProperty(Z.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Z.prototype.has=function(B){return this._find(B,!1)>=0},Z.prototype.get=function(B){var j=this._find(B,!1);return j>=0?this._values[j]:void 0},Z.prototype.set=function(B,j){var W=this._find(B,!0);return this._values[W]=j,this},Z.prototype.delete=function(B){var j=this._find(B,!1);if(j>=0){for(var W=this._keys.length,J=j+1;J<W;J++)this._keys[J-1]=this._keys[J],this._values[J-1]=this._values[J];return this._keys.length--,this._values.length--,yo(B,this._cacheKey)&&(this._cacheKey=S,this._cacheIndex=-2),!0}return!1},Z.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=S,this._cacheIndex=-2},Z.prototype.keys=function(){return new L(this._keys,this._values,K)},Z.prototype.values=function(){return new L(this._keys,this._values,ve)},Z.prototype.entries=function(){return new L(this._keys,this._values,ke)},Z.prototype["@@iterator"]=function(){return this.entries()},Z.prototype[i]=function(){return this.entries()},Z.prototype._find=function(B,j){if(!yo(this._cacheKey,B)){this._cacheIndex=-1;for(var W=0;W<this._keys.length;W++)if(yo(this._keys[W],B)){this._cacheIndex=W;break}}return this._cacheIndex<0&&j&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},Z})();return U;function K(Z,B){return Z}function ve(Z,B){return B}function ke(Z,B){return[Z,B]}}function yd(){var S=(function(){function A(){this._map=new f}return Object.defineProperty(A.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),A.prototype.has=function(L){return this._map.has(L)},A.prototype.add=function(L){return this._map.set(L,L),this},A.prototype.delete=function(L){return this._map.delete(L)},A.prototype.clear=function(){this._map.clear()},A.prototype.keys=function(){return this._map.keys()},A.prototype.values=function(){return this._map.keys()},A.prototype.entries=function(){return this._map.entries()},A.prototype["@@iterator"]=function(){return this.keys()},A.prototype[i]=function(){return this.keys()},A})();return S}function wd(){var S=16,A=d.create(),L=U();return(function(){function B(){this._key=U()}return B.prototype.has=function(j){var W=K(j,!1);return W!==void 0?d.has(W,this._key):!1},B.prototype.get=function(j){var W=K(j,!1);return W!==void 0?d.get(W,this._key):void 0},B.prototype.set=function(j,W){var J=K(j,!0);return J[this._key]=W,this},B.prototype.delete=function(j){var W=K(j,!1);return W!==void 0?delete W[this._key]:!1},B.prototype.clear=function(){this._key=U()},B})();function U(){var B;do B="@@WeakMap@@"+Z();while(d.has(A,B));return A[B]=!0,B}function K(B,j){if(!r.call(B,L)){if(!j)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,j){for(var W=0;W<j;++W)B[W]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var j=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(j):typeof msCrypto<"u"?msCrypto.getRandomValues(j):ve(j,B),j}return ve(new Array(B),B)}function Z(){var B=ke(S);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var j="",W=0;W<S;++W){var J=B[W];(W===4||W===6||W===8)&&(j+="-"),J<16&&(j+="0"),j+=J.toString(16).toLowerCase()}return j}}function _o(S){return S.__=void 0,delete S.__,S}})})(oi||(oi={}))});I();var Wb=Re(si(),1),Ze=Re(require("process"),1);I();var nc=Re(require("os"),1),rc=Re(require("path"),1),oc=require("url"),sc=require("util");I();var Ai=require("crypto");I();var me=class extends Error{},Od=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Td(t){if(typeof t!="string")return!1;let e=Od.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Pd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new me(`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 me(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new me(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new me(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new me(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new me(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new me(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Td(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new me(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new me(`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 me(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new me(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function jt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function ii(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new me(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function vo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new me(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function ai(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 me(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Pd(await r.json())}I();function Ne(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}I();var De=class extends Error{name="ModelPriceError"},bo="per_million_input_tokens",So="per_million_output_tokens",ui="model_id,variant,unit,price_usd,effective_at,expires_at",li={per_request:!0,per_minute:!0,per_output_unit:!0},Cd=5e3;function Ld(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new De(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function di(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new De(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function $d(t,e,n){return t===null?null:di(t,e,n)}function Md(t,e){if(t===bo)return"input";if(t===So)return"output";if(typeof t=="string"&&Object.hasOwn(li,t))return null;throw new De(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${bo} | ${So}) nor a known GPU-time unit (${Object.keys(li).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 Nd(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 ko(t,e){return`${t}\0${e}`}function Ud(t){if(!Array.isArray(t))throw new De(`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 De(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of ui.split(","))if(!Object.hasOwn(s,u))throw new De(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Md(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new De(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new De(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Ld(s.price_usd,o),effective_at:di(s.effective_at,o,"effective_at"),expires_at:$d(s.expires_at,o,"expires_at")})}return e}function ci(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let _=f&&f.length>0?f:d?.[h];if(!_||_.length===0)return null;let R=Nd(_,h);return"reason"in R?R:R.rate.usd===0?h==="output"&&m!==null&&n?.has(ko(l,m))?R.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:R.rate};for(let[f,h]of o.get(l)){let m=u.get(f),_=c(m?.input,"input",h),R=c(m?.output,"output",h);if(_!==null&&"reason"in _){i.push({model_id:l,variant:h,reason:_.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:l,variant:h,reason:R.reason});continue}_===null||R===null||s.push({model_id:l,variant:h,pricing:{input:_.usd,output:R.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function wn(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 _n={prices:[],refusals:[]};async function pi(t){let e=t.fetchImpl??fetch,n=`${bo},${So}`,r=await e(`${t.catalogUrl}/model_prices?select=${ui}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Cd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Ud(await r.json())}I();var kt="/partners/openrouter/models",Dd={chat:!0,code:!0,agent:!0,vl:!0},fi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Fd(t){let e=t.toLowerCase();return Object.hasOwn(fi,e)?fi[e]:null}var mi={"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 Bd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(mi,o)?mi[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 gi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},hi={2:"Llama2",3:"Llama3"};function Hd(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(gi,s))return gi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(hi,i))return hi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var jd=["context_length","max_model_len"];function qd(t){let e=jd.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 Xn(t){let e=t.map(qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Gd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Ro(t){if(t.length===0)return null;let e=t.map(Gd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Eo(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 Wd(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return vn(n);let r=e.filter(s=>Ne(s.model_id)===t);if(r.length>0)return vn(r);let o=Eo(t,e);return o.length>0?vn(o):null}function vn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Jd(t),matches:t}:null}function Jd(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 ft=class extends Error{name="ModelCreatedError"};function qt(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 ft(`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 ft(`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 ft(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new ft(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function St(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 Qn(t,e,n){let r=Wd(t,e);if(!r)return St({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Xn(s),a=qt(s),l=wn(o.model_id,o.variant,n),u=_i(o,s),d=Ro(s);return St({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var Vd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function _i(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:[...Vd],defect:o}:{published:[],defect:o}}function xo(t){let e=t.length>0?vn(t):null;return e===null?{published:[],defect:null}:_i(e.row,e.matches)}function yi(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 wi(t){return{input:[{type:"prompt",unit:"token",cost_usd:yi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:yi(t.output)}]}}function Kd(t,e,n,r){if(e.length===0)return null;let o=vn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Dd[s.task]!==!0)return null;let a=Xn(i),l=wn(s.model_id,s.variant,n),u=Hd(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:qt(i),quantization:Fd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:wi(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:wi(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function vi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?jt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Bd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=Kd(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}I();var bi={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 Si(t){let e=t.t;if(typeof e!="string"||!(e in bi))throw new Gt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(bi).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 zd(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 Si(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 Si(t)}function ki(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Yd(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 Ri(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 ki(e);let s=o.next();if(e!==void 0&&await Yd(s,e)==="aborted")throw s.catch(()=>{}),ki(e);let i=await s;if(i.done)return;yield zd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var oe=class extends Error{},ee=class extends Error{},Io="urs1.";function kn(t,e){return Io+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Wt(t){if(!t.startsWith(Io))return null;try{let e=JSON.parse(Buffer.from(t.slice(Io.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 Ii(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 Ei(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Zd(t);return e===null?[]:[e]}function Xd(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
- `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function So(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||Ne(`${r.model_id}-${r.variant}`)===e.appSlug||Ne(r.model_id)===e.appSlug)),n?Td(n.engine_args?.pool):null}function _o(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 fi(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 hi="shared:",Ht="speech:",jt="realtime:";function ft(t){return t.sharedApp?hi+t.appSlug:t.appSlug}function Jn(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 bo(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ne(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Pd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Cd(t){let e=t.map(Pd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Ld={stt:"stt",tts:"tts"};function pt(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:Ld[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function yi(t,e){let n=bo(t,e);return n.length>0?n:yo(t,e)}function hn(t,e){return yi(t.appSlug,e)}function Md(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 Vn=6e4,Kn=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Vn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Vn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Vn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Vn;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 De)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
- `),mn}let r=Qs(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(go(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(hi)||o.startsWith(Ht)||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 ne(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=po(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=Ne(s),u=n.endpoints.filter(c=>Ne(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:po(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=Ne(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 ne(`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 ne(`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===Ne(u.model_id)||o===Ne(`${u.model_id}-${u.variant}`));if(a)throw new ne(`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=Jn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return So(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return ft(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ft(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ht+ft(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,jt+(0,mi.randomUUID)())}async evictHandle(e){let n=wn(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Jn(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:yn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:yn(n,this.keyOf(r))}}async sessionForHandle(e){let n=wn(e);if(!n)throw new Q(`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 Q(`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&&this.mintedIds.get(i)!==o)throw new Q(`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:mn;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?Ut(n):[]).map(l=>{let d=s.filter(b=>b.model_id===l.model_id&&b.variant===l.variant),c=Gn(d),p=Dt(d),h=ho(d),m=fn(l.model_id,l.variant,i),_=wo(d);return _t({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},..._.published.length>0?{voices:[..._.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>Wn(l,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ai(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=_o(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return fi(`${r.modelId}:${r.variant}`,s).includes(n)}return pi(bo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:pt(hn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":pt(hn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":pt(hn(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):hn(n,r);return Md(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):hn(n,r);return wo(o)}async imageModelList(){let e=await this.catalogRows(),n=mn,r=[];for(let s of await this.availableIds()){let i=pi(bo(s,e));i.length!==0&&r.push(_t({...Wn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Ut(o)){let i=_o(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=fi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=_t({id:`${s.model_id}:${s.variant}`,object:"model",created:Dt(i),owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=mn,r=[];for(let s of await this.availableIds())pt(yi(s,e))==="stt"&&r.push(Wn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Ut(o)){let i=_o(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(pt(i)!=="stt")continue;let a=_t({id:`${s.model_id}:${s.variant}`,object:"model",created:Dt(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 wi(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 zn(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 Fd=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function _i(t){let e=t?.code;return typeof e=="string"&&Fd.has(e)}function Ze(t,e){try{return t.write(e),!0}catch(n){if(_i(n))return!1;throw n}}function vi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{_i(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)}}}E();var he=require("@prometheus-io/client"),Gi=require("http");E();var Hd={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"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 jd(t){return Hd[t]??null}var ki=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Bd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function qd(t){return t==="surface"}function Gd(t){let e=t?.ledgerFailureReason;return ki.includes(e)?e:"unknown"}var Wd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],bi=["priced","unpriced"],Vd={written:bi,already_written:bi,skipped:Wd,failed:ki},Ri=Object.entries(Vd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Jd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Kd(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 zd=256,Si=4096,_n=12e4,Yd=250,Xd=8e3,it=[],ko=new Set,vn=0,Bt=!1;function Ei(){return it.length}function xi(t=Date.now()){let e=it[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Yn=new Set;function Ai(){return vn===0&&it.length===0}function Oi(){if(Ai()){Bt=!1;for(let t of[...Yn])t()}}async function Ii(t=Pi){return Ai()?!0:await new Promise(e=>{let n=null,r=()=>{Yn.delete(r),n&&clearTimeout(n),e(!0)};Yn.add(r),n=setTimeout(()=>{Yn.delete(r),e(!1)},t),n.unref?.()})}function Ti(){Bt=!0;let t=[...it.splice(0,it.length),...ko];for(let e of t)e.settled||St(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 Oi(),t.length}var Pi=5e3;function Ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
- `}function Qd(t){Ze(process.stdout,t)}function Li(t,e){try{t(e)}catch{}}function Mi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Qd,o=jd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Li(r,Ci("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:Kd(e),completed_at:e.ts,billable_outcome:Jd(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(it.length>=Si){i("queue_full",`${it.length} ledger writes are already waiting (capacity ${Si}, ${vn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}it.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),vn<zd&&(vn+=1,Zd())}async function Zd(){try{for(;;){let t=ec();if(t===void 0)return;ko.add(t);try{await tc(t)}finally{ko.delete(t)}}}finally{vn-=1,Oi()}}function ec(){let t=Date.now();for(;;){let e=it.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<_n)return e;St(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 ${_n}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 tc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);St(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=Bd(o);if(s!==null){St(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=Gd(o),a=Date.now()-t.queuedAt;if(Bt){St(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(qd(i)&&a<_n){if(await rc(nc(t.attempts)),Bt||Date.now()-t.queuedAt>=_n){let u=Date.now()-t.queuedAt;St(t,{outcome:"failed",reason:Bt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Bt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${_n}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}St(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 nc(t){return Math.min(Xd,Yd*2**Math.max(0,t-1))}function rc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function St(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Li(t.report,Ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}E();E();var Qn="/v1/usage/requests",$i=1e4,oc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,mt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ge=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Xn=class extends ge{constructor(e){super(e),this.name="UsageWithholdingError"}},Fi=1024*1024;function xo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new mt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new mt(`"${e}" must be an array of uuid strings`);if(n.length>$i)throw new mt(`"${e}" carries ${n.length} ids; at most ${$i} 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"||!oc.test(s))throw new mt(`"${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 Hi(t){return xo(t,"inference_ids")}var sc=["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 qt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new ge(`${n}: ${e} is not a non-empty string (got ${Wt(r)})`);return r}function Ro(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new ge(`${n}: ${e} is neither null nor a non-empty string (got ${Wt(r)})`);return r}function Gt(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 ge(`${n}: ${e} is not a number (got ${Wt(o)})`);if(r&&!Number.isSafeInteger(s))throw new ge(`${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 ge(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var ic=40,Ni=64,Ui=600;function ji(t){let e=Object.keys(t).sort(),r=e.slice(0,ic).map(o=>o.length>Ni?`${o.slice(0,Ni)}\u2026`:o).join(", ");return r.length>Ui&&(r=`${r.slice(0,Ui)}\u2026`),`${e.length} keys present: [${r}]`}function Wt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Eo(t){Ze(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
- `)}function ac(t,e){let n;try{n=t(e)}catch{Di(t,e);return}uc(n)&&Promise.resolve(n).catch(()=>{Di(t,e)})}function uc(t){return typeof t?.then=="function"}function Di(t,e){if(t!==Eo)try{Eo(e)}catch{}}function Bi(t,e=Eo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?ji(t):Wt(t);throw new ge(`the usage surface answered without a "requests" array: got ${Wt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(lc(n[o],s))}catch(i){if(i instanceof Xn||!(i instanceof ge))throw i;ac(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new ge(`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 lc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ge(`${e} is not an object: got ${Wt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Xn(`${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 sc)if(!Object.hasOwn(n,o))throw new ge(`${e} has no "${o}" column (${ji(n)})`);let r=Gt(n,"http_status",e,!0);if(r===null)throw new ge(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:qt(n,"inference_id",e),model_id:qt(n,"model_id",e),identity_kind:qt(n,"identity_kind",e),variant:Ro(n,"variant",e),task:qt(n,"task",e),http_status:r,started_at:qt(n,"started_at",e),completed_at:qt(n,"completed_at",e),prompt_tokens:Gt(n,"prompt_tokens",e,!0),completion_tokens:Gt(n,"completion_tokens",e,!0),output_units:Gt(n,"output_units",e,!1),output_minutes:Gt(n,"output_minutes",e,!1),cost_nano_usd:Gt(n,"cost_nano_usd",e,!0),price_version:Ro(n,"price_version",e),priced_at:Ro(n,"priced_at",e)}}function Zn(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 ge(`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 ge(`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 bn="/partners/huggingface/v1/billing/requests";function dc(t){return xo(t,"requestIds")}function cc(t){return t>=200&&t<=399}function pc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&cc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function qi(t,e){let n=dc(t),r=await e(n);return Zn(r,n),pc(r)}var Ao=9464,er="/metrics",tr="(other)",fc="(none)",mc=64,gc=128,hc=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/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",Qn,bn,vt],yc=new Set(hc);function wc(t){return yc.has(t)?t:tr}function _c(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var nr=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?fc:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,tr):(this.admitted.add(e),e):tr}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},rr=class{registry=new he.Registry;modelLabel=new nr(mc);orgLabel=new nr(gc);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new he.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 he.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 he.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 he.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 he.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 he.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 he.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 Ri)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new he.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"},Ei()),this.ledgerQueue.set({measure:"oldest_age_seconds"},xi()/1e3)}}),this.labelCardinality=new he.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 he.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 he.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 he.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 he.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 he.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 he.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,he.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=wc(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===""?tr:e.method,status_class:_c(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 Wi(t){return(0,Gi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==er){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${er}
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||Ne(`${r.model_id}-${r.variant}`)===e.appSlug||Ne(r.model_id)===e.appSlug)),n?Xd(n.engine_args?.pool):null}function Ao(t,e,n,r,o){if(!o)throw new me(`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 me(`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 me(`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 xi(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 me(`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 Oi="shared:",Jt="speech:",Et="realtime:";function gt(t){return t.sharedApp?Oi+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 Oo(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ne(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Qd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Zd(t){let e=t.map(Qd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var ec={stt:"stt",tts:"tts"};function mt(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:ec[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Ti(t,e){let n=Oo(t,e);return n.length>0?n:Eo(t,e)}function bn(t,e){return Ti(t.appSlug,e)}function tc(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 me(`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 Zn=6e4,er=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Zn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Zn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Zn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Zn;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 De)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
+ `),_n}let r=ci(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(ko(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(Oi)||o.startsWith(Jt)||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 oe(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=vo(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=Ne(s),l=n.endpoints.filter(c=>Ne(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:vo(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=Ne(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 l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new oe(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new oe(`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.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===Ne(l.model_id)||o===Ne(`${l.model_id}-${l.variant}`));if(a)throw new oe(`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=Sn(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 gt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,gt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Sn(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Jt+gt(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Et+(0,Ai.randomUUID)())}async evictHandle(e){let n=Wt(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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.then(o=>this.snapshotMintId(o),()=>{}),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:kn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:kn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Wt(e);if(!n)throw new ee(`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 ee(`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&&this.mintedIds.get(i)!==o)throw new ee(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:_n;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 l=(n?jt(n):[]).map(u=>{let d=s.filter(v=>v.model_id===u.model_id&&v.variant===u.variant),c=Xn(d),f=qt(d),h=Ro(d),m=wn(u.model_id,u.variant,i),_=xo(d);return St({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},..._.published.length>0?{voices:[..._.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Qn(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return vi(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=Ao(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return xi(`${r.modelId}:${r.variant}`,s).includes(n)}return Ei(Oo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?mt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:mt(bn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?mt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":mt(bn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?mt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":mt(bn(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):bn(n,r);return tc(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):bn(n,r);return xo(o)}async imageModelList(){let e=await this.catalogRows(),n=_n,r=[];for(let s of await this.availableIds()){let i=Ei(Oo(s,e));i.length!==0&&r.push(St({...Qn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of jt(o)){let i=Ao(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=xi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=St({id:`${s.model_id}:${s.variant}`,object:"model",created:qt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=_n,r=[];for(let s of await this.availableIds())mt(Ti(s,e))==="stt"&&r.push(Qn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of jt(o)){let i=Ao(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(mt(i)!=="stt")continue;let a=St({id:`${s.model_id}:${s.variant}`,object:"model",created:qt(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 Pi(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 tr(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 ic=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ci(t){let e=t?.code;return typeof e=="string"&&ic.has(e)}function et(t,e){try{return t.write(e),!0}catch(n){if(Ci(n))return!1;throw n}}function Li(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Ci(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)}}}I();var _e=require("@prometheus-io/client"),na=require("http");I();var ac={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"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","/v1/realtime":"realtime"};function lc(t){return ac[t]??null}var Ni=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function uc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function dc(t){return t==="surface"}function cc(t){let e=t?.ledgerFailureReason;return Ni.includes(e)?e:"unknown"}var pc=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],$i=["priced","unpriced"],fc={written:$i,already_written:$i,skipped:pc,failed:Ni},Ui=Object.entries(fc).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function mc(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function gc(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 hc=256,Mi=4096,Rn=12e4,yc=250,wc=8e3,at=[],Po=new Set,En=0,Vt=!1;function Di(){return at.length}function Fi(t=Date.now()){let e=at[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var nr=new Set;function Bi(){return En===0&&at.length===0}function Hi(){if(Bi()){Vt=!1;for(let t of[...nr])t()}}async function ji(t=Gi){return Bi()?!0:await new Promise(e=>{let n,r=()=>{nr.delete(r),clearTimeout(n),e(!0)};nr.add(r),n=setTimeout(()=>{nr.delete(r),e(!1)},t),n.unref?.()})}function qi(){Vt=!0;let t=[...at.splice(0,at.length),...Po];for(let e of t)e.settled||xt(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 ${Gi}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Hi(),t.length}var Gi=5e3;function Wi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
+ `}function _c(t){et(process.stdout,t)}function Ji(t,e){try{t(e)}catch{}}function rr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??_c,o=lc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Ji(r,Wi("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 l;if(a.kind==="catalog")l={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}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:gc(e),completed_at:e.ts,billable_outcome:mc(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,session_seconds:e.session_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(at.length>=Mi){i("queue_full",`${at.length} ledger writes are already waiting (capacity ${Mi}, ${En} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}at.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),En<hc&&(En+=1,vc())}async function vc(){try{for(;;){let t=bc();if(t===void 0)return;Po.add(t);try{await Sc(t)}finally{Po.delete(t)}}}finally{En-=1,Hi()}}function bc(){let t=Date.now();for(;;){let e=at.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Rn)return e;xt(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 ${Rn}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 Sc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);xt(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=uc(o);if(s!==null){xt(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=cc(o),a=Date.now()-t.queuedAt;if(Vt){xt(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(dc(i)&&a<Rn){if(await Rc(kc(t.attempts)),Vt||Date.now()-t.queuedAt>=Rn){let l=Date.now()-t.queuedAt;xt(t,{outcome:"failed",reason:Vt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Vt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${Rn}ms dwell bound (waited ${l}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}xt(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 kc(t){return Math.min(wc,yc*2**Math.max(0,t-1))}function Rc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function xt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Ji(t.report,Wi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}I();I();var sr="/v1/usage/requests",Vi=1e4,Ec=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ht=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},we=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},or=class extends we{constructor(e){super(e),this.name="UsageWithholdingError"}},Xi=1024*1024;function $o(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ht(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ht(`"${e}" must be an array of uuid strings`);if(n.length>Vi)throw new ht(`"${e}" carries ${n.length} ids; at most ${Vi} 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"||!Ec.test(s))throw new ht(`"${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 Qi(t){return $o(t,"inference_ids")}var xc=["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 Kt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is not a non-empty string (got ${Yt(r)})`);return r}function Co(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is neither null nor a non-empty string (got ${Yt(r)})`);return r}function zt(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 we(`${n}: ${e} is not a number (got ${Yt(o)})`);if(r&&!Number.isSafeInteger(s))throw new we(`${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 we(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Ac=40,Ki=64,zi=600;function Zi(t){let e=Object.keys(t).sort(),r=e.slice(0,Ac).map(o=>o.length>Ki?`${o.slice(0,Ki)}\u2026`:o).join(", ");return r.length>zi&&(r=`${r.slice(0,zi)}\u2026`),`${e.length} keys present: [${r}]`}function Yt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Lo(t){et(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
+ `)}function Ic(t,e){let n;try{n=t(e)}catch{Yi(t,e);return}Oc(n)&&Promise.resolve(n).catch(()=>{Yi(t,e)})}function Oc(t){return typeof t?.then=="function"}function Yi(t,e){if(t!==Lo)try{Lo(e)}catch{}}function ea(t,e=Lo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Zi(t):Yt(t);throw new we(`the usage surface answered without a "requests" array: got ${Yt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Tc(n[o],s))}catch(i){if(i instanceof or||!(i instanceof we))throw i;Ic(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new we(`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 Tc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`${e} is not an object: got ${Yt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new or(`${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 xc)if(!Object.hasOwn(n,o))throw new we(`${e} has no "${o}" column (${Zi(n)})`);let r=zt(n,"http_status",e,!0);if(r===null)throw new we(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Kt(n,"inference_id",e),model_id:Kt(n,"model_id",e),identity_kind:Kt(n,"identity_kind",e),variant:Co(n,"variant",e),task:Kt(n,"task",e),http_status:r,started_at:Kt(n,"started_at",e),completed_at:Kt(n,"completed_at",e),prompt_tokens:zt(n,"prompt_tokens",e,!0),completion_tokens:zt(n,"completion_tokens",e,!0),output_units:zt(n,"output_units",e,!1),output_minutes:zt(n,"output_minutes",e,!1),cost_nano_usd:zt(n,"cost_nano_usd",e,!0),price_version:Co(n,"price_version",e),priced_at:Co(n,"priced_at",e)}}function ir(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 we(`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 we(`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 xn="/partners/huggingface/v1/billing/requests";function Pc(t){return $o(t,"requestIds")}function Cc(t){return t>=200&&t<=399}function Lc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Cc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ta(t,e){let n=Pc(t),r=await e(n);return ir(r,n),Lc(r)}var Mo=9464,ar="/metrics",lr="(other)",$c="(none)",Mc=64,Nc=128,Uc=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/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",sr,xn,kt],Dc=new Set(Uc);function Fc(t){return Dc.has(t)?t:lr}function Bc(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var ur=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$c:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,lr):(this.admitted.add(e),e):lr}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},dr=class{registry=new _e.Registry;modelLabel=new ur(Mc);orgLabel=new ur(Nc);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new _e.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 _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 Ui)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"},Di()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Fi()/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]}),this.lanesReady=new _e.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 _e.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 _e.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 _e.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 _e.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,_e.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=Fc(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 l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?lr:e.method,status_class:Bc(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,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 ra(t){return(0,na.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==ar){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${ar}
11
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)}
12
- `);return}n.end()})})}E();var Oo=require("crypto"),Ji=require("http"),Io=9465,vc="x-urun-key-id",bc="x-urun-key-fingerprint",Sc="urun-ratelimit-bucket:",kc="urun-ratelimit-tier:",Vi="anonymous",Rc=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Ec(t){return(0,Oo.createHash)("sha256").update(`${Sc}${t}`).digest("hex")}function xc(t){return(0,Oo.createHash)("sha256").update(`${kc}${t}`).digest("hex")}function Ac(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Rc.test(n)?n:null}function Ki(){return(0,Ji.createServer)((t,e)=>{let n=Ac(t.headers.authorization);e.setHeader(vc,n===null?Vi:Ec(n)),e.setHeader(bc,n===null?Vi:xc(n)),e.writeHead(200),e.end()})}E();var Oc=8080,To="serve",kt="0.0.0.0";function Ic(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function zi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Oc: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=wi(zn(Ic(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?zn(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:zn(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()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((x,P)=>Object.values(p)[P]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let _=m.length===0?p:void 0,S={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"],A=b.filter((x,P)=>Object.values(S)[P]==="");if(A.length!==0&&A.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${A.join(", ")}, which would half-configure the pooler cutover`);let f=A.length===0?S:void 0,g={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},y=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],k=y.filter((x,P)=>Object.values(g)[P]==="");if(k.length!==0&&k.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${k.join(", ")}, which would half-configure the machine-identity rung`);let T=g.issuers.split(",").map(x=>x.trim()).filter(x=>x!=="");if(T.length===0&&k.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let w=Number(g.tokenTtlS);if(k.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(g.tokenTtlS)}`);let O=k.length===0?{jwksBaseUrl:g.jwksBaseUrl,issuers:T,tokenTtlS:w}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:_,pooler:f,machine:O}}E();var Fl=require("http");E();E();var Xi="audio",Po=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}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),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}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 Qi(t,e,n=1e4){let r=new Po(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(Xi);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await Tc(t,n);return await r.startInbound(i),r}function Tc(t,e){let n=t.stream(Xi);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 Yi="rt-video-in",kn=256e3;function Co(t){let e=t.stream(Yi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Yi}') 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>kn)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${kn}-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 Pc=24e3,Sn=480,Cc=111;async function Lc(){let t=await import("opusscript"),e=t.default??t;return new e(Pc,1,2048)}async function Zi(){let t=await import("werift"),e=await Lc();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>=Sn;){let d=u.subarray(l,l+Sn);l+=Sn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Sn);o=o+1&65535,s=s+Sn>>>0;let h=new t.RtpHeader({version:2,payloadType:Cc,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,p);n.writeRtp(m)}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}}}E();var or=require("@urun-sh/core"),Lo="rt-video-out";var Mc="h264";function $c(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 Nc(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;$c(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 ea="urun.videoOut.v2-ws";function ta(t){let e=t.stream(Lo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Lo}') 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: "${Lo}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Nc(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:Mc,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 ur="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Uc=1007,ra=1008,at=1011,lr=1008,N=class extends Error{constructor(n,r=Uc){super(n);this.closeCode=r}closeCode},ve=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,sr=["setup","clientContent","realtimeInput","toolResponse"];function oa(t){let e;try{e=JSON.parse(t)}catch{throw new N("client message is not valid JSON")}let n=ve(e);if(!n)throw new N("client message must be a JSON object");let r=sr.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!sr.includes(a));if(o.length>0)throw new N(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${sr.join(", ")}`);if(r.length!==1)throw new N(`client message must contain exactly one of ${sr.join(", ")} (got ${r.length})`);let s=r[0],i=ve(n[s]);if(!i)throw new N(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function sa(t,e){if(typeof t=="string")return t;let n=ve(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new N(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ve(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new N(`${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 N(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new N(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
- `)}var Dc={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Rt="urun.videoOut";function ia(t){return{framing:ea,codec:t}}function aa(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 Fc={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Hc=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Rt],na=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function jc(t){let e=ve(t);if(!e)throw new N("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new N(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ve(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new N("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new N(`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 N("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(!na.includes(e.activityHandling))throw new N(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${na.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Bc=["temperature","maxOutputTokens","responseModalities"];function ua(t){for(let[c,p]of Object.entries(Fc))if(t[c]!==void 0)throw new N(p);for(let c of Object.keys(t))if(!Hc.includes(c))throw new N(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new N('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ve(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new N("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Bc.includes(c))throw new N(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new N("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new N("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 h=String(p).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new N(`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:sa(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new N("setup.tools must be an array");a=[];for(let c of t.tools){let p=ve(c);if(!p)throw new N("setup.tools entries must be objects");for(let h of Object.keys(p))if(h!=="functionDeclarations")throw new N(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new N("tool.functionDeclarations must be an array");for(let h of p.functionDeclarations){let m=ve(h);if(!m||typeof m.name!="string")throw new N("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ve(t.sessionResumption);if(!c)throw new N("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new N(`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 N("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?Dc:jc(t.realtimeInputConfig),d=!1;if(t[Rt]!==void 0){if(!ve(t[Rt]))throw new N(`setup["${Rt}"] 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 la(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function da(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ca(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new N(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new N("clientContent.turns must be an array");let n=[];for(let r of e){let o=ve(r);if(!o)throw new N("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 N(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:sa(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var ir=16e3,pa=24e3,qc=`audio/pcm;rate=${pa}`,fa=Buffer.alloc(960).toString("base64");function Gc(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 Wc(t){let e=ve(t);if(!e)throw new N("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new N(`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 N("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 N("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Vc(t){let e=ve(t);if(!e)throw new N("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new N(`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])!==ir)throw new N(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${ir} Hz (audio/pcm;rate=${ir})`);if(typeof e.data!="string"||e.data.length===0)throw new N("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 N(`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=Gc(o,ir,pa);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function ma(t){if(t.mediaChunks!==void 0)throw new N('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 N("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ve(t[o]);if(!s||Object.keys(s).length!==0)throw new N(`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 N(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new N(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Vc(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Wc(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new N("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new N("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ga(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new N(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new N("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ve(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new N("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 ha(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ya(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:qc,data:t}}]}}}}function wa(t){let e=ve(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=ve(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=ve(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=ve(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new N(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,at);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new N(`upstream function_call arguments are not valid JSON: ${c}`,at)}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=ve(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}}E();var _a=require("crypto"),va=require("ws");var Jc=256,Mo=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Jc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Kc="local",Rn=t=>t.slice(0,120),$o=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 ne){this.ws.close(ra,Rn(e.message));return}if(e instanceof Q){this.ws.close(lr,Rn(e.message));return}if(e instanceof N){this.ws.close(e.closeCode,Rn(e.message));return}this.ws.close(at,Rn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=oa(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(`"${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}=ca(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=ma(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:fa);return}this.transcript.push(...ga(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new N("setup may only be sent once, as the first client message");let n=ua(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new N("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",lr);if(s.model!==n.model)throw new N(`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 N("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 N(`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`,lr);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(aa(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Rt]=ia(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 N("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new N("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",at);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ya(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 N("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new N("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",at);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 N(`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 N("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 N("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,_a.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(la(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(da(e.timeLeftMs)),this.ws.close(at,Rn(`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 N(`upstream error: ${JSON.stringify(l)}`,at);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=ha(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new N("upstream produced no response.completed event",at);let{messages:i,assistantItems:a}=wa(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Et=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function zc(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 Et(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 Et(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 Et(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function No(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 va.WebSocketServer({noServer:!0}),o=new Mo;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===ur&&(a.on("error",()=>{}),(async()=>{let d=zc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Et(401,"invalid local proxy api key");c={clients:e.clients,scope:Kc}}r.handleUpgrade(i,a,u,p=>{new $o(p,c,o)})})().catch(d=>{let c=502;(d instanceof Et||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",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
12
+ `);return}n.end()})})}I();var No=require("crypto"),sa=require("http"),Uo=9465,Hc="x-urun-key-id",jc="x-urun-key-fingerprint",qc="urun-ratelimit-bucket:",Gc="urun-ratelimit-tier:",oa="anonymous",Wc=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Jc(t){return(0,No.createHash)("sha256").update(`${qc}${t}`).digest("hex")}function Vc(t){return(0,No.createHash)("sha256").update(`${Gc}${t}`).digest("hex")}function Kc(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Wc.test(n)?n:null}function ia(){return(0,sa.createServer)((t,e)=>{let n=Kc(t.headers.authorization);e.setHeader(Hc,n===null?oa:Jc(n)),e.setHeader(jc,n===null?oa:Vc(n)),e.writeHead(200),e.end()})}I();var zc=8080,Do="serve",At="0.0.0.0";function Yc(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function aa(t=process.env){let e=(t.PORT??"").trim(),n=e===""?zc: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=Pi(tr(Yc(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?tr(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 l=i?{catalogUrl:tr(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!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=u?{keyId:d,key:u}:void 0,f={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()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((w,T)=>Object.values(f)[T]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let _=m.length===0?f:void 0,R={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},v=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=v.filter((w,T)=>Object.values(R)[T]==="");if(b.length!==0&&b.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let p=b.length===0?R:void 0,g={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},y=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],k=y.filter((w,T)=>Object.values(g)[T]==="");if(k.length!==0&&k.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${k.join(", ")}, which would half-configure the machine-identity rung`);let O=g.issuers.split(",").map(w=>w.trim()).filter(w=>w!=="");if(O.length===0&&k.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let x=Number(g.tokenTtlS);if(k.length===0&&(!Number.isFinite(x)||x<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(g.tokenTtlS)}`);let P=k.length===0?{jwksBaseUrl:g.jwksBaseUrl,issuers:O,tokenTtlS:x}:void 0,E=(t.URUN_WORKOS_ISSUERS??"").trim(),C=E.split(",").map(w=>w.trim()).filter(w=>w!=="");if(E!==""&&C.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let w of C){let T;try{T=new URL(w)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(w)}`)}if(T.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${w}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:_,pooler:p,machine:P,...C.length>0?{userIssuers:C}:{}}}I();var id=require("http");I();I();var ua="audio",Fo=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}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)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function da(t,e,n=1e4){try{return await Xc(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Xc(t,e,n){let r=new Fo(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(ua);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await Qc(t,n);return await r.startInbound(i),r}function Qc(t,e){let n=t.stream(ua);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=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var la="rt-video-in",In=256e3;function Ho(t){let e=t.stream(la),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${la}') 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>In)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${In}-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 Zc=24e3,An=480,ep=111,tp=50,cr=null;async function np(){if(cr)return;let t=await import("opusscript");cr=t.default??t}function rp(){if(!cr)throw new Error("[opus-guard] opusscript module not loaded");return new cr(Zc,1,2048)}var Bo=class{constructor(e=rp){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=tp}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function ca(){let t=await import("werift");await np();let e=new Bo;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 l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=An;){let d=l.subarray(u,u+An);u+=An;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,An);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+An>>>0;let h=new t.RtpHeader({version:2,payloadType:ep,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}I();var pr=require("@urun-sh/core"),jo="rt-video-out";var op="h264";function sp(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 ip(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;sp(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 pa="urun.videoOut.v2-ws";function fa(t){let e=t.stream(jo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${jo}') 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=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${jo}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=ip(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:op,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var hr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ap=1007,ga=1008,lt=1011,yr=1008,D=class extends Error{constructor(n,r=ap){super(n);this.closeCode=r}closeCode},Se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,fr=["setup","clientContent","realtimeInput","toolResponse"];function ha(t){let e;try{e=JSON.parse(t)}catch{throw new D("client message is not valid JSON")}let n=Se(e);if(!n)throw new D("client message must be a JSON object");let r=fr.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!fr.includes(a));if(o.length>0)throw new D(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${fr.join(", ")}`);if(r.length!==1)throw new D(`client message must contain exactly one of ${fr.join(", ")} (got ${r.length})`);let s=r[0],i=Se(n[s]);if(!i)throw new D(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ya(t,e){if(typeof t=="string")return t;let n=Se(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new D(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=Se(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new D(`${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 D(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new D(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
+ `)}var lp={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},It="urun.videoOut";function wa(t){return{framing:pa,codec:t}}function _a(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[It]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var up={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},dp=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",It],ma=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function cp(t){let e=Se(t);if(!e)throw new D("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new D(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Se(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new D("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new D(`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 D("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(!ma.includes(e.activityHandling))throw new D(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ma.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var pp=["temperature","maxOutputTokens","responseModalities"];function va(t){for(let[c,f]of Object.entries(up))if(t[c]!==void 0)throw new D(f);for(let c of Object.keys(t))if(!dp.includes(c))throw new D(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new D('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=Se(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new D("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!pp.includes(c))throw new D(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new D("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new D("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 f of c){let h=String(f).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new D(`responseModalities ${JSON.stringify(f)} 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:ya(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new D("setup.tools must be an array");a=[];for(let c of t.tools){let f=Se(c);if(!f)throw new D("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new D(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new D("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let m=Se(h);if(!m||typeof m.name!="string")throw new D("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=Se(t.sessionResumption);if(!c)throw new D("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new D(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new D("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?lp:cp(t.realtimeInputConfig),d=!1;if(t[It]!==void 0){if(!Se(t[It]))throw new D(`setup["${It}"] 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:u,sessionResumption:l,videoOut:d}}function ba(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Sa(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ka(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new D(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new D("clientContent.turns must be an array");let n=[];for(let r of e){let o=Se(r);if(!o)throw new D("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 D(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:ya(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var mr=16e3,Ra=24e3,fp=`audio/pcm;rate=${Ra}`,Ea=Buffer.alloc(960).toString("base64");function mp(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 l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function gp(t){let e=Se(t);if(!e)throw new D("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new D(`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 D("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 D("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function hp(t){let e=Se(t);if(!e)throw new D("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new D(`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])!==mr)throw new D(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${mr} Hz (audio/pcm;rate=${mr})`);if(typeof e.data!="string"||e.data.length===0)throw new D("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 D(`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=mp(o,mr,Ra);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function xa(t){if(t.mediaChunks!==void 0)throw new D('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 D("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=Se(t[o]);if(!s||Object.keys(s).length!==0)throw new D(`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 D(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new D(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:hp(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:gp(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new D("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new D("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Aa(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new D(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new D("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Se(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new D("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 Ia(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Oa(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:fp,data:t}}]}}}}function Ta(t){let e=Se(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=Se(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=Se(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=Se(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new D(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,lt);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new D(`upstream function_call arguments are not valid JSON: ${c}`,lt)}r.push({id:d.call_id,name:d.name,args:f}),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=Se(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}I();var Pa=require("crypto"),Ca=require("ws");var yp=256,qo=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>yp;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},wp="local",On=t=>t.slice(0,120),Go=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 oe){this.ws.close(ga,On(e.message));return}if(e instanceof ee){this.ws.close(yr,On(e.message));return}if(e instanceof D){this.ws.close(e.closeCode,On(e.message));return}this.ws.close(lt,On(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=ha(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 D(`"${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}=ka(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=xa(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:Ea);return}this.transcript.push(...Aa(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new D("setup may only be sent once, as the first client message");let n=va(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new D("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",yr);if(s.model!==n.model)throw new D(`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 D("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 D(`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`,yr);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(u=>this.send(_a(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[It]=wa(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 D("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new D("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",lt);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Oa(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 D("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new D("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",lt);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 D(`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 D("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 D("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,Pa.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ba(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(Sa(e.timeLeftMs)),this.ws.close(lt,On(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new D(`upstream error: ${JSON.stringify(u)}`,lt);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=Ia(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new D("upstream produced no response.completed event",lt);let{messages:i,assistantItems:a}=Ta(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ot=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function _p(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(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 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&&i!==void 0&&i!=="")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 l of r)a=l;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 Wo(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 Ca.WebSocketServer({noServer:!0}),o=new qo;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===hr&&(a.on("error",()=>{}),(async()=>{let d=_p(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ot(401,"invalid local proxy api key");c={clients:e.clients,scope:wp}}r.handleUpgrade(i,a,l,f=>{new Go(f,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 f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${f}\r
14
14
  Connection: close\r
15
15
  \r
16
16
  ${h}\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)}E();var yt=require("ws");E();E();var ba=require("crypto"),Sa="Inference-Id";function En(){return(0,ba.randomUUID)()}function Uo(t){return t==="/v1"||t.startsWith("/v1/")}function ka(t,e){if(!Uo(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 xn(t){return`resp_${t}`}function Ra(t){return`chatcmpl-${t}`}function Ea(t){return`msg_${t}`}function Fe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function xa(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 Aa(t){return`${JSON.stringify(t)}
18
- `}var Yc=256,Xc=128;function Pe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Xc)}var xt=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>=Yc?"(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}}}},Qc=256;function Zc(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var At=class extends Error{},Vt=class{conversations=new Map;thread(e,n){let r=Zc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new At(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Qc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Oa=new WeakMap;function An(t){let e=Oa.get(t);return e||(e=new Vt,Oa.set(t,e)),e}function Jt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function et(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 gt=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}))}},ep=["<tool_call>","<function="];function tp(t){return ep.find(e=>t.includes(e))}function Ot(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function It(t,e,n){if(!(!t||e>0))return tp(n)}function zt(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 ut(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function np(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 Do(t,e){let n=np(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var He=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Yt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof At?new He(n.message,"previous_response_not_found",400,"previous_response_id"):new He(String(n instanceof Error?n.message:n),"invalid_input")}}function Ia(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Fo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new He("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}:{},...Ia(e)!==void 0?{response_format:Ia(e)}:{}},o)}async function On(t){let{body:e,clients:n,store:r,stats:o}=t,s=Yt(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=Pe(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await Fo(n,e,s,!0,c?Fe(c):void 0);return{responseId:i,events:ip({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function rp(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?sp(o[i++],u):u),...op(r,n)]}function op(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 sp(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*ip(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=J=>J.response&&typeof J.response=="object"?{...J,response:{...J.response,id:r}}:J,p=`item_${r.slice(5)}`,h=!1,m=!1,_=0;function*S(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],A=(J,$)=>{b.push({output_index:J,item:$})},f=!1,g=0,y="",k=0,T="";function*w(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:T};let J={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:T}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:J},A(g,J),T=""}let O=!1,x=0,P="",I=0,M="",G="";function*V(J){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:P,output_index:x,content_index:0,text:M},yield{type:"response.content_part.done",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:M}};let $={id:P,type:"message",role:"assistant",status:J,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:x,item:$},A(x,$),M=""}let Z=new gt,Y=null,Te=-1;function*oe(J){if(!Y)return;let $=Y;Y=null,yield{type:"response.function_call_arguments.done",item_id:$.fcId,output_index:$.outputIndex,arguments:$.args};let re={id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:$.args,status:J};yield{type:"response.output_item.done",output_index:$.outputIndex,item:re},A($.outputIndex,re)}let Se=!1;for await(let J of l.track(e,o,t.turn)){d.push(J);let $=String(J.type??"");if($==="response.created"||$==="response.in_progress"){h=!0,yield c(J);continue}if($==="response.output_item.added"){m=!0,yield c(J);continue}if($==="response.reasoning_text.delta"&&!m){yield*S(),f||(f=!0,g=_++,k+=1,y=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),T+=String(J.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:J.delta};continue}if($==="response.output_text.delta"&&!m){yield*S(),yield*w(),O||(O=!0,x=_++,I+=1,P=I===1?p:`${p}_${I}`,yield{type:"response.output_item.added",output_index:x,item:{id:P,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:""}}),M+=String(J.delta??""),G+=String(J.delta??""),yield{type:$,item_id:P,output_index:x,content_index:0,delta:J.delta};continue}let re=m?null:Kt(J);if(re){if(yield*S(),yield*w(),yield*V("completed"),Z.add(re),re.tool_index!==Te){yield*oe("completed"),Te=re.tool_index;let rt=_++;Y={fcId:`fc_${r.slice(5)}_${re.tool_index}`,outputIndex:rt,callId:re.call_id,name:re.name,args:""},yield{type:"response.output_item.added",output_index:rt,item:{id:Y.fcId,type:"function_call",call_id:Y.callId??Y.fcId,name:Y.name??"",arguments:"",status:"in_progress"}}}Y&&(re.call_id&&(Y.callId=re.call_id),re.name&&(Y.name=re.name),Y.args+=re.delta,yield{type:"response.function_call_arguments.delta",item_id:Y.fcId,output_index:Y.outputIndex,delta:re.delta});continue}if($==="response.completed"&&!m){let rt=Jt(J.response),ie=It(s,Z.size+rt.length,G);if(ie){Se=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(o,ie)}};break}if(yield*w(),yield*V("completed"),yield*oe("completed"),Z.size===0)for(let de of rt){let Le=_++,ot=de.id??de.call_id??`fc_${Le}`,Me=de.arguments??"",cn={id:ot,type:"function_call",call_id:de.call_id??ot,name:de.name??""};yield{type:"response.output_item.added",output_index:Le,item:{...cn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Le,delta:Me},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Le,arguments:Me};let st={...cn,arguments:Me,status:"completed"};yield{type:"response.output_item.done",output_index:Le,item:st},A(Le,st)}let ae=rp(b,J.response);yield ae.length>0?c({...J,response:{...J.response,output:ae}}):c(J);continue}yield c(J)}if(yield*w(),yield*V("incomplete"),yield*oe("incomplete"),i&&!Se){let J=et(d);u.remember(r,n,Do(J,zt(d,J)),a)}}E();E();var je=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},Ee=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};E();var ht=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)}},In=class extends ht{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Ho=class extends ht{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")}},We=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},dr=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 In;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 In;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 Ho(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 In}}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)`)}};E();var jo=require("@urun-sh/core"),Ve=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 Ta(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 cr),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof Q||l instanceof jo.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof cr?(await r.return?.(void 0),new Ve("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 Ve("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 Ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var cr=class extends Error{constructor(){super("stream idle timeout")}};function Pa(t){return t instanceof Ve?!1:t instanceof Q?!0:t instanceof jo.SessionFailedError?t.kind==="transport-failed":!1}var ap=[/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 Ke(t){return!ap.some(e=>e.test(t))}function ze(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 Ue(t,e){if(t instanceof Q)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=Ca(t);return n||{message:ze(e?.inferenceId??null),redacted:!0}}function Ca(t){return t instanceof ct?{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 ne?{message:t.message,redacted:!1}:t instanceof je?{message:t.message,redacted:!1}:t instanceof ht?{message:t.message,redacted:!1}:t instanceof Ve?Ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof We?{message:t.message,redacted:!1}:t instanceof Ee?{message:t.message,redacted:!1}:null}function Xt(t,e,n){let r=n??(i=>console.error(i)),o=Ca(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Je(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Je(e)}`),`the ${t} upstream failed while serving this request`)}function tt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ke(e)?e:null}function Je(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Wo="/v1/responses",up=64*1024*1024,lp=8*1024*1024,dp=16,La=32,Ma=3600*1e3,cp=/^[A-Za-z0-9._-]{1,256}$/;function Ce(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var pp=Ce(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 Vo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function fp(t){for(;t.bufferedAmount>lp&&t.readyState===yt.WebSocket.OPEN;){let{promise:e,resolve:n}=Vo();setTimeout(n,5),await e}}var qo=class extends Vt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof At))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Go=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 qo(An(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(Ce(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ma/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ma).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(Ce(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(Ce(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(Ce(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(Ce(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(Ce(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(Ce(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"||!cp.test(o.stream_id)){this.sendFrame(pp);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=La){this.sendFrame(Ce(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${La}). 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=En();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await On({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:xn(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!==yt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await fp(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=En(),o=xn(r);try{let s=Yt(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:Je(e);if(e instanceof He)return Ce(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof ne)return Ce(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Q){let a=Ue(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}`),Ce(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}`),Ce(s.status,{type:s.openaiType,message:o},n);let i=Ue(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}`),Ce(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=tt(o),a=i??ze(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)}`),Ce(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=dp;){let{promise:e,resolve:n}=Vo();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!==yt.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!==yt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function pr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\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(l=>l===void 0?i():a(l)))})(),s)}I();var _t=require("ws");I();I();var La=require("crypto"),$a="Inference-Id";function Tt(){return(0,La.randomUUID)()}function Jo(t){return t==="/v1"||t.startsWith("/v1/")}function Ma(t,e){if(!Jo(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 Tn(t){return`resp_${t}`}function Na(t){return`chatcmpl-${t}`}function Ua(t){return`msg_${t}`}function Fe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Da(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_seconds: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 Fa(t){return`${JSON.stringify(t)}
18
+ `}var vp=256,bp=128;function Pe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,bp)}var Pt=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>=vp?"(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 u of e)u.type==="response.output_text.delta"&&typeof u.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+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Sp=256;function kp(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 Ct=class extends Error{},Xt=class{conversations=new Map;thread(e,n){let r=kp(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ct(`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<=Sp)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ba=new WeakMap;function Pn(t){let e=Ba.get(t);return e||(e=new Xt,Ba.set(t,e)),e}function Qt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function tt(t){return t.find(e=>e.type==="response.completed")?.response??null}function Zt(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 yt=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}))}},Rp=["<tool_call>","<function="];function Ep(t){return Rp.find(e=>t.includes(e))}function Lt(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 $t(t,e,n){if(!(!t||e>0))return Ep(n)}function en(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 ut(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function xp(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 Vo(t,e){let n=xp(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function tn(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ct?new Be(n.message,"previous_response_not_found",400,"previous_response_id"):new Be(String(n instanceof Error?n.message:n),"invalid_input")}}function Ha(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ko(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Be("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}:{},...Ha(e)!==void 0?{response_format:Ha(e)}:{}},o)}async function Cn(t){let{body:e,clients:n,store:r,stats:o}=t,s=tn(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,l=e.store!==!1,u=Pe(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await Ko(n,e,s,!0,c?Fe(c):void 0);return{responseId:i,events:Tp({events:f,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function Ap(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?Op(o[i++],l):l),...Ip(r,n)]}function Ip(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function Op(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*Tp(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=z=>z.response&&typeof z.response=="object"?{...z,response:{...z.response,id:r}}:z,f=`item_${r.slice(5)}`,h=!1,m=!1,_=0;function*R(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],b=(z,N)=>{v.push({output_index:z,item:N})},p=!1,g=0,y="",k=0,O="";function*x(){if(!p)return;p=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:O};let z={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:O}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:z},b(g,z),O=""}let P=!1,E=0,C="",w=0,T="",$="";function*M(z){if(!P)return;P=!1,yield{type:"response.output_text.done",item_id:C,output_index:E,content_index:0,text:T},yield{type:"response.content_part.done",item_id:C,output_index:E,content_index:0,part:{type:"output_text",text:T}};let N={id:C,type:"message",role:"assistant",status:z,content:[{type:"output_text",text:T}]};yield{type:"response.output_item.done",output_index:E,item:N},b(E,N),T=""}let F=new yt,G=null,se=-1;function*X(z){if(!G)return;let N=G;G=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let te={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:z};yield{type:"response.output_item.done",output_index:N.outputIndex,item:te},b(N.outputIndex,te)}let ae=!1;for await(let z of u.track(e,o,t.turn)){d.push(z);let N=String(z.type??"");if(N==="response.created"||N==="response.in_progress"){h=!0,yield c(z);continue}if(N==="response.output_item.added"){m=!0,yield c(z);continue}if(N==="response.reasoning_text.delta"&&!m){yield*R(),p||(p=!0,g=_++,k+=1,y=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),O+=String(z.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:z.delta};continue}if(N==="response.output_text.delta"&&!m){yield*R(),yield*x(),P||(P=!0,E=_++,w+=1,C=w===1?f:`${f}_${w}`,yield{type:"response.output_item.added",output_index:E,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:E,content_index:0,part:{type:"output_text",text:""}}),T+=String(z.delta??""),$+=String(z.delta??""),yield{type:N,item_id:C,output_index:E,content_index:0,delta:z.delta};continue}let te=m?null:Zt(z);if(te){if(yield*R(),yield*x(),yield*M("completed"),F.add(te),te.tool_index!==se){yield*X("completed"),se=te.tool_index;let ot=_++;G={fcId:`fc_${r.slice(5)}_${te.tool_index}`,outputIndex:ot,callId:te.call_id,name:te.name,args:""},yield{type:"response.output_item.added",output_index:ot,item:{id:G.fcId,type:"function_call",call_id:G.callId??G.fcId,name:G.name??"",arguments:"",status:"in_progress"}}}G&&(te.call_id&&(G.callId=te.call_id),te.name&&(G.name=te.name),G.args+=te.delta,yield{type:"response.function_call_arguments.delta",item_id:G.fcId,output_index:G.outputIndex,delta:te.delta});continue}if(N==="response.completed"&&!m){let ot=Qt(z.response),ue=$t(s,F.size+ot.length,$);if(ue){ae=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Lt(o,ue)}};break}if(yield*x(),yield*M("completed"),yield*X("completed"),F.size===0)for(let fe of ot){let Le=_++,st=fe.id??fe.call_id??`fc_${Le}`,$e=fe.arguments??"",hn={id:st,type:"function_call",call_id:fe.call_id??st,name:fe.name??""};yield{type:"response.output_item.added",output_index:Le,item:{...hn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:st,output_index:Le,delta:$e},yield{type:"response.function_call_arguments.done",item_id:st,output_index:Le,arguments:$e};let it={...hn,arguments:$e,status:"completed"};yield{type:"response.output_item.done",output_index:Le,item:it},b(Le,it)}let de=Ap(v,z.response);yield de.length>0?c({...z,response:{...z.response,output:de}}):c(z);continue}yield c(z)}if(yield*x(),yield*M("incomplete"),yield*X("incomplete"),i&&!ae){let z=tt(d);l.remember(r,n,Vo(z,en(d,z)),a)}}I();I();var He=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},xe=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Mt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};I();var wt=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)}},Ln=class extends wt{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},zo=class extends wt{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}},wr=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 Ln;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 Ln;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 l=r+n-Date.now();if(l<=0)throw new zo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);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 Ln}}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)`)}};I();var Yo=require("@urun-sh/core"),Ve=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)}},Xo=33e4;function ja(t,e=Xo){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new _r),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof ee||u instanceof Yo.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof _r?(await r.return?.(void 0),new Ve("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 Ve("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var _r=class extends Error{constructor(){super("stream idle timeout")}};function qa(t){return t instanceof Ve?!1:t instanceof ee?!0:t instanceof Yo.SessionFailedError?t.kind==="transport-failed":!1}var Pp=[/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 Ke(t){return!Pp.some(e=>e.test(t))}function ze(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 Ue(t,e){if(t instanceof ee)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=Ga(t);return n||{message:ze(e?.inferenceId??null),redacted:!0}}function Ga(t){return t instanceof ft?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof me?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof oe?{message:t.message,redacted:!1}:t instanceof He?{message:t.message,redacted:!1}:t instanceof wt?{message:t.message,redacted:!1}:t instanceof Ve?Ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof Je?{message:t.message,redacted:!1}:t instanceof xe?{message:t.message,redacted:!1}:null}function nn(t,e,n){let r=n??(i=>console.error(i)),o=Ga(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${je(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${je(e)}`),`the ${t} upstream failed while serving this request`)}function nt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ke(e)?e:null}function je(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var es="/v1/responses",Cp=64*1024*1024,Lp=8*1024*1024,$p=16,Wa=32,Ja=3600*1e3,Mp=/^[A-Za-z0-9._-]{1,256}$/;function Ce(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Np=Ce(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 ts(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Up(t){for(;t.bufferedAmount>Lp&&t.readyState===_t.WebSocket.OPEN;){let{promise:e,resolve:n}=ts();setTimeout(n,5),await e}}var Qo=class extends Xt{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 Ct))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)}},Zo=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 Qo(Pn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Ce(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ja/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ja).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(Ce(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(Ce(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(Ce(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(Ce(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(Ce(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(Ce(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"||!Mp.test(o.stream_id)){this.sendFrame(Np);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Wa){this.sendFrame(Ce(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Wa}). 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??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.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=Tt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Cn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Tn(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!==_t.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Up(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=Tt(),o=Tn(r);try{let s=tn(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:je(e);if(e instanceof Be)return Ce(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof oe)return Ce(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof ee){let a=Ue(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}`),Ce(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}`),Ce(s.status,{type:s.openaiType,message:o},n);let i=Ue(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}`),Ce(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=nt(o),a=i??ze(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)}`),Ce(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=$p;){let{promise:e,resolve:n}=ts();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!==_t.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!==_t.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function vr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
19
19
  `;t.end(`HTTP/1.1 ${e} ${r}\r
20
20
  Connection: close\r
21
21
  Content-Type: text/plain; charset=utf-8\r
22
22
  Content-Length: ${Buffer.byteLength(o)}\r
23
23
  \r
24
- ${o}`)}function Jo(t,e){let n=new yt.WebSocketServer({noServer:!0,maxPayload:up}),r=new xt,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 h;try{h=new URL(d.url??"/","http://localhost")}catch{pr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==Wo){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){pr(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(S){let b=e.statusOf?.(S)??null;pr(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(m=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new Go(S,_,r,e.statusOf,e.operatorLog??(b=>console.error(b)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&pr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Vo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let p=setTimeout(()=>{for(let h of o)h.readyState!==yt.WebSocket.CLOSED&&h.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}E();E();var es=require("@urun-sh/core");E();var $a=require("@urun-sh/core"),mp={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},gp={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 Tn(t,e){let n=gp[t.code];return e?`${n} (${e})`:n}function fr(t){if(t==null)return null;let e=mp[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 mr(t){if(t.kind==="create-failed")return fr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=$a.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return fr(e?"cold_start_exceeded":"queue_timeout")}var ja=require("ws");E();var Ha=require("@urun-sh/core");E();var Ua=require("crypto");function j(t){return`${t}_${(0,Ua.randomUUID)().replace(/-/g,"").slice(0,24)}`}var gr=4*1024*1024,Ko=8*1024*1024,hr=512,yr=20*1024*1024;function pe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Tt(t,e){return{type:"server_error",code:t,message:e}}function se(t){return{type:"error",event_id:j("event"),error:t}}function zo(){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},hp={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},yp={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},wp={format:!0,voice:!0,speed:!0};function _p(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Qt(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 Na(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 vp=10;function Yo(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:vp})}function Pn(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 hp));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=Qt(o.modalities,"modalities"),u=Qt(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=Qt(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(!_p(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=Yo(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,h]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(h!=null&&h!==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(h)}, 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 yp))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Na(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Pn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Pn({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 wp))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Na(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 wr(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 Xo(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:j("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new 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}if(i.type==="input_image"){if(r!=="user")throw new q("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new q("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new q("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new q(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new q(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function _r(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var bp=1001,Sp=1011,Da=t=>t.slice(0,120),kp=/^[A-Za-z0-9+/=]*$/,Rp=2;function Ep(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Rp)return!1;return!0}var Cn=class{id=j("conn");ws;binding;onClosed;operatorLog;config=zo();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;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:j("event"),session:wr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}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 Q&&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(se(Tt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:j("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=j("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.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(pe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>gr){this.fail(pe("frame_too_large",`frame exceeds the ${gr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(pe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(pe("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(se({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Tt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Pn(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(se(pe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:j("event"),session:wr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Xo(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(se(pe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:j("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(se(pe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(se(pe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:j("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(se(pe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!kp.test(e.audio)){this.send(se(pe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>yr){this.send(se(pe("buffer_full",`uncommitted input audio exceeds the ${yr}-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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(se(pe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=j("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(se(pe("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(se(pe("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(se(pe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(se(pe("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(se({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(se(pe("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?Qt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Qt(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(se(pe("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=j("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:_r(this.items),c=Yo(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,m=h==="inf"||h===void 0?void 0:h,_=n.tools!==void 0?n.tools:this.config.tools,S=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}:{},...m!==void 0?{max_output_tokens:m}:{},..._!==void 0?{tools:_}:{},...S!==void 0?{tool_choice:S}:{}};if(!(u&&!this.ensureVoice())){for(let A of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A);this.inFlight=(async()=>{let A=[],f=T=>{this.responseFlushed?this.send(T):A.push(T)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(a,"in_progress")});for(let T of A)this.send(T);A.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},k=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(P=>{this.pendingTranscriptSettled=P}),this.cancelled||this.closed))return;l=this.items.length,d=_r(this.items)}let{input:T,sawAudioOnlyItem:w}=d??{input:[],sawAudioOnlyItem:!1},O={...b,input:T,...u?this.compositeTurnAsk(n):{}};w&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(O,i)}catch(P){this.upstreamTurnFault(P,a);return}try{for await(let P of x){if(this.cancelled)break;let I=P;if(I.type==="error"){let M=this.upstreamErrorBody(I);this.responseFlushed?this.send(se(M)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(a,M)});return}if(I.type==="response.output_text.delta"&&typeof I.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(a,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&f({type:"response.output_text.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,f({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta})),y.messageText+=I.delta;continue}if(I.type==="response.function_call_arguments.delta"){g();let M=typeof I.delta=="string"?I.delta:"",G=typeof I.call_id=="string"&&I.call_id.length>0?I.call_id:`${a}_fc_${y.nextOutputIndex}`,V=y.tools.get(G);if(!V){let Z=typeof I.name=="string"&&I.name.length>0?I.name:void 0;V={outputIndex:y.nextOutputIndex++,name:Z,args:""},y.tools.set(G,V);let Y={id:G,object:"realtime.item",type:"function_call",call_id:G,name:Z??"",arguments:"",status:"in_progress"};f({type:"response.output_item.added",event_id:j("event"),response_id:a,output_index:V.outputIndex,item:Y}),this.emitAssistantItemAdded(Y)}typeof I.name=="string"&&I.name.length>0&&(V.name=I.name),V.args+=M,f({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:G,response_id:a,output_index:V.outputIndex,call_id:G,name:V.name??"",delta:M});continue}if(I.type==="response.completed"){k=I.response??null;continue}}}catch(P){this.upstreamTurnFault(P,a);return}if(this.cancelled)return;this.closeOpenItems(a,y,l),g(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(a,l,k)})}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(Ep(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(se({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let 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:j("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:j("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=tt(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??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ke(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: ${Je(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(Tt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ha.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Tt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(se(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(se(pe("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:j("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>hr&&(this.items.shift(),this.send(se({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${hr} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(se(pe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>kn){this.send(se(pe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${kn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(se(pe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(se(Tt(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Ko){this.ws.close(bp,Da("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Je(e)}`),r.message}fail(e,n){this.send(se(e)),this.ws.close(Sp,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=>Fa(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Fa(this.id,e)}},Qo=[];function Fa(t,e){Qo.push({id:t,reason:e}),Qo.length>256&&Qo.shift()}var Ln="/v1/realtime",xp=t=>t.slice(0,120);function Ap(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
24
+ ${o}`)}function ns(t,e){let n=new _t.WebSocketServer({noServer:!0,maxPayload:Cp}),r=new Pt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{vr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==es){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){vr(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(R){let v=e.statusOf?.(R)??null;vr(c,v?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Zo(R,_,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&vr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ts();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==_t.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}I();I();var ds=require("@urun-sh/core");I();var Va=require("@urun-sh/core"),Dp={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},Fp={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 $n(t,e){let n=Fp[t.code];return e?`${n} (${e})`:n}function br(t){if(t==null)return null;let e=Dp[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 Sr(t){if(t.kind==="create-failed")return br(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Va.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return br(e?"cold_start_exceeded":"queue_timeout")}var Un=require("ws");I();var Qa=require("@urun-sh/core");I();var za=require("crypto");function q(t){return`${t}_${(0,za.randomUUID)().replace(/-/g,"").slice(0,24)}`}var kr=4*1024*1024,rs=8*1024*1024,os=512,Rr=20*1024*1024;function ge(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function vt(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:q("event"),error:t}}function ss(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var V=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Bp={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},Hp={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},jp={format:!0,voice:!0,speed:!0};function qp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function rn(t,e){if(!Array.isArray(t)||t.length===0)throw new V(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new V(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Ka(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new V(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Gp=10;function is(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:Gp})}function Mn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new V("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Bp));if(s.length>0)throw new V(`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=rn(o.modalities,"modalities"),l=rn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new V("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new V(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new V(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(l==="transcription"&&!n.turns)throw new V('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new V(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=rn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new V('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!qp(l))throw new V(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new V("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new V("instructions must be a string or null","instructions");i.instructions=is(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new V("voice must be a string or null","voice");if(!n.voice)throw new V("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new V(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new V("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new V(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new V("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new V("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new V("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new V("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new V(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new V(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new V(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new V("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!l||typeof l!="object"||Array.isArray(l))throw new V("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new V(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new V(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new V("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new V("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new V("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Hp))throw new V(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Ka(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Mn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Mn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new V("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new V("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in jp))throw new V(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Ka(d.format,"audio.output.format"),d.speed!==void 0)throw new V("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 V("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new V("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 Er(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 as(t,e){let n=t;if(!n||typeof n!="object")throw new V("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 V("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:q("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 V('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new V("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 V("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 V(`${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 V("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 V("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new V("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new V("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new V("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new V(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:q("item"),type:"message",role:r,content:o}}throw new V(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function xr(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 Wp=1001,Jp=1011,Vp=15e3;var Ar=class extends Error{},Ir=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ya=t=>t.slice(0,120),Kp=/^[A-Za-z0-9+/=]*$/,zp=2;function Yp(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>zp)return!1;return!0}var Nn=class{id=q("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=ss();sessionId=q("sess");conversationId=q("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;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.turnStallMs=e.turnStallMs??Vp,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:q("event"),session:Er(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:q("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof ee&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(vt("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:q("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:q("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:q("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:q("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:q("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:q("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:q("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:q("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=q("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:q("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:q("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:q("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:q("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(ge("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>kr){this.fail(ge("frame_too_large",`frame exceeds the ${kr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ge("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ge("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(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Ar){this.fail(vt(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
+ ${o?.stack??je(o)}`),this.send(le(vt(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=Mn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(ge("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:q("event"),session:Er(this.config,this.sessionId)});return}case"conversation.item.create":{let n=as(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:q("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(ge("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:q("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(ge("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:q("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(ge("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:q("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(le(ge("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Kp.test(e.audio)){this.send(le(ge("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Rr){this.send(le(ge("buffer_full",`uncommitted input audio exceeds the ${Rr}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;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:q("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(ge("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=q("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:q("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:q("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:q("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:q("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(ge("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(le(ge("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(le(ge("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(ge("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 Ar("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(le({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=!0;try{for(;;){let o;if(r||this.turnStallMs<=0)r=!1,o=await n.next();else{let s,i=new Promise((a,l)=>{s=setTimeout(()=>l(new Ir),this.turnStallMs)});o=await Promise.race([n.next(),i]).finally(()=>clearTimeout(s))}if(o.done===!0)return;yield o.value}}finally{await n.return?.()}}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(le(ge("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?rn(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?rn(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 V("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(le(ge("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=q("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:xr(this.items),c=is(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,m=h==="inf"||h===void 0?void 0:h,_=n.tools!==void 0?n.tools:this.config.tools,R=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...m!==void 0?{max_output_tokens:m}:{},..._!==void 0?{tools:_}:{},...R!==void 0?{tool_choice:R}:{}};if(!(l&&!this.ensureVoice())){for(let{audio:b,captureWallMs:p}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(b,p);this.inFlight=(async()=>{let b=[],p=O=>{this.responseFlushed?this.send(O):b.push(O)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:q("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:q("event"),response:this.responseObject(a,"in_progress")});for(let O of b)this.send(O);b.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},k=null;try{if(l){if(this.pendingTranscriptItemId!==null&&(await new Promise(C=>{this.pendingTranscriptSettled=C}),this.cancelled||this.closed))return;u=this.items.length,d=xr(this.items)}let{input:O,sawAudioOnlyItem:x}=d??{input:[],sawAudioOnlyItem:!1},P={...v,input:O,...l?this.compositeTurnAsk(n):{}};x&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(P,i)}catch(C){this.upstreamTurnFault(C,a);return}try{for await(let C of this.stallBoundedTurn(E)){if(this.cancelled)break;let w=C;if(w.type==="error"){let T=this.upstreamErrorBody(w);this.responseFlushed?this.send(le(T)):this.send({type:"response.failed",event_id:q("event"),response:this.failedResponse(a,T)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(a,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&p({type:"response.output_text.delta",event_id:q("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,p({type:"response.output_audio_transcript.delta",event_id:q("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),y.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){g();let T=typeof w.delta=="string"?w.delta:"",$=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${y.nextOutputIndex}`,M=y.tools.get($);if(!M){let F=typeof w.name=="string"&&w.name.length>0?w.name:void 0;M={outputIndex:y.nextOutputIndex++,name:F,args:""},y.tools.set($,M);let G={id:$,object:"realtime.item",type:"function_call",call_id:$,name:F??"",arguments:"",status:"in_progress"};p({type:"response.output_item.added",event_id:q("event"),response_id:a,output_index:M.outputIndex,item:G}),this.emitAssistantItemAdded(G)}typeof w.name=="string"&&w.name.length>0&&(M.name=w.name),M.args+=T,p({type:"response.function_call_arguments.delta",event_id:q("event"),item_id:$,response_id:a,output_index:M.outputIndex,call_id:$,name:M.name??"",delta:T});continue}if(w.type==="response.completed"){k=w.response??null;continue}}}catch(C){if(C instanceof Ir)this.operatorLog(`[realtime] turn ${a} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(C,a);return}}if(this.cancelled)return;this.closeOpenItems(a,y,u),g(),this.send({type:"response.done",event_id:q("event"),response:this.doneResponse(a,u,k)})}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(Yp(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:q("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:q("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:q("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:q("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:q("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:q("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:q("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:q("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:q("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:q("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:q("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:q("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:q("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:q("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:q("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:q("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=nt(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??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ke(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: ${je(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(vt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof ee){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=vt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:q("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(ge("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:q("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>os&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(ge("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>In){this.send(le(ge("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${In}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(ge("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(vt(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>rs){this.ws.close(Wp,Ya("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${je(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(Jp,Ya(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=>Xa(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Xa(this.id,e)}},ls=[];function Xa(t,e){ls.push({id:t,reason:e}),ls.length>256&&ls.shift()}var Dn="/v1/realtime",Za="urun.admission",el=t=>t.slice(0,120);function Xp(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
26
  Connection: close\r
26
27
  Content-Type: text/plain\r
27
28
  \r
28
- ${xp(n)}\r
29
- `),t.destroy()}function Op(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
30
- `}function Ip(t){Ze(process.stdout,t)}function Tp(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zo(t){return t.audioSession?.audio.sessionId??void 0}function vr(t,e){let n=new ja.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Ln)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=j("rtup"),l=Tp(o),d=y=>{(e.log??Ip)(Op(y))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,h=y=>{p??=y,c.abort(new Error(p))},m=()=>h("client socket closed"),_=()=>h("client socket closed (half-close)"),S=y=>h(`client socket error: ${y.message}`);s.once("close",m),s.once("end",_),s.once("error",S);let b=()=>{s.removeListener("close",m),s.removeListener("end",_),s.removeListener("error",S)},A=y=>{d({stage:"close",conn:u,model:l,...y})},f=y=>{let k=y,T=k.session!=null&&typeof k.session.sendResponseCreate=="function",w=k.clients!=null&&typeof k.clients.createResponse=="function";if(!T&&!w)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((O,x)=>{n.handleUpgrade(o,s,i,P=>{try{new Cn({ws:P,binding:y,operatorLog:e.operatorLog,onClosed:(I,M)=>{A({while:"live",reason:M.reason})}}),d({stage:"admit",conn:u,model:l,...Zo(y)===void 0?{}:{session:Zo(y)}}),O()}catch(I){x(I)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async y=>{if(c.signal.aborted){b();let k=Zo(y);try{await y.release?.()}catch(T){A({while:"queued",...k===void 0?{}:{session:k},reason:p??"client socket closed",release_failed:T instanceof Error?T.message:String(T)});return}A({while:"queued",...k===void 0?{}:{session:k},reason:p??"client socket closed",released:!0}),s.destroy();return}b(),await f(y)}).catch(y=>{let k=y instanceof es.SessionFailedError?mr(y):null,T=null;if(y!==null&&typeof y=="object"&&"status"in y){let P=y.status;typeof P=="number"&&(T=P)}let w=T??k?.status??502,O=y instanceof Error?y.message:String(y),x=T!==null?O:k!==null?Tn(k,y instanceof es.SessionFailedError&&y.status.sessionId?`session ${y.status.sessionId}`:void 0):Ue(y).message;A({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:w}}),s.destroyed||Ap(s,w,x)}).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()))}}E();var Cu=require("crypto");E();var lf=require("http");E();var K=class extends Error{},Be=class extends Error{};function xe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function br(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Zt(t,e){if(t!=null)throw new K(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function ts(t){let e=br(t);return e!==null&&e<=1?e:null}function Ba(t,e){if(!xe(t))throw new K("decisions requires a JSON object body");Zt(t.prompt_cache_key,"prompt_cache_key"),Zt(t.prompt_cache_options,"prompt_cache_options"),Zt(t.safety_identifier,"safety_identifier");let n=[],r=Pp(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new K("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=$p(o[l],l,o.length,n);if(a.has(c.key))throw new K(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let u={model:e,state:r,questions:s};return n.length>0&&(u.media=n),{systemone:u,specs:i}}function Pp(t,e){if(typeof t=="string")return t;if(!xe(t)&&!Array.isArray(t))throw new K("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)Lp(o,r,e);return Cp(r)}function Cp(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
29
+ ${el(n)}\r
30
+ `),t.destroy()}function Qp(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
31
+ `}function Zp(t){et(process.stdout,t)}function ef(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function us(t){return t.audioSession?.audio.sessionId??void 0}function Or(t,e){let n=new Un.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Dn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=q("rtup"),u=ef(o),d=E=>{(e.log??Zp)(Qp(E))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,f=null,h=E=>{f??=E,c.abort(new Error(f))},m=()=>h("client socket closed"),_=()=>h("client socket closed (half-close)"),R=E=>h(`client socket error: ${E.message}`);s.once("close",m),s.once("end",_),s.once("error",R);let v=()=>{s.removeListener("close",m),s.removeListener("end",_),s.removeListener("error",R)},b=E=>{d({stage:"close",conn:l,model:u,...E})},p=null,g=!1,y=null,k=E=>JSON.stringify({type:Za,event_id:q("event"),...E}),O=E=>{if(p!==null){p.readyState===Un.WebSocket.OPEN&&p.send(k(E));return}g||(g=!0,n.handleUpgrade(o,s,i,C=>{p=C,y=[],C.on("message",w=>{y?.push(String(w))}),d({stage:"waiting",conn:l,model:u,status:E.status}),C.send(k(E))}))},x=E=>{let C=E,w=C.session!=null&&typeof C.session.sendResponseCreate=="function",T=C.clients!=null&&typeof C.clients.createResponse=="function";if(!w&&!T)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(($,M)=>{let F=(G,se)=>{try{let X=Date.now();new Nn({ws:G,binding:E,operatorLog:e.operatorLog,...se.length>0?{replayFrames:se}:{},onClosed:(ae,z)=>{b({while:"live",reason:z.reason});try{e.onSessionEnded?.({req:o,binding:E,connected_ms:Math.max(0,Date.now()-X),reason:z.reason})}catch(N){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${N instanceof Error?N.message:String(N)}
32
+ `)}}}),d({stage:"admit",conn:l,model:u,...us(E)===void 0?{}:{session:us(E)}}),$()}catch(X){M(X)}};if(p!==null){let G=y??[];y=null,F(p,G);return}n.handleUpgrade(o,s,i,G=>F(G,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,O).then(async E=>{if(c.signal.aborted){v();let C=us(E);try{await E.release?.()}catch(w){b({while:"queued",...C===void 0?{}:{session:C},reason:f??"client socket closed",release_failed:w instanceof Error?w.message:String(w)});return}b({while:"queued",...C===void 0?{}:{session:C},reason:f??"client socket closed",released:!0}),s.destroy();return}v(),await x(E)}).catch(E=>{let C=E instanceof ds.SessionFailedError?Sr(E):null,w=null;if(E!==null&&typeof E=="object"&&"status"in E){let F=E.status;typeof F=="number"&&(w=F)}let T=w??C?.status??502,$=E instanceof Error?E.message:String(E),M=w!==null?$:C!==null?$n(C,E instanceof ds.SessionFailedError&&E.status.sessionId?`session ${E.status.sessionId}`:void 0):Ue(E).message;if(b({while:"queued",...c.signal.aborted?{reason:f??"client socket closed"}:{reason:$,status:T}}),p!==null&&!c.signal.aborted){let F=JSON.stringify({type:Za,event_id:q("event"),status:T<500?"rejected":"failed",reason:M});p.readyState===Un.WebSocket.OPEN&&p.send(F),p.close(1011,el(M));return}s.destroyed||Xp(s,T,M)}).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()))}}I();var Ye=require("crypto"),sl=require("dns/promises");I();var tl="/realtime/openai.quic-relay";async function nl(t){let e=await fetch(`${t.sfuBase}${tl}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let s=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${tl} -> ${e.status} ${s}`)}let n=await e.json(),r=new URL(t.sfuBase).host,o=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:o,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var cs="/v1/realtime/calls",rl="/v1/realtime/client_secrets",tf="session-server-ts-pods.urun.svc.cluster.local",ol=8081,nf="/realtime/openai.relay",rf=262144,of=600;function il(t){let e=t.secret===void 0?void 0:Buffer.from((0,Ye.hkdfSync)("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>df(await(0,sl.resolve4)(tf))),r=(o,s,i,a)=>{o.writeHead(s,{"content-type":"application/json"}),o.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(o,s)=>{let i=new URL(o.url??"/","http://proxy");if(o.method!=="POST"||i.pathname!==cs&&i.pathname!==rl)return!1;let a=await af(o);if(a===null)return r(s,413,"request body too large"),!0;let l=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");if(l.startsWith("ek_")){let v=e===void 0?null:uf(e,l.slice(3));if(v===null)return r(s,401,"invalid or expired client secret","invalid_api_key"),!0;o.headers.authorization=`Bearer ${v}`}try{await t.authorize(o)}catch(v){let b=typeof v=="object"&&v!==null&&"status"in v&&typeof v.status=="number"?v.status:401;return r(s,b,v instanceof Error?v.message:String(v)),!0}if(i.pathname===rl){if(e===void 0)return r(s,501,"client secrets are not configured on this proxy"),!0;let v=a.length===0?{}:JSON.parse(a.toString("utf8")),b=typeof v=="object"&&v!==null&&"session"in v?v.session:null,p=Math.floor(Date.now()/1e3)+of,g=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");return s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({value:`ek_${lf(e,g,p)}`,expires_at:p,session:b})),!0}if(i.searchParams.get("transport")==="quic"){let v=i.searchParams.get("model");if(v===null)return r(s,400,"model is required (?model=)"),!0;let b=`quic_${(0,Ye.randomUUID)().replaceAll("-","")}`,p=new URLSearchParams(i.searchParams);p.set("model",v),p.set("call_id",b);let g="no media edge resolved";for(let y of await n())try{let k=await nl({sfuBase:`http://${y}:${ol}`,query:`?${p}`,upstreamHeaders:{authorization:o.headers.authorization??""}});return s.writeHead(201,{"content-type":"application/json",location:`${cs}/${k.body.callId}`}),s.end(JSON.stringify(k.body)),!0}catch(k){g=`${y}: ${String(k)}`}return r(s,502,`no media edge accepted the quic call (${g})`),!0}let{sdp:u,session:d}=await sf(o.headers["content-type"]??"",a);if(u===void 0)return r(s,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)"),!0;let c=typeof d=="object"&&d!==null&&"model"in d&&typeof d.model=="string"?d.model:void 0,f=i.searchParams.get("model")??c;if(f===void 0)return r(s,400,"model is required (?model= or session.model)"),!0;let h=`rtc_${(0,Ye.randomUUID)().replaceAll("-","")}`,m=new URLSearchParams(i.searchParams);m.set("model",f),m.set("call_id",h);let _=JSON.stringify({sdp:u,...d!==void 0?{session:d}:{}}),R="no media edge resolved";for(let v of await n()){let b;try{b=await fetch(`http://${v}:${ol}${nf}?${m}`,{method:"POST",headers:{"content-type":"application/json",authorization:o.headers.authorization??""},body:_,signal:AbortSignal.timeout(1e4)})}catch(g){R=`${v}: ${String(g)}`;continue}let p=await b.text();if(b.status===201)return s.writeHead(201,{"content-type":"application/sdp",location:`${cs}/${h}`}),s.end(p),!0;if(b.status>=500||b.status===404||b.status===405||b.status===501){R=`${v}: ${b.status} ${p}`;continue}return r(s,b.status,p),!0}return r(s,503,`no media edge answered the offer (${R})`,"media_edge_unavailable"),!0}}async function sf(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),o=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof o=="string"?{session:JSON.parse(o)}:{}}}async function af(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>rf)return null;e.push(r)}return Buffer.concat(e)}function lf(t,e,n){let r=(0,Ye.randomBytes)(12),o=(0,Ye.createCipheriv)("aes-256-gcm",t,r),s=Buffer.concat([o.update(JSON.stringify({b:e,e:n}),"utf8"),o.final()]);return Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}function uf(t,e){try{let n=Buffer.from(e,"base64url"),r=(0,Ye.createDecipheriv)("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let o=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof o!="object"||o===null||!("b"in o)||!("e"in o))return null;let{b:s,e:i}=o;return typeof s!="string"||typeof i!="number"?null:i>Date.now()/1e3?s:null}catch{return null}}function df(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}I();var Xl=require("crypto");I();var jf=require("http");I();var Y=class extends Error{},qe=class extends Error{};function Ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Tr(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function on(t,e){if(t!=null)throw new Y(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function ps(t){let e=Tr(t);return e!==null&&e<=1?e:null}function al(t,e){if(!Ae(t))throw new Y("decisions requires a JSON object body");on(t.prompt_cache_key,"prompt_cache_key"),on(t.prompt_cache_options,"prompt_cache_options"),on(t.safety_identifier,"safety_identifier");let n=[],r=cf(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new Y("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=gf(o[u],u,o.length,n);if(a.has(c.key))throw new Y(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function cf(t,e){if(typeof t=="string")return t;if(!Ae(t)&&!Array.isArray(t))throw new Y("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ff(o,r,e);return pf(r)}function pf(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
31
33
 
32
- `)}function Lp(t,e,n){if(!xe(t))throw new K("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Mp(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){qa(s,e,n,void 0,!1);return}throw new K(`${o} output must be a string or an array of parts`)}default:throw new K(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Mp(t,e,n,r){e==="assistant"&&Zt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new K(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!xe(s))throw new K("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new K(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}qa(o,n,r,e)}function qa(t,e,n,r,o=!0){for(let s of t){if(!xe(s))throw new K("decisions content parts must be JSON objects");switch(Zt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new K("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new K("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!xe(i)&&!(Array.isArray(i)&&i.every(xe)))throw new K("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ga(s));break}default:throw new K(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ga(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new K("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new K("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new K("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new K("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new K("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function $p(t,e,n,r){if(!xe(t))throw new K(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new K(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new K(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,u=Np(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new K(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let _ of l){if(!xe(_))throw new K(`questions[${e}] choices must be JSON objects`);let S=_.value;if(typeof S!="string"&&typeof S!="boolean")throw new K(`questions[${e}] choice value must be a string or boolean`);let b=String(S);if(c.has(b))throw new K(`questions[${e}] has duplicate choice value ${JSON.stringify(b)} (choices must be unique)`);c.add(b);let A=_.description;if(A!==void 0&&typeof A!="string")throw new K(`questions[${e}] choice description must be a string`);d.push(S),p.push(A)}let h=l.map((_,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:u,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new K(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of l){if(!xe(h)||typeof h.label!="string")throw new K(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new K(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new K(`questions[${e}] score level description must be a string`);let _=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(_))throw new K(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d}}}}}function Np(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new K(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!xe(s))throw new K(`questions[${e}] instruction parts must be JSON objects`);switch(Zt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new K(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new K(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Ga(s));break}case"input_json":{let i=s.data;if(!xe(i)&&!(Array.isArray(i)&&i.every(xe)))throw new K(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new K(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
34
+ `)}function ff(t,e,n){if(!Ae(t))throw new Y("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){mf(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){ll(s,e,n,void 0,!1);return}throw new Y(`${o} output must be a string or an array of parts`)}default:throw new Y(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function mf(t,e,n,r){e==="assistant"&&on(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new Y(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!Ae(s))throw new Y("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new Y(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}ll(o,n,r,e)}function ll(t,e,n,r,o=!0){for(let s of t){if(!Ae(s))throw new Y("decisions content parts must be JSON objects");switch(on(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new Y("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new Y("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!Ae(i)&&!(Array.isArray(i)&&i.every(Ae)))throw new Y("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(ul(s));break}default:throw new Y(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function ul(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new Y("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new Y("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new Y("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new Y("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new Y("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function gf(t,e,n,r){if(!Ae(t))throw new Y(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new Y(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new Y(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=hf(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new Y(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,f=[];for(let _ of u){if(!Ae(_))throw new Y(`questions[${e}] choices must be JSON objects`);let R=_.value;if(typeof R!="string"&&typeof R!="boolean")throw new Y(`questions[${e}] choice value must be a string or boolean`);let v=String(R);if(c.has(v))throw new Y(`questions[${e}] has duplicate choice value ${JSON.stringify(v)} (choices must be unique)`);c.add(v);let b=_.description;if(b!==void 0&&typeof b!="string")throw new Y(`questions[${e}] choice description must be a string`);d.push(R),f.push(b)}let h=u.map((_,R)=>({name:String(d[R]),description:f[R]??String(d[R])}));return{entry:{kind:"choice",prompt:l,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new Y(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of u){if(!Ae(h)||typeof h.label!="string")throw new Y(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new Y(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new Y(`questions[${e}] score level description must be a string`);let _=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(_))throw new Y(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d}}}}}function hf(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new Y(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!Ae(s))throw new Y(`questions[${e}] instruction parts must be JSON objects`);switch(on(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new Y(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new Y(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(ul(s));break}case"input_json":{let i=s.data;if(!Ae(i)&&!(Array.isArray(i)&&i.every(Ae)))throw new Y(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new Y(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
33
35
 
34
- `)}function Wa(t,e){if(!xe(e))throw new Be("decision answer was not a JSON object");let n=e.answers;if(!xe(n))throw new Be("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!xe(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=xe(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=ts(s.noul);if(a===null)throw new Be(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],u=s.choice;if(typeof u!="string")throw new Be(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new Be(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=br(s.confidence);if(d===null)throw new Be(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let h=ts(i[String(p)]);h!==null&&c.push({value:p,probability:h})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=br(s.score);if(u===null)throw new Be(`the score answer for "${o.key}" carries no numeric score to translate`);let l=br(s.confidence);if(l===null)throw new Be(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=ts(i[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}r.push({type:"score",name:o.name,score:u,confidence:l,probabilities:d});continue}}}return r}E();E();var Ae=class extends Error{};async function Sr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Ae(`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 Ae(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function kr(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 Ae(`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 Ae?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Va="/v1/images/generations",Rr="/v1/images/edits";function Ja(t){return t===Va||t===Rr}var Ka="/v1/images/models";async function za(t,e,n){if(t){if(t.model=Pe({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 te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Up=16*1024*1024,Ya=64*1024*1024;function Xa(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 Mn(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 Qa(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let m of a){if(m.type==="error"){let _=m.error??{},S=typeof _.message=="string"&&_.message.length>0&&Ke(_.message)?_.message:null;throw S===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new te(502,"the image upstream failed while serving this request")):new te(502,`image upstream error: ${S}`)}if(m.type==="response.completed"){u=m.response??null;break}}if(u===null)throw new te(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=ut(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new te(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(Xa(p)===null)throw new te(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 Za(t,e){if(t instanceof te)return t;if(t instanceof je)throw t;return t instanceof ne?new te(404,t.message):new te(502,Xt("image",t,e))}async function eu(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 Mn(r,new te(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 tu(t,e){t&&(t.outputUnits=e.images.length)}function nu(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 Dp={model:!0,prompt:!0,response_format:!0,n:!0};async function ru(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ya;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${Va}`);let s;try{s=JSON.parse((await Sr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Ae?new te(413,p.message):new te(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new te(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Dp[p])throw new te(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 te(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 te(400,"model must be a string","model");await za(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new te(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 te(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 eu(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Qa(n.clients,u,c,n.turn?Fe(n.turn):void 0,n.turn,r);tu(n.turn,p),nu(e,p)}catch(p){throw Za(p,r)}}catch(s){if(s instanceof Ae){Mn(e,new te(413,s.message));return}if(s instanceof te){Mn(e,s);return}throw s}}var Fp={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ou(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ya,s=n.maxImagePartBytes??Up;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${Rr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new te(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await kr(t,o)}catch(m){throw m instanceof Ae?new te(413,m.message):new te(400,String(m instanceof Error?m.message:m))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new te(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 te(400,"model must be a string field","model");let d=l===null?void 0:l;await za(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new te(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 m of a.keys())if(!Fp[m])throw new te(400,`form field "${m}" 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[]).`,m);let p=[];for(let m of["image","image[]"])for(let _ of a.getAll(m)){if(!(_ instanceof File))throw new te(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(_.size>s)throw new te(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let S=new Uint8Array(await _.arrayBuffer()),b=Xa(S);if(b===null)throw new te(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:S,mime:b})}if(p.length===0)throw new te(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await eu(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:m,mime:_}of p)h.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Qa(n.clients,d,h,n.turn?Fe(n.turn):void 0,n.turn,r);tu(n.turn,m),nu(e,m)}catch(m){throw Za(m,r)}}catch(i){if(i instanceof Ae){Mn(e,new te(413,i.message));return}if(i instanceof te){Mn(e,i);return}throw i}}E();var $n="/v1/audio/speech";function fu(t){return t===$n}var su=4096,iu=18e4,au=5e3,Hp=64*1024*1024,uu=8,lu=5,du=1024*1024,en="voice_applied",xr="X-Urun-Voice-Applied",z=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function ns(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 Ar=class extends z{constructor(e){super(502,e)}};function mu(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 gu(t){return new z(502,`the runtime's ${en} receipt ${JSON.stringify(t)} cannot be relayed as the ${xr} 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 jp(t,e,n){if(t){if(t.model=Pe({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 hu(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Bp=2;function qp(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Bp)return!1;return!0}function Gp(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 cu=new WeakMap,Er=new WeakMap;function Wp(t,e){let n=Er.get(t)??0;if(n>=uu)throw new z(503,`this model's speech queue is full \u2014 ${uu} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${lu}s`,void 0,lu);Er.set(t,n+1);let r=cu.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return cu.set(t,s),(async()=>{await r;try{return await e()}finally{Er.set(t,(Er.get(t)??1)-1),o()}})()}async function Vp(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new z(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 Q))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 Pt(t,e){if(t instanceof z)return t;if(t instanceof je)throw t;return t instanceof ne?new z(404,t.message):new z(502,Xt("speech",t,e))}async function pu(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Wp(e,async()=>{if(i?.()===!0)return null;let p=!1,h=!1,m=!1,_,S=new Promise(w=>{_=w}),b=[],A=()=>{h&&!m&&b.length>=o.quietRunFrames&&(m=!0,_())},f=e.onOutputAudio(w=>{let O=Buffer.from(w,"base64");if(O.byteLength===0)return;let x=qp(O);if(!p){if(x)return;p=!0}if(x){b.push(O),A();return}for(let P of b)c(P);b.length=0,c(O),A()}),g=null,y,k,T;try{T=(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(I=>{k=setTimeout(I,s.capMs)}),x=!1;for(;;){let I=T.next(),M=await Promise.race([I,O]);if(M===void 0){x=!0,I.catch(()=>{});break}if(M.done)break;let G=M.value;if(G.type==="error"){let V=G.error??{};await T.return?.();let Z=typeof V.message=="string"&&V.message.length>0&&Ke(V.message)?V.message:null;throw Z===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(G)}`),new z(502,"the speech upstream failed while serving this request")):new z(502,`speech upstream error: ${Z}`)}if(G.type==="response.completed"){g=G.response??null,h=!0,u?.(g),A(),await T.return?.();break}}if(clearTimeout(k),x)throw new z(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(g===null)throw new z(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([S,new Promise(I=>{y=setTimeout(()=>{P=!0,I()},o.capMs)})]),y!==void 0&&clearTimeout(y),r.voice!==void 0){let I=g[en];if(typeof I!="string"||I!==r.voice){let M=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${en} ${JSON.stringify(I)}`:`no ${en} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new Ar(M):new z(502,M)}}if(!p)throw new z(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!m&&b.length<1)throw new z(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 g}catch(w){throw w instanceof Ar||await Vp(t,n,T,s.returnBoundMs),w}finally{y!==void 0&&clearTimeout(y),k!==void 0&&clearTimeout(k),f()}})}function Jp(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",xr)),t.write(a,u=>{u||(s+=a.byteLength,hu(e,s))}),t.writableLength>du&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${du} 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[en];if(typeof u=="string"){if(!mu(u))throw gu(u);t.addTrailers({[xr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Kp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Pt(s,r)}return o?!0:(ns(n,new z(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 zp={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Yp="wav, pcm";async function yu(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Hp,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new z(405,`${String(t.method)} is not supported on ${$n}`);let a;try{a=JSON.parse((await Sr(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof Ae?new z(413,g.message):new z(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new z(400,"request body must be a JSON object");let u=a;for(let g of Object.keys(u))if(!zp[g])throw new z(400,`request field "${g}" 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.`,g);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new z(400,"input is required and must be a non-empty string","input");if(l.length>su)throw new z(400,`input is ${l.length} chars \u2014 over the ${su}-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 z(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new z(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new z(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 ${$n} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(g){throw Pt(g,r)}if(p.defect!==null)throw new z(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 h=typeof c=="string"?c:void 0;if(h!==void 0&&p.published.length>0&&!p.published.includes(h))throw new z(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=u.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new z(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Yp} \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 z(400,"stream_format, when present, must be a string","stream_format");let _=u.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new z(400,"speed, when present, must be a number","speed");if(_!==1)throw new z(400,`speed=${JSON.stringify(_)} 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 S=u.instructions;if(S!==void 0){if(typeof S!="string")throw new z(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new z(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 jp(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",b,b),!await Kp(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new z(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 z(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 z(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 A;try{A=await n.clients.speechSessionHandle(d)}catch(g){throw Pt(g,r)}let f;try{f=await n.clients.openAudioOn(A)}catch(g){throw Pt(g,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(m==="wav"){let g=[],y=await pu(n.clients,f,A,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??iu,returnBoundMs:n.turnReturnBoundMs??au},i,T=>g.push(T),T=>{n.turn&&(n.turn.outputSeconds=ut(T))},r);if(y===null||i())return;let k=Buffer.concat(g);if(h===void 0){let T=y[en];if(typeof T=="string"){if(!mu(T))throw gu(T);e.setHeader(xr,T)}}hu(n.turn,k.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Gp(k.byteLength),k]))}else{let g=Jp(e,n.turn,i,h===void 0),y;try{y=await pu(n.clients,f,A,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??iu,returnBoundMs:n.turnReturnBoundMs??au},i,g.sink,k=>{n.turn&&(n.turn.outputSeconds=ut(k))},r)}catch(k){let T=Pt(k,r);if(!g.started())throw T;n.turn&&(n.turn.streamError=!0),g.fail(T);return}if(y===null)return;try{await g.finish(y)}catch(k){let T=Pt(k,r);n.turn&&(n.turn.streamError=!0),g.fail(T);return}}}catch(g){throw Pt(g,r)}}catch(a){if(a instanceof Ae){ns(e,new z(413,a.message));return}if(a instanceof z){ns(e,a);return}throw a}}E();var Or="/v1/audio/transcriptions";function wu(t){return t===Or}var _u="/v1/audio/models",Xp=16*1024*1024,Qp=64*1024*1024,fe=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function rs(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 vu(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 Zp(t){if(!vu(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 ef(t,e,n){if(t){if(t.model=Pe({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 tf(t,e){t&&(t.outputUnits=e.seconds)}async function nf(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??{},h=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&Ke(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new fe(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new fe(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new fe(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=ut(d)),zt(l,d)}function bu(t,e){if(t instanceof fe)return t;if(t instanceof je)throw t;return t instanceof ne?new fe(404,t.message):new fe(502,Xt("transcription",t,e))}async function rf(t,e,n,r){let o;try{o=await t(e)}catch(s){throw bu(s,r)}return o?!0:(rs(n,new fe(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 of=new Set(["file","model","language","response_format"]);async function Su(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Qp,s=n.maxAudioPartBytes??Xp;try{if(t.method!=="POST")throw new fe(405,`${String(t.method)} is not supported on ${Or}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new fe(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await kr(t,o)}catch(A){throw A instanceof Ae?new fe(413,A.message):new fe(400,String(A instanceof Error?A.message:A))}let u=new Map;for(let A of a.keys()){if(!of.has(A))throw new fe(400,`form field "${A}" 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.`,A);u.set(A,(u.get(A)??0)+1)}for(let[A,f]of u)if(f>1)throw new fe(400,`form field "${A}" appears ${f} 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`,A);let l=a.get("model");if(l!==null&&typeof l!="string")throw new fe(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 fe(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new fe(400,`response_format ${JSON.stringify(h)} 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 m=a.get("file");if(!(m instanceof File))throw new fe(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new fe(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await m.arrayBuffer());if(!vu(_))throw new fe(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 S=Zp(_);if(S===null)throw new fe(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 ef(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await rf(n.transcriptionModels,d,e,r))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let A=await nf(n.clients,d,b,p,n.turn?Fe(n.turn):void 0,n.turn,r);tf(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:A}))}catch(A){throw bu(A,r)}}catch(i){if(i instanceof Ae){rs(e,new fe(413,i.message));return}if(i instanceof fe){rs(e,i);return}throw i}}var Cr=require("@urun-sh/core");E();var ss="x-urun-profile",Nn="voice";var $e=class extends Error{status=400},sf=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,af=/\s/;function uf(t){return sf.test(t)}function os(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new $e(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ku(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 $e(`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 $e(`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 $e(`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 Ru(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 $e(`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 $e(`the ${ss} header is empty \u2014 the only profile this lane accepts is "${Nn}" (omit the header for the ordinary lane)`);if(l!==Nn)throw new $e(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Nn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Nn)throw new $e(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Nn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new $e("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 $e("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:ku(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:ku(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:os(u,"sentence_flush",!0),includeReasoning:os(u,"include_reasoning",!1),metadata:os(u,"metadata",!1)}}var tn=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&&uf(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(af.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 us(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function df(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 Oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ue(t,e,n,r="invalid_request_error",o){Oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function ls(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=tt(r),a=i??ze(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"),Oe(t,l,{error:{message:a,type:o,code:u}})}function Ye(t,e,n,r){Oe(t,e,{type:"error",error:{type:n,message:r}})}function nn(t,e,n){if(e==="anthropic"){Oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var cf=64*1024*1024,Un=class extends Error{};async function Eu(t,e=cf){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Un(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ct(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Au(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 Ir(t){let e=Au(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function xu(t){let e=Ir(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:pf(t)},completion_tokens_details:{reasoning_tokens:0}}}function pf(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function ff(t,e){let n=Au(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function mf(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 gf(t,e){let n=mf(e);n&&(t.timing=n),t.outputSeconds=ut(e)}function Lt(t,e){ff(t,e),gf(t,e)}async function Lr(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 Ou(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 hf(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 Tr=class extends Error{};function yf(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 Tr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function wf(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:yf(n.role,n.content)})}return e}function is(t){return Jt(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 _f(t,e,n,r,o,s,i){let a=xn(s.id),u=t.stream===!0;if(s.model=Pe(t),s.stream=u,await Lr(s,e,typeof t.model=="string"?t.model:void 0),u){let A;try{A=await On({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(f){if(f instanceof ne){nn(r,"openai",f);return}if(f instanceof He){ue(r,f.status,f.message);return}if(f instanceof We||f instanceof Ee){r.setHeader("retry-after","2"),ue(r,503,f.message,"capacity_error");return}throw f}us(r);for await(let f of A.events){if(f.type==="error"){s.streamError=!0;let g=f.error,y=tt(g),k=y??ze(s.id);y===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(f)}`),r.write(`event: error
36
+ `)}function dl(t,e){if(!Ae(e))throw new qe("decision answer was not a JSON object");let n=e.answers;if(!Ae(n))throw new qe("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!Ae(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=Ae(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=ps(s.noul);if(a===null)throw new qe(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new qe(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(f=>String(f)===l);if(u===-1)throw new qe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=Tr(s.confidence);if(d===null)throw new qe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let f of a){let h=ps(i[String(f)]);h!==null&&c.push({value:f,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=Tr(s.score);if(l===null)throw new qe(`the score answer for "${o.key}" carries no numeric score to translate`);let u=Tr(s.confidence);if(u===null)throw new qe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let f=ps(i[String(c)]);f!==null&&d.push({value:c,label:a[c],probability:f})}r.push({type:"score",name:o.name,score:l,confidence:u,probabilities:d});continue}}}return r}I();I();var Ie=class extends Error{};async function Pr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Ie(`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 Ie(`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 Ie(`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[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,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 Ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var cl="/v1/images/generations",Lr="/v1/images/edits";function pl(t){return t===cl||t===Lr}var fl="/v1/images/models";async function ml(t,e,n){if(t){if(t.model=Pe({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 re=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},yf=16*1024*1024,gl=64*1024*1024;function hl(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 Fn(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 yl(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let _=m.error??{},R=typeof _.message=="string"&&_.message.length>0&&Ke(_.message)?_.message:null;throw R===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new re(502,"the image upstream failed while serving this request")):new re(502,`image upstream error: ${R}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new re(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=ut(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new re(502,`image upstream returned ${Array.isArray(u)?u.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=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],f=Buffer.from(c,"base64");if(hl(f)===null)throw new re(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function wl(t,e){if(t instanceof re)return t;if(t instanceof He)throw t;return t instanceof oe?new re(404,t.message):new re(502,nn("image",t,e))}async function _l(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 Fn(r,new re(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 vl(t,e){t&&(t.outputUnits=e.images.length)}function bl(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 wf={model:!0,prompt:!0,response_format:!0,n:!0};async function Sl(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??gl;try{if(t.method!=="POST")throw new re(405,`${String(t.method)} is not supported on ${cl}`);let s;try{s=JSON.parse((await Pr(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof Ie?new re(413,f.message):new re(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new re(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!wf[f])throw new re(400,`request field "${f}" 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.`,f);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new re(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new re(400,"model must be a string","model");await ml(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new re(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new re(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 _l(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let f=await yl(n.clients,l,c,n.turn?Fe(n.turn):void 0,n.turn,r);vl(n.turn,f),bl(e,f)}catch(f){throw wl(f,r)}}catch(s){if(s instanceof Ie){Fn(e,new re(413,s.message));return}if(s instanceof re){Fn(e,s);return}throw s}}var _f={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function kl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??gl,s=n.maxImagePartBytes??yf;try{if(t.method!=="POST")throw new re(405,`${String(t.method)} is not supported on ${Lr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new re(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Cr(t,o)}catch(m){throw m instanceof Ie?new re(413,m.message):new re(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new re(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new re(400,"model must be a string field","model");let d=u===null?void 0:u;await ml(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new re(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 m of a.keys())if(!_f[m])throw new re(400,`form field "${m}" 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[]).`,m);let f=[];for(let m of["image","image[]"])for(let _ of a.getAll(m)){if(!(_ instanceof File))throw new re(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(_.size>s)throw new re(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let R=new Uint8Array(await _.arrayBuffer()),v=hl(R);if(v===null)throw new re(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);f.push({bytes:R,mime:v})}if(f.length===0)throw new re(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await _l(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:_}of f)h.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await yl(n.clients,d,h,n.turn?Fe(n.turn):void 0,n.turn,r);vl(n.turn,m),bl(e,m)}catch(m){throw wl(m,r)}}catch(i){if(i instanceof Ie){Fn(e,new re(413,i.message));return}if(i instanceof re){Fn(e,i);return}throw i}}I();var Bn="/v1/audio/speech";function Cl(t){return t===Bn}var Rl=4096,El=18e4,xl=5e3,vf=64*1024*1024,Al=8,Il=5,Ol=1024*1024,sn="voice_applied",Mr="X-Urun-Voice-Applied",Q=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function fs(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 Nr=class extends Q{constructor(e){super(502,e)}};function Ll(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 $l(t){return new Q(502,`the runtime's ${sn} 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 bf(t,e,n){if(t){if(t.model=Pe({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 Ml(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Sf=2;function kf(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Sf)return!1;return!0}function Rf(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 Tl=new WeakMap,$r=new WeakMap;function Ef(t,e){let n=$r.get(t)??0;if(n>=Al)throw new Q(503,`this model's speech queue is full \u2014 ${Al} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Il}s`,void 0,Il);$r.set(t,n+1);let r=Tl.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Tl.set(t,s),(async()=>{await r;try{return await e()}finally{$r.set(t,($r.get(t)??1)-1),o()}})()}async function xf(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new Q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof ee))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(()=>{clearTimeout(s)})}function Nt(t,e){if(t instanceof Q)return t;if(t instanceof He)throw t;return t instanceof oe?new Q(404,t.message):new Q(502,nn("speech",t,e))}async function Pl(t,e,n,r,o,s,i,a,l,u){let d=u??(f=>console.error(f)),c=a??(()=>{});return Ef(e,async()=>{if(i?.()===!0)return null;let f=!1,h=!1,m=!1,_,R=new Promise(C=>{_=C}),v=[],b,p=!1,g=null,y=()=>{g!==null&&(clearTimeout(b),b=setTimeout(()=>{p=!0,g?.()},o.capMs))},k=()=>{h&&!m&&v.length>=o.quietRunFrames&&(m=!0,_())},O=e.onOutputAudio(C=>{let w=Buffer.from(C,"base64");if(w.byteLength===0)return;y();let T=kf(w);if(!f){if(T)return;f=!0}if(T){v.push(w),k();return}for(let $ of v)c($);v.length=0,c(w),k()}),x=null,P,E;try{E=(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 w=()=>(clearTimeout(P),new Promise(F=>{P=setTimeout(F,s.capMs)})),T=w(),$=!1;for(;;){let F=E.next(),G=await Promise.race([F,T]);if(G===void 0){$=!0,F.catch(()=>{});break}if(G.done)break;let se=G.value;if(T=w(),se.type==="error"){let X=se.error??{};await E.return?.();let ae=typeof X.message=="string"&&X.message.length>0&&Ke(X.message)?X.message:null;throw ae===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(se)}`),new Q(502,"the speech upstream failed while serving this request")):new Q(502,`speech upstream error: ${ae}`)}if(se.type==="response.completed"){x=se.response??null,h=!0,l?.(x),k(),await E.return?.();break}}if(clearTimeout(P),$)throw new Q(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(x===null)throw new Q(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let M=new Promise(F=>{g=F});if(y(),await Promise.race([R,M]),clearTimeout(b),b=void 0,g=null,r.voice!==void 0){let F=x[sn];if(typeof F!="string"||F!==r.voice){let G=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof F=="string"?`${sn} ${JSON.stringify(F)}`:`no ${sn} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new Nr(G):new Q(502,G)}}if(!f)throw new Q(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(p&&!m&&v.length<1)throw new Q(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return x}catch(C){throw C instanceof Nr||await xf(t,n,E,s.returnBoundMs),C}finally{clearTimeout(b),clearTimeout(P),O()}})}function Af(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,l=>{l||(s+=a.byteLength,Ml(e,s))}),t.writableLength>Ol&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ol} 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 l=a[sn];if(typeof l=="string"){if(!Ll(l))throw $l(l);t.addTrailers({[Mr]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function If(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Nt(s,r)}return o?!0:(fs(n,new Q(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Of={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Tf="wav, pcm";async function Nl(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??vf,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${Bn}`);let a;try{a=JSON.parse((await Pr(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof Ie?new Q(413,g.message):new Q(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new Q(400,"request body must be a JSON object");let l=a;for(let g of Object.keys(l))if(!Of[g])throw new Q(400,`request field "${g}" 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.`,g);let u=l.input;if(typeof u!="string"||u.trim().length===0)throw new Q(400,"input is required and must be a non-empty string","input");if(u.length>Rl)throw new Q(400,`input is ${u.length} chars \u2014 over the ${Rl}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new Q(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new Q(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new Q(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Bn} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(g){throw Nt(g,r)}if(f.defect!==null)throw new Q(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&f.published.length>0&&!f.published.includes(h))throw new Q(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new Q(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Tf} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new Q(400,"stream_format, when present, must be a string","stream_format");let _=l.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new Q(400,"speed, when present, must be a number","speed");if(_!==1)throw new Q(400,`speed=${JSON.stringify(_)} 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 R=l.instructions;if(R!==void 0){if(typeof R!="string")throw new Q(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new Q(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await bf(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",v,v),!await If(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new Q(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new Q(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new Q(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let b;try{b=await n.clients.speechSessionHandle(d)}catch(g){throw Nt(g,r)}let p;try{p=await n.clients.openAudioOn(b)}catch(g){throw Nt(g,r)}n.turn&&(n.turn.sessionId=p.sessionId);try{if(m==="wav"){let g=[],y=await Pl(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??El,returnBoundMs:n.turnReturnBoundMs??xl},i,O=>g.push(O),O=>{n.turn&&(n.turn.outputSeconds=ut(O))},r);if(y===null||i())return;let k=Buffer.concat(g);if(h===void 0){let O=y[sn];if(typeof O=="string"){if(!Ll(O))throw $l(O);e.setHeader(Mr,O)}}Ml(n.turn,k.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Rf(k.byteLength),k]))}else{let g=Af(e,n.turn,i,h===void 0),y;try{y=await Pl(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??El,returnBoundMs:n.turnReturnBoundMs??xl},i,g.sink,k=>{n.turn&&(n.turn.outputSeconds=ut(k))},r)}catch(k){let O=Nt(k,r);if(!g.started())throw O;n.turn&&(n.turn.streamError=!0),g.fail(O);return}if(y===null)return;try{await g.finish(y)}catch(k){let O=Nt(k,r);n.turn&&(n.turn.streamError=!0),g.fail(O);return}}}catch(g){throw Nt(g,r)}}catch(a){if(a instanceof Ie){fs(e,new Q(413,a.message));return}if(a instanceof Q){fs(e,a);return}throw a}}I();var Ur="/v1/audio/transcriptions";function Ul(t){return t===Ur}var Dl="/v1/audio/models",Pf=16*1024*1024,Cf=64*1024*1024,he=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function ms(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 Fl(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 Lf(t){if(!Fl(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 l=t[a+2]|t[a+3]<<8,u=(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:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}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 $f(t,e,n){if(t){if(t.model=Pe({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 Mf(t,e){t&&(t.outputUnits=e.seconds)}async function Nf(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let f=c.error??{},h=typeof f.type=="string"?f.type:"upstream_error",m=typeof f.message=="string"&&f.message.length>0&&Ke(f.message)?f.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new he(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new he(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new he(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=ut(d)),en(u,d)}function Bl(t,e){if(t instanceof he)return t;if(t instanceof He)throw t;return t instanceof oe?new he(404,t.message):new he(502,nn("transcription",t,e))}async function Uf(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Bl(s,r)}return o?!0:(ms(n,new he(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 Df=new Set(["file","model","language","response_format"]);async function Hl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Cf,s=n.maxAudioPartBytes??Pf;try{if(t.method!=="POST")throw new he(405,`${String(t.method)} is not supported on ${Ur}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new he(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Cr(t,o)}catch(b){throw b instanceof Ie?new he(413,b.message):new he(400,String(b instanceof Error?b.message:b))}let l=new Map;for(let b of a.keys()){if(!Df.has(b))throw new he(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);l.set(b,(l.get(b)??0)+1)}for(let[b,p]of l)if(p>1)throw new he(400,`form field "${b}" appears ${p} 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=a.get("model");if(u!==null&&typeof u!="string")throw new he(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new he(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new he(400,`response_format ${JSON.stringify(h)} 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 m=a.get("file");if(!(m instanceof File))throw new he(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new he(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await m.arrayBuffer());if(!Fl(_))throw new he(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 R=Lf(_);if(R===null)throw new he(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 $f(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await Uf(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let b=await Nf(n.clients,d,v,f,n.turn?Fe(n.turn):void 0,n.turn,r);Mf(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw Bl(b,r)}}catch(i){if(i instanceof Ie){ms(e,new he(413,i.message));return}if(i instanceof he){ms(e,i);return}throw i}}var Hr=require("@urun-sh/core");I();var hs="x-urun-profile",Hn="voice";var Me=class extends Error{status=400},Ff=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Bf=/\s/;function Hf(t){return Ff.test(t)}function gs(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Me(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function jl(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 Me(`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 Me(`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 Me(`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 ql(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 Me(`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 u=n.trim();if(u==="")throw new Me(`the ${hs} header is empty \u2014 the only profile this lane accepts is "${Hn}" (omit the header for the ordinary lane)`);if(u!==Hn)throw new Me(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${Hn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Hn)throw new Me(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Hn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Me("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 Me("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:jl(l,"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:jl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:gs(l,"sentence_flush",!0),includeReasoning:gs(l,"include_reasoning",!1),metadata:gs(l,"metadata",!1)}}var an=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&&Hf(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(Bf.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 _s(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function qf(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 Oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ce(t,e,n,r="invalid_request_error",o){Oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function vs(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=nt(r),a=i??ze(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 l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),Oe(t,u,{error:{message:a,type:o,code:l}})}function Xe(t,e,n,r){Oe(t,e,{type:"error",error:{type:n,message:r}})}function ln(t,e,n){if(e==="anthropic"){Oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Gf=64*1024*1024,jn=class extends Error{};async function Gl(t,e=Gf){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new jn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ut(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Jl(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Dr(t){let e=Jl(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Wl(t){let e=Dr(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Wf(t)},completion_tokens_details:{reasoning_tokens:0}}}function Wf(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Jf(t,e){let n=Jl(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Vf(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u: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 Kf(t,e){let n=Vf(e);n&&(t.timing=n),t.outputSeconds=ut(e)}function Dt(t,e){Jf(t,e),Kf(t,e)}async function jr(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 Vl(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 zf(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 Fr=class extends Error{};function Yf(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 Fr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Xf(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:Yf(n.role,n.content)})}return e}function ys(t){return Qt(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 Qf(t,e,n,r,o,s,i){let a=Tn(s.id),l=t.stream===!0;if(s.model=Pe(t),s.stream=l,await jr(s,e,typeof t.model=="string"?t.model:void 0),l){let b;try{b=await Cn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(p){if(p instanceof oe){ln(r,"openai",p);return}if(p instanceof Be){ce(r,p.status,p.message);return}if(p instanceof Je||p instanceof xe){r.setHeader("retry-after","2"),ce(r,503,p.message,"capacity_error");return}throw p}_s(r);for await(let p of b.events){if(p.type==="error"){s.streamError=!0;let g=p.error,y=nt(g),k=y??ze(s.id);y===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(p)}`),r.write(`event: error
35
37
  data: ${JSON.stringify({error:{message:k,type:g?.type??"upstream_error",code:g?.code??null}})}
36
38
 
37
- `),r.end();return}f.type==="response.completed"&&Lt(s,f.response),r.write(`event: ${String(f.type??"message")}
38
- data: ${JSON.stringify(f)}
39
+ `),r.end();return}p.type==="response.completed"&&Dt(s,p.response),r.write(`event: ${String(p.type??"message")}
40
+ data: ${JSON.stringify(p)}
39
41
 
40
42
  `)}r.write(`data: [DONE]
41
43
 
42
- `),r.end();return}let l;try{l=Yt(n,t)}catch(A){if(A instanceof He){ue(r,A.status,A.message);return}throw A}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Pe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await Fo(e,t,l,!1,Fe(s))}catch(A){if(A instanceof ne){nn(r,"openai",A);return}if(A instanceof He){ue(r,A.status,A.message);return}if(A instanceof We||A instanceof Ee){r.setHeader("retry-after","2"),ue(r,503,A.message,"capacity_error");return}throw A}let m=[],_=null;for await(let A of o.track(h,c,s)){if(m.push(A),A.type==="error"){ls(r,A,{inferenceId:s.id,operatorError:i});return}A.type==="response.completed"&&(_=A.response)}if(_==null){ue(r,502,"upstream produced no response.completed event","upstream_error");return}Lt(s,_);let S=zt(m,_),b=It(p,Jt(_).length,S);if(b){ue(r,502,Ot(c,b),"upstream_error");return}d&&n.remember(a,l,Do(_,S),d),Oe(r,200,{..._,id:a})}async function vf(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){ue(n,400,"chat/completions requires a messages array");return}let u;try{u=Ru(s,t)}catch(x){if(x instanceof $e){ue(n,x.status,x.message);return}throw x}let l=String(t.model??"urun"),d=Ra(o.id),c;try{c=wf(a)}catch(x){if(x instanceof Tr){ue(n,400,x.message);return}throw x}let p=Pe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Lr(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:hf(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}:{}},Fe(o))}catch(x){if(x instanceof ne){nn(n,"openai",x);return}if(x instanceof We||x instanceof Ee){n.setHeader("retry-after","2"),ue(n,503,x.message,"capacity_error");return}throw x}if(t.stream===!0){u?df(n):us(n);let x=[],P=new gt,I="",M=u?new tn(u,V=>{n.write(`data: ${JSON.stringify(Ct(d,l,{content:V},null))}
44
+ `),r.end();return}let u;try{u=tn(n,t)}catch(b){if(b instanceof Be){ce(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 d=t.store!==!1,c=Pe(t);o.model(c);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await Ko(e,t,u,!1,Fe(s))}catch(b){if(b instanceof oe){ln(r,"openai",b);return}if(b instanceof Be){ce(r,b.status,b.message);return}if(b instanceof Je||b instanceof xe){r.setHeader("retry-after","2"),ce(r,503,b.message,"capacity_error");return}throw b}let m=[],_=null;for await(let b of o.track(h,c,s)){if(m.push(b),b.type==="error"){vs(r,b,{inferenceId:s.id,operatorError:i});return}b.type==="response.completed"&&(_=b.response)}if(_==null){ce(r,502,"upstream produced no response.completed event","upstream_error");return}Dt(s,_);let R=en(m,_),v=$t(f,Qt(_).length,R);if(v){ce(r,502,Lt(c,v),"upstream_error");return}d&&n.remember(a,u,Vo(_,R),d),Oe(r,200,{..._,id:a})}async function Zf(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){ce(n,400,"chat/completions requires a messages array");return}let l;try{l=ql(s,t)}catch(E){if(E instanceof Me){ce(n,E.status,E.message);return}throw E}let u=String(t.model??"urun"),d=Na(o.id),c;try{c=Xf(a)}catch(E){if(E instanceof Fr){ce(n,400,E.message);return}throw E}let f=Pe(t);r.model(f),o.model=f,o.stream=t.stream===!0,await jr(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:zf(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}:{}},Fe(o))}catch(E){if(E instanceof oe){ln(n,"openai",E);return}if(E instanceof Je||E instanceof xe){n.setHeader("retry-after","2"),ce(n,503,E.message,"capacity_error");return}throw E}if(t.stream===!0){l?qf(n):_s(n);let E=[],C=new yt,w="",T=l?new an(l,M=>{n.write(`data: ${JSON.stringify(Ut(d,u,{content:M},null))}
43
45
 
44
- `)}):null,G=V=>{M?.flush(),n.write(V),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}})}
46
+ `)}):null,$=M=>{T?.flush(),n.write(M),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
45
47
 
46
- `),n.write(`data: ${JSON.stringify(Ct(d,l,{role:"assistant"},null))}
48
+ `),n.write(`data: ${JSON.stringify(Ut(d,u,{role:"assistant"},null))}
47
49
 
48
- `);for await(let oe of r.track(m,p,o)){x.push(oe);let Se=Kt(oe);if(oe.type==="response.output_text.delta"&&typeof oe.delta=="string")I+=oe.delta,M?M.push(oe.delta):n.write(`data: ${JSON.stringify(Ct(d,l,{content:oe.delta},null))}
50
+ `);for await(let X of r.track(m,f,o)){E.push(X);let ae=Zt(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")w+=X.delta,T?T.push(X.delta):n.write(`data: ${JSON.stringify(Ut(d,u,{content:X.delta},null))}
49
51
 
50
- `);else if(oe.type==="response.reasoning_text.delta"&&typeof oe.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(Ct(d,l,{reasoning_content:oe.delta},null))}
52
+ `);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(Ut(d,u,{reasoning_content:X.delta},null))}
51
53
 
52
- `);else if(Se){M?.flush();let{call:J,isNew:$}=P.add(Se),re=$?{index:Se.tool_index,id:J.id??`call_${Se.tool_index}`,type:"function",function:{name:J.name??"",arguments:Se.delta}}:{index:Se.tool_index,function:{arguments:Se.delta}};n.write(`data: ${JSON.stringify(Ct(d,l,{tool_calls:[re]},null))}
54
+ `);else if(ae){T?.flush();let{call:z,isNew:N}=C.add(ae),te=N?{index:ae.tool_index,id:z.id??`call_${ae.tool_index}`,type:"function",function:{name:z.name??"",arguments:ae.delta}}:{index:ae.tool_index,function:{arguments:ae.delta}};n.write(`data: ${JSON.stringify(Ut(d,u,{tool_calls:[te]},null))}
53
55
 
54
- `)}else if(oe.type==="error"){o.streamError=!0;let J=oe.error??{},$=tt(J),re=$??ze(o.id);$===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(oe)}`),G(`data: ${JSON.stringify({error:{message:re,type:J.type??"upstream_error",code:J.code??null}})}
56
+ `)}else if(X.type==="error"){o.streamError=!0;let z=X.error??{},N=nt(z),te=N??ze(o.id);N===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(X)}`),$(`data: ${JSON.stringify({error:{message:te,type:z.type??"upstream_error",code:z.code??null}})}
55
57
 
56
- `);return}}let V=is(et(x)),Z=It(h,P.size+V.length,I);if(Z){o.streamError=!0,G(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(p,Z)}})}
58
+ `);return}}let M=ys(tt(E)),F=$t(h,C.size+M.length,w);if(F){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Lt(f,F)}})}
57
59
 
58
- `);return}M?.flush(),P.size===0&&V.length>0&&n.write(`data: ${JSON.stringify(Ct(d,l,{tool_calls:V},null))}
60
+ `);return}T?.flush(),C.size===0&&M.length>0&&n.write(`data: ${JSON.stringify(Ut(d,u,{tool_calls:M},null))}
59
61
 
60
- `);let Y=P.size>0||V.length>0;n.write(`data: ${JSON.stringify(Ct(d,l,{},Y?"tool_calls":"stop"))}
62
+ `);let G=C.size>0||M.length>0;n.write(`data: ${JSON.stringify(Ut(d,u,{},G?"tool_calls":"stop"))}
61
63
 
62
- `);let Te=Ir(et(x));Lt(o,et(x)),Te&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:xu(et(x))})}
64
+ `);let se=Dr(tt(E));Dt(o,tt(E)),se&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Wl(tt(E))})}
63
65
 
64
66
  `),n.write(`data: [DONE]
65
67
 
66
- `),n.end();return}finally{M?.flush(),M?.dispose()}}let _="",S="",b=[],A=new gt;for await(let x of r.track(m,p,o)){b.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(_+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(S+=x.delta);let P=Kt(x);if(P&&A.add(P),x.type==="error"){ls(n,x,{inferenceId:o.id,operatorError:i});return}}let f=et(b);Lt(o,f);let g=is(f),y=g.length>0?g:is({output:A.items()}),k=It(h,y.length,_);if(k){ue(n,502,Ot(p,k),"upstream_error");return}let T=y.map(({index:x,...P})=>P),w={role:"assistant",content:_||null},O=S||Ou(f);O&&(w.reasoning_content=O),T.length>0&&(w.tool_calls=T),Oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:w,finish_reason:T.length>0?"tool_calls":"stop"}],usage:xu(f)})}var Mr="sense-latest";async function bf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ue(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Mr,a=Pe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){ue(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){ue(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){ue(n,400,"systemone media, when present, must be an array");return}let l=await Iu(t,i,a,e,n,r,o,s);l!==null&&Oe(n,200,l.answer)}async function Iu(t,e,n,r,o,s,i,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=u;let l=performance.now();s.model(n),await Lr(i,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Fe(i))}catch(b){if(b instanceof ne)return nn(o,"openai",b),null;if(b instanceof We||b instanceof Ee)return o.setHeader("retry-after","2"),ue(o,503,b.message,"capacity_error"),null;throw b}u.dial_ms=Math.round(performance.now()-c);let p=[],h=null;try{for await(let b of s.track(d,n,i))if(h===null&&(h=performance.now(),u.first_event_ms=Math.round(h-c)),p.push(b),b.type==="error")return ls(o,b,{inferenceId:i.id,operatorError:a}),null}catch(b){if(b instanceof ne)return h!==null&&(u.stream_ms=Math.round(performance.now()-h)),nn(o,"openai",b),null;if(b instanceof We||b instanceof Ee)return h!==null&&(u.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),ue(o,503,b.message,"capacity_error"),null;throw h!==null&&(u.stream_ms=Math.round(performance.now()-h)),b}h!==null&&(u.stream_ms=Math.round(performance.now()-h));let m=et(p);if(m==null)return ue(o,502,"upstream produced no response.completed event","upstream_error"),null;Lt(i,m);let _=zt(p,m),S;try{S=JSON.parse(_)}catch{return ue(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return ue(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let b=S.timing;if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"question_fwd_ms"in b&&"head_ms"in b){let A=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;u.question_fwd_ms=A(b.question_fwd_ms),u.head_ms=A(b.head_ms)}}return{answer:S,completed:m}}async function Sf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ue(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Mr,a=Pe({model:i});o.model=a,o.stream=!1;let u;try{u=Ba(t,i)}catch(p){if(p instanceof K){ue(n,400,p.message);return}throw p}let l=await Iu(u.systemone,i,a,e,n,r,o,s);if(l===null)return;let d;try{d=Wa(u.specs,l.answer)}catch(p){if(p instanceof Be){ue(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;Oe(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function kf(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Dn=class extends Error{};function Pr(t){return new Dn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Rf(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 Ef(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 Dn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function xf(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Pr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Pr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Af(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 Pr(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:xf(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Pr(a)}}return s(),r}function as(t){return Jt(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 Of(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ye(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){Ye(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ye(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(w=>typeof w!="string"))){Ye(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=Ea(o.id),l=[],d;try{t.system&&l.push({role:"system",content:kf(t.system)});for(let w of i)l.push(...Af(w));d=Ef(t.tool_choice)}catch(w){if(w instanceof Dn){Ye(n,400,"invalid_request_error",w.message);return}throw w}let c=Pe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Lr(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:l,stream:!0,tools:Rf(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Fe(o))}catch(w){if(w instanceof ne){nn(n,"anthropic",w);return}if(w instanceof We||w instanceof Ee){n.setHeader("retry-after","2"),Ye(n,503,"capacity_error",w.message);return}throw w}let m=(w,O)=>{n.destroyed||n.write(`event: ${w}
67
- data: ${JSON.stringify({type:w,...O})}
68
+ `),n.end();return}finally{T?.flush(),T?.dispose()}}let _="",R="",v=[],b=new yt;for await(let E of r.track(m,f,o)){v.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(_+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(R+=E.delta);let C=Zt(E);if(C&&b.add(C),E.type==="error"){vs(n,E,{inferenceId:o.id,operatorError:i});return}}let p=tt(v);Dt(o,p);let g=ys(p),y=g.length>0?g:ys({output:b.items()}),k=$t(h,y.length,_);if(k){ce(n,502,Lt(f,k),"upstream_error");return}let O=y.map(({index:E,...C})=>C),x={role:"assistant",content:_||null},P=R||Vl(p);P&&(x.reasoning_content=P),O.length>0&&(x.tool_calls=O),Oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:x,finish_reason:O.length>0?"tool_calls":"stop"}],usage:Wl(p)})}var qr="sense-latest";async function em(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ce(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:qr,a=Pe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){ce(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).length===0){ce(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){ce(n,400,"systemone media, when present, must be an array");return}let u=await Kl(t,i,a,e,n,r,o,s);u!==null&&Oe(n,200,u.answer)}async function Kl(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await jr(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Fe(i))}catch(v){if(v instanceof oe)return ln(o,"openai",v),null;if(v instanceof Je||v instanceof xe)return o.setHeader("retry-after","2"),ce(o,503,v.message,"capacity_error"),null;throw v}l.dial_ms=Math.round(performance.now()-c);let f=[],h=null;try{for await(let v of s.track(d,n,i))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-c)),f.push(v),v.type==="error")return vs(o,v,{inferenceId:i.id,operatorError:a}),null}catch(v){if(v instanceof oe)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),ln(o,"openai",v),null;if(v instanceof Je||v instanceof xe)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),ce(o,503,v.message,"capacity_error"),null;throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),v}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let m=tt(f);if(m==null)return ce(o,502,"upstream produced no response.completed event","upstream_error"),null;Dt(i,m);let _=en(f,m),R;try{R=JSON.parse(_)}catch{return ce(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return ce(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let v=R.timing;if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"question_fwd_ms"in v&&"head_ms"in v){let b=p=>typeof p=="number"&&Number.isFinite(p)&&p>=0?Math.round(p):null;l.question_fwd_ms=b(v.question_fwd_ms),l.head_ms=b(v.head_ms)}}return{answer:R,completed:m}}async function tm(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ce(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:qr,a=Pe({model:i});o.model=a,o.stream=!1;let l;try{l=al(t,i)}catch(f){if(f instanceof Y){ce(n,400,f.message);return}throw f}let u=await Kl(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=dl(l.specs,u.answer)}catch(f){if(f instanceof qe){ce(n,502,f.message,"upstream_error");return}throw f}let c=u.completed.usage;Oe(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function nm(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var qn=class extends Error{};function Br(t){return new qn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function rm(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 om(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 qn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function sm(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Br(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Br(`tool_result > ${r}`);e+=String(n.text??"")}return e}function im(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 Br(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:sm(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Br(a)}}return s(),r}function ws(t){return Qt(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 am(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Xe(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){Xe(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Xe(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(x=>typeof x!="string"))){Xe(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Ua(o.id),u=[],d;try{t.system&&u.push({role:"system",content:nm(t.system)});for(let x of i)u.push(...im(x));d=om(t.tool_choice)}catch(x){if(x instanceof qn){Xe(n,400,"invalid_request_error",x.message);return}throw x}let c=Pe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await jr(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:u,stream:!0,tools:rm(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Fe(o))}catch(x){if(x instanceof oe){ln(n,"anthropic",x);return}if(x instanceof Je||x instanceof xe){n.setHeader("retry-after","2"),Xe(n,503,"capacity_error",x.message);return}throw x}let m=(x,P)=>{n.destroyed||n.write(`event: ${x}
69
+ data: ${JSON.stringify({type:x,...P})}
68
70
 
69
- `)};if(t.stream===!0){let w=r.track(h,c,o);us(n),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,x="",P=0,I="none",M=()=>I,G=-1,V=-1,Z=new gt,Y=[],Te=()=>{I!=="none"&&(I="none",m("content_block_stop",{index:G}))},oe=(ae,de)=>{Te(),I=ae,G=P++,m("content_block_start",{index:G,content_block:de})};for await(let ae of w){if(n.destroyed)break;Y.push(ae);let de=Kt(ae);if(ae.type==="response.reasoning_text.delta"&&typeof ae.delta=="string")M()!=="thinking"&&oe("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:G,delta:{type:"thinking_delta",thinking:ae.delta}});else if(ae.type==="response.output_text.delta"&&typeof ae.delta=="string")M()!=="text"&&oe("text",{type:"text",text:""}),O+=1,x+=ae.delta,m("content_block_delta",{index:G,delta:{type:"text_delta",text:ae.delta}});else if(de){let{call:Le}=Z.add(de);(M()!=="tool"||de.tool_index!==V)&&(V=de.tool_index,oe("tool",{type:"tool_use",id:Le.id??`call_${de.tool_index}`,name:Le.name??"",input:{}})),de.delta&&m("content_block_delta",{index:G,delta:{type:"input_json_delta",partial_json:de.delta}})}else if(ae.type==="error"){o.streamError=!0;let Le=ae.error,ot=tt(Le);ot===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(ae)}`),m("error",{error:{type:"api_error",message:ot??ze(o.id)}}),n.end();return}}if(n.destroyed)return;let Se=et(Y),J=Jt(Se),$=It(p,Z.size+J.length,x);if($){o.streamError=!0,m("error",{error:{type:"api_error",message:Ot(c,$)}}),n.end();return}Te();let re=[];if(Z.size===0)try{re=as(Se)}catch(ae){o.streamError=!0;let de=Ue(ae,{inferenceId:o.id});de.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(ae instanceof Error?ae.message:ae)}`),m("error",{error:{type:"api_error",message:de.message}}),n.end();return}P===0&&re.length===0&&(oe("text",{type:"text",text:""}),Te()),re.forEach(ae=>{let de=P++;m("content_block_start",{index:de,content_block:{...ae,input:{}}}),m("content_block_delta",{index:de,delta:{type:"input_json_delta",partial_json:JSON.stringify(ae.input??{})}}),m("content_block_stop",{index:de})});let rt=Z.size>0||re.length>0,ie=Ir(Se);Lt(o,Se),m("message_delta",{delta:{stop_reason:rt?"tool_use":"end_turn"},usage:ie?{input_tokens:ie.input_tokens,output_tokens:ie.output_tokens}:{output_tokens:O}}),m("message_stop",{}),n.end();return}let _="",S="",b=[],A=new gt;for await(let w of r.track(h,c,o)){b.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(_+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(S+=w.delta);let O=Kt(w);if(O&&A.add(O),w.type==="error"){let x=w.error,P=x?.type==="invalid_request_error",I=tt(x);I===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(w)}`),Ye(n,P?400:502,P?"invalid_request_error":"api_error",I??ze(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=et(b);Lt(o,f);let g;try{g=as(f),g.length===0&&A.size>0&&(g=as({output:A.items()}))}catch(w){let O=Ue(w,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(w instanceof Error?w.message:w)}`),Ye(n,502,"api_error",O.message);return}let y=It(p,g.length,_);if(y){Ye(n,502,"api_error",Ot(c,y));return}let k=[],T=S||Ou(f);T&&k.push({type:"thinking",thinking:T}),(_||g.length===0)&&k.push({type:"text",text:_}),k.push(...g),Oe(n,200,{id:u,type:"message",role:"assistant",content:k,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:Ir(f)??{input_tokens:0,output_tokens:0}})}function If(t){Ze(process.stdout,t)}function Tu(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??If,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new xt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),h=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(f,g,y,k,T)=>h?Ye(c,f,k,g):ue(c,f,g,y,T),_=Uo(p.pathname),S=p.pathname.startsWith("/partners/"),b=_||S?{id:En(),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(Sa,b.id),c.once("close",()=>{let f=xa({turn:b,method:d.method??"",path:p.pathname,res:c});i(Aa(f)),u?.(f),Mi({record:f,ledger:t.ledger??null,req:d})}));let A=()=>ka(p.pathname,b);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){Oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){Oe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===Qn?"canonical":p.pathname===bn?"huggingface":null;if(f){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let T=t.usage;if(!T){m(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 w=T.authorize(d),O;try{O=await Eu(d,Fi)}catch(I){if(I instanceof Un){m(413,I.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=I=>T.lookup(w,I),P;try{if(f==="canonical"){let I=Hi(O),M=await x(I);Zn(M,I),P={requests:M}}else P=await qi(O,x)}catch(I){if(I instanceof mt){m(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}Oe(c,200,P);return}if(d.method==="GET"&&p.pathname===vt){let T=await s(d);if(b&&(b.org=T.tenant??null),!T.openRouterModels){m(501,`GET ${vt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Oe(c,200,await T.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${bn} and GET ${vt}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(b&&(b.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:vt}),c.end();return}Oe(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===Ka){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Oe(c,200,await g.listImageModels());return}if(Ja(p.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let T={clients:g,imageModels:g.supportsImages,stats:l,turn:A(),operatorLog:a};p.pathname===Rr?await ou(d,c,T):await ru(d,c,T);return}if(d.method==="GET"&&p.pathname===_u){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Oe(c,200,await g.listSpeechToTextModels());return}if(wu(p.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Or}`,"not_implemented","not_implemented_error");return}let T={clients:g,transcriptionModels:g.supportsTranscription,stats:l,turn:A(),operatorLog:a};await Su(d,c,T);return}if(fu(p.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${$n}`,"not_implemented","not_implemented_error");return}let T={clients:g,speechModels:g.supportsSpeech,stats:l,turn:A(),operatorLog:a};await yu(d,c,T);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await Eu(d)}catch(T){if(T instanceof Un){m(413,T.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",k,k),await _f(y,g,An(g),c,l,A(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",k,k),await vf(y,g,c,l,A(),d.headers[ss],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",k,k),await bf(y,g,c,l,A(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",k,k),await Sf(y,g,c,l,A(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",k,k),await Of(y,g,c,l,A(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",k,k),Ye(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let g=String(f instanceof Error?f.message:f);if(!c.headersSent){let T=o?.(f)??null;if(T){T.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${T.operatorDetail}`),m(T.status,g,T.openaiType,T.anthropicType,T.code);return}if(f instanceof Cr.SessionAllocationError){let O=fr(f.code);if(O){let x=f.retryAfterSeconds??(O.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),m(O.status,Tn(O,f.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof Cr.SessionFailedError){let O=mr(f);if(O){let x=O.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),m(O.status,Tn(O,f.status.sessionId?`session ${f.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof ge){m(502,g,"upstream_error","api_error");return}if(f instanceof Ve){f.retryable&&c.setHeader("Retry-After","1");let O=Ue(f,{inferenceId:b?.id??null});O.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Je(f)}`),m(502,O.message,"upstream_error","api_error",f.code);return}if(f instanceof ht){c.setHeader("Retry-After",String(f.retryAfterSeconds)),m(f.status,g,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let w=Ue(f,{inferenceId:b?.id??null});w.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Je(f)}`),m(500,w.message,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let y=f instanceof Ve?f.code:null,k=Ue(f,{inferenceId:b?.id??null});k.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Je(f)}`),c.destroyed||(h?c.write(`event: error
71
+ `)};if(t.stream===!0){let x=r.track(h,c,o);_s(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let P=0,E="",C=0,w="none",T=()=>w,$=-1,M=-1,F=new yt,G=[],se=()=>{w!=="none"&&(w="none",m("content_block_stop",{index:$}))},X=(de,fe)=>{se(),w=de,$=C++,m("content_block_start",{index:$,content_block:fe})};for await(let de of x){if(n.destroyed)break;G.push(de);let fe=Zt(de);if(de.type==="response.reasoning_text.delta"&&typeof de.delta=="string")T()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:de.delta}});else if(de.type==="response.output_text.delta"&&typeof de.delta=="string")T()!=="text"&&X("text",{type:"text",text:""}),P+=1,E+=de.delta,m("content_block_delta",{index:$,delta:{type:"text_delta",text:de.delta}});else if(fe){let{call:Le}=F.add(fe);(T()!=="tool"||fe.tool_index!==M)&&(M=fe.tool_index,X("tool",{type:"tool_use",id:Le.id??`call_${fe.tool_index}`,name:Le.name??"",input:{}})),fe.delta&&m("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:fe.delta}})}else if(de.type==="error"){o.streamError=!0;let Le=de.error,st=nt(Le);st===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(de)}`),m("error",{error:{type:"api_error",message:st??ze(o.id)}}),n.end();return}}if(n.destroyed)return;let ae=tt(G),z=Qt(ae),N=$t(f,F.size+z.length,E);if(N){o.streamError=!0,m("error",{error:{type:"api_error",message:Lt(c,N)}}),n.end();return}se();let te=[];if(F.size===0)try{te=ws(ae)}catch(de){o.streamError=!0;let fe=Ue(de,{inferenceId:o.id});fe.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(de instanceof Error?de.message:de)}`),m("error",{error:{type:"api_error",message:fe.message}}),n.end();return}C===0&&te.length===0&&(X("text",{type:"text",text:""}),se()),te.forEach(de=>{let fe=C++;m("content_block_start",{index:fe,content_block:{...de,input:{}}}),m("content_block_delta",{index:fe,delta:{type:"input_json_delta",partial_json:JSON.stringify(de.input??{})}}),m("content_block_stop",{index:fe})});let ot=F.size>0||te.length>0,ue=Dr(ae);Dt(o,ae),m("message_delta",{delta:{stop_reason:ot?"tool_use":"end_turn"},usage:ue?{input_tokens:ue.input_tokens,output_tokens:ue.output_tokens}:{output_tokens:P}}),m("message_stop",{}),n.end();return}let _="",R="",v=[],b=new yt;for await(let x of r.track(h,c,o)){v.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(_+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(R+=x.delta);let P=Zt(x);if(P&&b.add(P),x.type==="error"){let E=x.error,C=E?.type==="invalid_request_error",w=nt(E);w===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(x)}`),Xe(n,C?400:502,C?"invalid_request_error":"api_error",w??ze(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let p=tt(v);Dt(o,p);let g;try{g=ws(p),g.length===0&&b.size>0&&(g=ws({output:b.items()}))}catch(x){let P=Ue(x,{inferenceId:o.id});P.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(x instanceof Error?x.message:x)}`),Xe(n,502,"api_error",P.message);return}let y=$t(f,g.length,_);if(y){Xe(n,502,"api_error",Lt(c,y));return}let k=[],O=R||Vl(p);O&&k.push({type:"thinking",thinking:O}),(_||g.length===0)&&k.push({type:"text",text:_}),k.push(...g),Oe(n,200,{id:l,type:"message",role:"assistant",content:k,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:Dr(p)??{input_tokens:0,output_tokens:0}})}function lm(t){et(process.stdout,t)}function zl(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??lm,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new Pt;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),h=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),m=(p,g,y,k,O)=>h?Xe(c,p,k,g):ce(c,p,g,y,O),_=Jo(f.pathname),R=f.pathname.startsWith("/partners/"),v=_||R?{id:Tt(),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;v&&(c.setHeader($a,v.id),c.once("close",()=>{let p=Da({turn:v,method:d.method??"",path:f.pathname,res:c});i(Fa(p)),l?.(p),rr({record:p,ledger:t.ledger??null,req:d})}));let b=()=>Ma(f.pathname,v);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){Oe(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){Oe(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let p=f.pathname===sr?"canonical":f.pathname===xn?"huggingface":null;if(p){if(d.method!=="POST"){m(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let O=t.usage;if(!O){m(501,`${f.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 x=O.authorize(d),P;try{P=await Gl(d,Xi)}catch(w){if(w instanceof jn){m(413,w.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let E=w=>O.lookup(x,w),C;try{if(p==="canonical"){let w=Qi(P),T=await E(w);ir(T,w),C={requests:T}}else C=await ta(P,E)}catch(w){if(w instanceof ht){m(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}Oe(c,200,C);return}if(d.method==="GET"&&f.pathname===kt){let O=await s(d);if(v&&(v.org=O.tenant??null),!O.openRouterModels){m(501,`GET ${kt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Oe(c,200,await O.openRouterModels());return}if(f.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${xn} and GET ${kt}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(v&&(v.org=g.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:kt}),c.end();return}Oe(c,200,await g.listModels());return}if(d.method==="GET"&&f.pathname===fl){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Oe(c,200,await g.listImageModels());return}if(pl(f.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let O={clients:g,imageModels:g.supportsImages,stats:u,turn:b(),operatorLog:a};f.pathname===Lr?await kl(d,c,O):await Sl(d,c,O);return}if(d.method==="GET"&&f.pathname===Dl){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Oe(c,200,await g.listSpeechToTextModels());return}if(Ul(f.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Ur}`,"not_implemented","not_implemented_error");return}let O={clients:g,transcriptionModels:g.supportsTranscription,stats:u,turn:b(),operatorLog:a};await Hl(d,c,O);return}if(Cl(f.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Bn}`,"not_implemented","not_implemented_error");return}let O={clients:g,speechModels:g.supportsSpeech,stats:u,turn:b(),operatorLog:a};await Nl(d,c,O);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await Gl(d)}catch(O){if(O instanceof jn){m(413,O.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=Buffer.byteLength(JSON.stringify(y));if(f.pathname==="/v1/responses"){u.request("responses",k,k),await Qf(y,g,Pn(g),c,u,b(),a);return}if(f.pathname==="/v1/chat/completions"){u.request("chat_completions",k,k),await Zf(y,g,c,u,b(),d.headers[hs],a);return}if(f.pathname==="/v1/systemone"){u.request("systemone",k,k),await em(y,g,c,u,b(),a);return}if(f.pathname==="/v1/decisions"){u.request("decisions",k,k),await tm(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages"){u.request("messages",k,k),await am(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",k,k),Xe(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let g=String(p instanceof Error?p.message:p);if(!c.headersSent){let O=o?.(p)??null;if(O){O.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${O.operatorDetail}`),m(O.status,g,O.openaiType,O.anthropicType,O.code);return}if(p instanceof Hr.SessionAllocationError){let P=br(p.code);if(P){let E=p.retryAfterSeconds??(P.status===429?30:void 0);E!==void 0&&c.setHeader("Retry-After",String(E)),m(P.status,$n(P,p.code??void 0),P.openaiType,P.anthropicType,P.code);return}}if(p instanceof Hr.SessionFailedError){let P=Sr(p);if(P){let E=P.status===429?30:void 0;E!==void 0&&c.setHeader("Retry-After",String(E)),m(P.status,$n(P,p.status.sessionId?`session ${p.status.sessionId}`:void 0),P.openaiType,P.anthropicType,P.code);return}}if(p instanceof we){m(502,g,"upstream_error","api_error");return}if(p instanceof Ve){p.retryable&&c.setHeader("Retry-After","1");let P=Ue(p,{inferenceId:v?.id??null});P.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:je(p)}`),m(502,P.message,"upstream_error","api_error",p.code);return}if(p instanceof wt){c.setHeader("Retry-After",String(p.retryAfterSeconds)),m(p.status,g,p.status===429?"capacity_error":"upstream_error",p.status===429?"rate_limit_error":"overloaded_error",p.code);return}let x=Ue(p,{inferenceId:v?.id??null});x.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:je(p)}`),m(500,x.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let y=p instanceof Ve?p.code:null,k=Ue(p,{inferenceId:v?.id??null});k.redacted&&a(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:je(p)}`),c.destroyed||(h?c.write(`event: error
70
72
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:k.message}})}
71
73
 
72
74
  `):c.write(`data: ${JSON.stringify({error:{message:k.message,type:"upstream_error",code:y}})}
73
75
 
74
- `)),c.end()})}}E();var lt=(t,e)=>Object.assign(new Error(e),{status:t}),Cf='"transcription" (a transcription session), or no intent at all (the realtime voice session)',cs=(t,e,n)=>new Q(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),ds=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ne?lt(404,n.message):n}};async function Pu(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw lt(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Cf}`);if(o==="transcription")throw lt(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 lt(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 lt(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(h){throw h instanceof ne?lt(404,h.message):h}if(!p)throw lt(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(h){throw h instanceof ne?lt(404,h.message):h}if(p!=="stt")throw lt(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 ds(t,n.stt),i=await ds(t,e),a=await ds(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let h=new AbortController;return d=h,Lf({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,h.signal,()=>{d===h&&(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(h){throw h instanceof Q?cs("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function ps(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var $r=class extends Error{};async function*Lf(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"),h=!1,m=null,_=null,S=[],b=null,A=new Promise((P,I)=>{n&&n.addEventListener("abort",()=>I(new $r),{once:!0})}),f=()=>h||n?.aborted===!0,g=async P=>{if(f())return;let I;try{I=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:P}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(G){throw G instanceof Q?cs("tts",u.tts,G):G}let M=I[Symbol.asyncIterator]();_=M;try{for(;;){let G=M.next(),V;try{V=await Promise.race([G,A])}catch(Y){if(G.catch(()=>{}),Y instanceof $r)return;throw Y}if(V.done)return;let Z=V.value;if(Z.type==="error"){let Y=Z.error&&typeof Z.error.message=="string"?Z.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${Y}`)}if(Z.type==="response.completed")return}}finally{_===M&&(_=null)}},y=async()=>{for(;S.length>0&&!f();){let P=S.shift();await g(P)}},k=P=>{if(P===""||f()||(S.push(P),b!==null))return;let I=y();b=I,I.then(()=>{b===I&&(b=null)},M=>{b===I&&(b=null),m??=M})},T=()=>{h=!0,S.length=0;let P=_;if(_=null,P){let I=P.return?.();I&&I.catch(()=>{})}},w=async()=>{for(;S.length>0||b!==null;){let P=b;if(P===null){await g(S.shift());continue}await P}},O=p?new tn({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},P=>k(P)):null,x=null;try{let P;try{P=await o.createResponseOn(s,d)}catch(I){throw I instanceof Q?cs("chat",a,I):I}for await(let I of P){if(f())return;let M=I;if(M.type==="error"){yield I;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield I,O?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){O?.flush(),yield I;continue}if(M.type==="response.completed"){x=I.response;continue}}O?.flush(),O?.dispose(),p&&await w(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),T();try{if(m instanceof Q)throw m}finally{r?.()}}}var qe=(t,e)=>Object.assign(new Error(e),{status:t});function Lu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Mu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function $u(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Mf='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Nu(t,e,n,r){if(!t.supportsAudio)throw qe(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(c){throw c instanceof ne?qe(404,c.message):c}if(!o){let c=null;if(t.realtimeCompanionsFor)try{c=await t.realtimeCompanionsFor(e)}catch(p){throw p instanceof ne?qe(404,p.message):p}if(c!==null)return await Pu(t,e,c,n,r);throw qe(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 qe(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(c){throw c instanceof ne?qe(404,c.message):c}if(s&&!t.openTurnsOn)throw qe(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 c;try{c=await t.transcriptStreamFor(e)}catch(p){throw p instanceof ne?qe(404,p.message):p}if(c!=="stt")throw qe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \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 qe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Mf}`);if(r==="transcription"&&!s)throw qe(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=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(c){throw c instanceof Ee?qe(503,c.message):c}let a=`conn_${(0,Cu.randomUUID)()}`,l={audio:await t.openAudioOn(i,n,a).catch(c=>{throw t.releaseSessionHandle?.(i),c})},d={clients:{createResponse:async c=>await t.createResponseOn(i,c,a)},voice:o,audioSession:l};return t.openVideoOn&&(d.video=()=>t.openVideoOn(i,n)),s&&(d.turns=c=>t.openTurnsOn(i,c)),r==="transcription"&&(d.intent="transcription"),t.releaseSessionHandle&&(d.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(d.model=e),d}E();var nl=require("@urun-sh/core"),rl=require("@urun-sh/core/internal"),ol=ke(require("ws"),1);E();var Hu=require("http");E();var $f=require("bullmq"),Nf=require("crypto");var Uu=12e4;var Uf="/pooler/v1/lanes/pick",Df="/pooler/v1/lanes/status",Ff=1e4,Fn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function Du(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"),h=null;try{h=p===""?null:JSON.parse(p)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",i)});l.on("timeout",()=>{l.destroy(new Fn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),l.on("error",i),l.end(u)})}function Fu(t,e,n){if(t===503)return new Ee(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 ju(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=Math.min(Math.max(Math.trunc(r),0),Uu),s=await Du(t,"POST",Uf,{pool:e,model:n,hold_ms:o},o+Ff);if(s.status!==200)throw Fu(s.status,s.json,e);return(s.json?.lanes??[]).filter(a=>typeof a.lane_id=="string"&&a.lane_id!==""&&typeof a.host=="string"&&a.host!=="").map(a=>({laneId:a.lane_id,host:a.host}))},async status(){let e=await Du(t,"GET",Df,void 0,5e3);if(e.status!==200)throw Fu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}E();E();E();async function Bu(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}E();E();function qu(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 Nr(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}E();E();function Gu(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 Hf="llm-resp";async function*Dr(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 Gu(s);return}}}async function*fs(t,e){let n=`${Hf}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Dr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Fr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(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=Nr(e,n,this.consumerId);return this.write(r),fs(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=qu(e,n,r,this.consumerId);return this.write(o),fs(this.session,r)})}async writeGated(e,n){try{await Bu(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Wu=0;function Bf(){return Wu+=1,`req_${Date.now().toString(36)}_${Wu.toString(36)}`}var Mt=class{transport;constructor(e,n){this.transport=new Fr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Bf(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};E();var rn=ke(require("yjs"),1),Vu=require("@urun-sh/core/internal"),qf=3e4;function Gf(t){return(e,n,r)=>{let o=t(e);rn.applyUpdate(n,rn.encodeStateAsUpdate(o));let s=a=>rn.applyUpdate(o,a),i=a=>rn.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)}}}}function ms(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Gf(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=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new Vu.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},u=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*p(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>p(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:u,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let p=d?.timeout??t.whenLiveTimeoutMs??qf;await new Promise((h,m)=>{let _=setTimeout(()=>{S(),m(new Error(`lane ${e} llm doc never synced within ${p}ms`))},p),S=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",b),h()}),b=()=>{clearTimeout(_),S(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",b,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}E();var $t=ke(require("ws"),1),Nt=require("@urun-sh/core"),Ju="/stream/";function Ku(t){if(!t.startsWith(Ju))return null;let e=t.slice(Ju.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Br(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Hr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>Nt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var jr=class{reassembler=new Nt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===Nt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},hs=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=zu||a.bytes+o.byteLength>Yu)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${zu} frames / ${Yu} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,u)=>a+u.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},zu=256,Yu=8*1024*1024,nt=new hs;function Xu(t,e){let n=new jr,r={send(o){nt.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Hr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),nt.detach(t,e,r)}};return nt.attach(t,e,r),r}function Wf(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function Qu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new $t.default(r,Br(e)),s=new jr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Hr(a)}catch(u){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(u)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Hr(i),o.readyState!==$t.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function gs(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
76
+ `)),c.end()})}}I();var dt=(t,e)=>Object.assign(new Error(e),{status:t}),cm='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ss=(t,e,n)=>new ee(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),bs=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof oe?dt(404,n.message):n}};async function Yl(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw dt(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${cm}`);if(o==="transcription")throw dt(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 dt(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 dt(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 f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof oe?dt(404,h.message):h}if(!f)throw dt(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 f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof oe?dt(404,h.message):h}if(f!=="stt")throw dt(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \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 bs(t,n.stt),i=await bs(t,e),a=await bs(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,pm({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof ee?Ss("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function ks(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Gr=class extends Error{};async function*pm(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,_=null,R=[],v=null,b=new Promise((C,w)=>{n&&n.addEventListener("abort",()=>w(new Gr),{once:!0})}),p=()=>h||n?.aborted===!0,g=async C=>{if(p())return;let w;try{w=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:C}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof ee?Ss("tts",l.tts,$):$}let T=w[Symbol.asyncIterator]();_=T;try{for(;;){let $=T.next(),M;try{M=await Promise.race([$,b])}catch(G){if($.catch(()=>{}),G instanceof Gr)return;throw G}if(M.done)return;let F=M.value;if(F.type==="error"){let G=F.error&&typeof F.error.message=="string"?F.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${G}`)}if(F.type==="response.completed")return}}finally{_===T&&(_=null)}},y=async()=>{for(;R.length>0&&!p();){let C=R.shift();await g(C)}},k=C=>{if(C===""||p()||(R.push(C),v!==null))return;let w=y();v=w,w.then(()=>{v===w&&(v=null)},T=>{v===w&&(v=null),m??=T})},O=()=>{h=!0,R.length=0;let C=_;if(_=null,C){let w=C.return?.();w&&w.catch(()=>{})}},x=async()=>{for(;R.length>0||v!==null;){let C=v;if(C===null){await g(R.shift());continue}await C}},P=f?new an({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},C=>k(C)):null,E=null;try{let C;try{C=await o.createResponseOn(s,d)}catch(w){throw w instanceof ee?Ss("chat",a,w):w}for await(let w of C){if(p())return;let T=w;if(T.type==="error"){yield w;return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){yield w,P?.push(T.delta);continue}if(T.type==="response.function_call_arguments.delta"){P?.flush(),yield w;continue}if(T.type==="response.completed"){E=w.response;continue}}P?.flush(),P?.dispose(),f&&await x(),E!==null&&(yield{type:"response.completed",response:E})}finally{P?.dispose(),O();try{if(m instanceof ee)throw m}finally{r?.()}}}var Ge=(t,e)=>Object.assign(new Error(e),{status:t});function Ql(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function eu(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var fm='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function tu(t,e,n,r,o){if(!t.supportsAudio)throw Ge(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 s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof oe?Ge(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof oe?Ge(404,m.message):m}if(h!==null)return await Yl(t,e,h,n,r);throw Ge(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 Ge(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(h){throw h instanceof oe?Ge(404,h.message):h}if(i&&!t.openTurnsOn)throw Ge(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 h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof oe?Ge(404,m.message):m}if(h!=="stt")throw Ge(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \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 Ge(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${fm}`);if(r==="transcription"&&!i)throw Ge(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 a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof xe?Ge(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,Xl.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}I();var Eu=require("@urun-sh/core"),xu=require("@urun-sh/core/internal"),Au=Re(require("ws"),1);I();var pu=require("http");I();var iu=require("http");I();function nu(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 Wr(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}I();I();function ru(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 ou=require("@urun-sh/core/internal");I();var mm="llm-resp";async function*Vr(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,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.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 ru(s);return}}}async function*Rs(t,e){let n=`${mm}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Vr(e,t.stream(n).messages())}finally{try{(0,ou.gcRequest)(t.doc("llm"),e)}catch{}}}var gm="/pooler/v1/inference",Qe=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},hm=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)},ym=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)}},au=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)}),wm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await au(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 Qe(t.status,e,n,t.retryAfterSeconds)};async function _m(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${gm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:hm(e),firstMessage:ym(e)}});return new Promise((a,l)=>{let u=(0,iu.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})});u.on("error",d=>l(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var su=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*vm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
77
+
78
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=su(s);i!==null&&(yield i)}let n=su(e);n!==null&&(yield n)}async function lu(t,e,n,r){let o=Wr(e,n,r),s=o.model??"";if(s==="")throw new Qe(400,"missing_model","the pooler submit requires a model");let i=await _m(t,o,n,s,e.stream===!0);if(i.status>=400)throw await wm(i);let a=e.stream===!0?Vr(n,vm(i)):await bm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function bm(t,e){let n=await au(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 Qe(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Vr(e,(async function*(){yield o})())}I();var Sm=require("@urun-sh/core"),km=require("bullmq"),Rm=require("crypto");var uu=12e4;var Em="/pooler/v1/lanes/pick",xm="/pooler/v1/lanes/status",Am=1e4,Gn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function du(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,pu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Gn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function cu(t,e,n,r){if(t===400&&Im(e)?.code==="lane_target")return new Mt(n,r);if(t===503)return new xe(n);let o=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: ${o}`)}function Im(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function fu(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),uu),l=await du(t,"POST",Em,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Am);if(l.status!==200)throw cu(l.status,l.json,e,s);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await du(t,"GET",xm,void 0,5e3);if(e.status!==200)throw cu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}I();I();I();async function mu(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var Kr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(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=Wr(e,n,this.consumerId);return this.write(r),Rs(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=nu(e,n,r,this.consumerId);return this.write(o),Rs(this.session,r)})}async writeGated(e,n){try{await mu(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var gu=0;function Tm(){return gu+=1,`req_${Date.now().toString(36)}_${gu.toString(36)}`}var Ft=class{transport;constructor(e,n){this.transport=new Kr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Tm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};I();var un=Re(require("yjs"),1),hu=require("@urun-sh/core/internal"),Pm=3e4;function Cm(t){return(e,n,r)=>{let o=t(e);un.applyUpdate(n,un.encodeStateAsUpdate(o));let s=a=>un.applyUpdate(o,a),i=a=>un.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)}}}}function Es(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Cm(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=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new hu.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??Pm;await new Promise((h,m)=>{let _=setTimeout(()=>{R(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),R=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",v),h()}),v=()=>{clearTimeout(_),R(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}I();var Bt=Re(require("ws"),1),Ht=require("@urun-sh/core"),yu="/stream/";function wu(t){if(!t.startsWith(yu))return null;let e=t.slice(yu.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Xr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function zr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>Ht.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Yr=class{reassembler=new Ht.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===Ht.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},As=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>_u&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${_u} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},_u=8*1024*1024,rt=new As;function vu(t,e){let n=new Yr,r={send(o){rt.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{zr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),rt.detach(t,e,r)}};return rt.attach(t,e,r),r}function Lm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function bu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new Bt.default(r,Xr(e)),s=new Yr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{zr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(zr(i),o.readyState!==Bt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function xs(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
75
79
  `;t.end(`HTTP/1.1 ${e} ${r}\r
76
80
  Connection: close\r
77
81
  Content-Type: text/plain; charset=utf-8\r
78
82
  Content-Length: ${Buffer.byteLength(o)}\r
79
83
  \r
80
- ${o}`)}function Zu(t,e){let n=e.heartbeatMs??3e4,r=new $t.WebSocketServer({noServer:!0,handleProtocols:(l,d)=>{let c=Ku(new URL(d.url??"/","http://localhost").pathname);if(!c)return!1;let p=Br(c.name);return l.has(p)?p:!1}}),o=new Map,s=new Set,i=!1,a=(l,d,c,p)=>{let h={client:c,upstream:p,laneId:l,name:d};s.add(h);let m=_=>{if(s.delete(h)){console.warn(`[lane-stream] ${l}/${d}: host-affinity pump torn down (${_})`);for(let S of[c,p])try{(S.readyState===$t.default.OPEN||S.readyState===$t.default.CONNECTING)&&S.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let _=(S,b)=>{let A=!0;S.on("pong",()=>{A=!0});let f=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${l}/${d}: pong timeout on ${b} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${b} dial never sends a close)`),clearInterval(f);try{S.terminate()}catch{}m(`${b} pong timeout`);return}A=!1;try{S.ping()}catch{}},n);f.unref?.();let g=()=>clearInterval(f);S.once("close",g),S.once("error",g)};_(c,"client"),_(p,"host")}c.on("message",_=>{try{p.send(_,{binary:!0})}catch(S){m(`upstream send failed: ${String(S)}`)}}),p.on("message",_=>{try{c.send(_,{binary:!0})}catch(S){m(`client send failed: ${String(S)}`)}}),c.on("close",()=>m("client socket closed")),c.on("error",()=>m("client socket error")),p.on("close",()=>m("host socket closed")),p.on("error",()=>m("host socket error"))},u=(l,d,c)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{gs(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let h=Ku(p.pathname);h&&(i||d.destroyed||(async()=>{let m=p.searchParams.get("token")??"",_=null;try{_=m===""?null:await e.verifyToken(m,h.laneId,h.name)}catch{_=null}if(_===null){gs(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let S=await e.hostOf(h.laneId).catch(()=>null);if(S&&S!==e.selfAddress)try{let b=await e.podToPodDial(h.laneId,h.name,S);r.handleUpgrade(l,d,c,A=>{a(h.laneId,h.name,A,b)});return}catch(b){console.warn(`[lane-stream] ${h.laneId}/${h.name}: host dial to ${S} failed (${String(b)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(l,d,c,S=>{let b=Wf(S);if(o.set(S,b),nt.attach(h.laneId,h.name,b),n>0){let f=!0;S.on("pong",()=>{f=!0});let g=setInterval(()=>{if(!f){console.warn(`[lane-stream] ${h.laneId}/${h.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(g),S.terminate();return}f=!1;try{S.ping()}catch{}},n);g.unref?.();let y=()=>clearInterval(g);S.once("close",y),S.once("error",y)}S.on("message",f=>{let g=new Uint8Array(f);try{Hr(g)}catch(y){console.warn(`[lane-stream] ${h.laneId}/${h.name}: dropped malformed envelope: ${String(y)}`);return}nt.deliver(h.laneId,h.name,b,g),g[1]===Nt.ENVELOPE_KIND.END&&nt.detach(h.laneId,h.name,b)});let A=()=>{o.delete(S),nt.detach(h.laneId,h.name,b)};S.on("close",A),S.on("error",A)})})().catch(()=>{d.destroyed||gs(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",u),{async close(){i=!0,t.off("upgrade",u),nt.clear();for(let l of o.values())l.close(1001,"lane stream host shutting down");o.clear();for(let l of s)for(let d of[l.client,l.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}E();var wt=require("crypto"),Vf=["sfu","urun-doc"],tl="runtime:lease",Jf="lane:join",Kf="urun-runtime-key-v1";function ys(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,wt.createHmac)("sha256",t).update(`${Kf}|${e}`).digest("base64url")}var zf=120,l_=1440*60;function el(t){return Buffer.from(t).toString("base64url")}function Yf(t,e,n){let r=el(JSON.stringify(t)),o=el(JSON.stringify(e)),s=(0,wt.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Hn(t,e,n=zf,r=Jf,o){let s=o?ys(e,o):e;return Xf(t,s,n,r,o)}function Xf(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return Yf({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,wt.randomUUID)()},e)}function ws(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,h=[];if(p!==void 0?(h.push(ys(n,p)),o&&h.push(ys(o,p))):(h.push(n),o&&h.push(o)),!h.some(A=>{let f=(0,wt.createHmac)("sha256",A).update(`${i}.${a}`).digest();return c.length===f.length&&(0,wt.timingSafeEqual)(c,f)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Vf.some(A=>A===_||Array.isArray(_)&&_.includes(A))))return null;let b=d.session_id??d.sub;return typeof b!="string"||b!==e?null:{sessionId:b,aud:_,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:m}}E();var Qf=3,Zf="llm",em=new Set(["paused","error"]);function qr(t,e,n){let r=t.doc(Zf),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<Qf||d(new Q(`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&&em.has(c.name)&&d(new Q(`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*_s(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 tm(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new je(`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 sl(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,_,S,b,A,f)=>{let g=S?w=>Xu(m,w):w=>Qu(m,w,{hostUrl:`ws://${b}/stream/${m}`,token:()=>Hn(m,t.tokenSecret,void 0,void 0,f)}),y=S?ms({laneId:m,roomDoc:w=>t.roomDoc(m,w),streamEndpoint:g}):ms({laneId:m,streamEndpoint:g,connector:(0,rl.createWebsocketDocConnector)({serverUrl:`ws://${b}/doc`,sessionId:m,token:()=>Hn(m,t.tokenSecret,void 0,void 0,f),WebSocketPolyfill:ol.default})}),k=S?u(m):qr(y,`lane:${m}`,{armOnFirstSync:!0}),T={session:y,responses:new Mt(y,{sessionTag:null}),gone:k,goneWatch:k,laneId:m,pool:_,inFlight:0,laneSession:y,self:S,host:b??"",mintedRelease:A??"",retireWhenIdle:!1};return n.set(m,T),k.onGone(()=>l(T)),T},u=m=>{let _=null,S=!1,b=new Set,A=g=>{if(!_){_=g;for(let y of[...b])y(g);b.clear()}},f=t.hostedSignal?.(m,g=>{if(g){S=!0;return}S&&A(new Q(`the lane ${m} 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:()=>_,onGone(g){return _?(g(_),()=>{}):(b.add(g),()=>b.delete(g))},dispose(){f?.(),b.clear()}}},l=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),nt.forgetLane(m.laneId))},d=m=>{let _=m.laneId;return typeof _=="string"&&n.get(_)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),l(m)))},p=(m,_)=>{throw t.metrics?.observeLane503Fast(_??""),s.set(m,e()),new Ee(m)},h=async(m,_)=>{let S=tm(_);o.add(S);let b=e();try{let A=await t.laneWarmWaitMsFor?.(m,_)??t.laneColdWakeDefaultMs??0,f;try{f=await t.plane.pick({pool:S,model:m,holdMs:A})}catch(O){throw O instanceof Fn?new nl.SessionAllocationError(`lane pick hold expired for ${S}: ${O.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):O}t.metrics?.observeLaneReady(m??"",f.length);let g=await t.currentReleaseOf?.(_)??null,y=new Set(f.map(O=>O.laneId));for(let O of i)y.has(O)||i.delete(O);let T=f.filter(O=>{let x=n.get(O.laneId);return x!==void 0&&g!==null&&x.mintedRelease!==""&&x.mintedRelease!==g&&(x.retireWhenIdle=!0,x.inFlight===0)?(c(x),!1):!i.has(O.laneId)}).map(O=>({laneId:O.laneId,self:O.host===t.selfAddress,host:O.host})).sort((O,x)=>O.self!==x.self?O.self?-1:1:(r.get(O.laneId)??0)-(r.get(x.laneId)??0))[0];T||p(S,m);let w=n.get(T.laneId);return w?.goneWatch?.gone()&&(l(w),w=void 0),w&&(w.pool!==S||w.self!==T.self||w.host!==T.host)&&(l(w),w=void 0),w||(w=a(T.laneId,S,T.self,T.host,g,_.sharedOrgId??void 0)),w.inFlight+=1,r.set(T.laneId,(r.get(T.laneId)??0)+1),{app:S,entry:w,identity:{kind:"catalog",model_id:_.modelId??m??"",variant:_.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-b)}};return{sessionFor(m,_){return h(m,_)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(b=>b.pool)])].sort(),_=await t.plane.status().catch(()=>[]),S=new Map(nm(_));return Promise.all(m.map(async b=>{let A=S.get(b)??{pool:b,lanes:[],lastDemandAt:null};return{pool:b,lanes:A.lanes,lastDemandAt:A.lastDemandAt,local:[...n.values()].filter(f=>f.pool===b).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:s.get(b)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function nm(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}E();var rm="urun:node-scheduler:apps:v1";function om(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function il(t){return async e=>{let n=om(e);if(n===null)return null;try{let r=await t.hget(rm,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}E();var fl=require("ws");E();var ul=ke(require("yjs"),1),an=ke(require("y-protocols/sync"),1),dt=ke(require("y-protocols/awareness"),1),me=ke(require("lib0/encoding"),1),un=ke(require("lib0/decoding"),1),ll=ke(require("lib0/map"),1),dl=ke(require("lodash.debounce"),1);E();var al=()=>{};var im=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,am=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,um=0,lm=1;var dm=process.env.GC!=="false"&&process.env.GC!=="0",cm=process.env.YPERSISTENCE,Gr=null;if(typeof cm=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var sn=new Map,Wr=0,bs=1,pm=(t,e,n)=>{let r=me.createEncoder();me.writeVarUint(r,Wr),an.writeUpdate(r,t);let o=me.toUint8Array(r);n.conns.forEach((s,i)=>jn(n,i,o))},vs=class extends ul.Doc{constructor(e){super({gc:dm}),this.name=e,this.conns=new Map,this.awareness=new dt.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=me.createEncoder();me.writeVarUint(u,bs),me.writeVarUint8Array(u,dt.encodeAwarenessUpdate(this.awareness,a));let l=me.toUint8Array(u);this.conns.forEach((d,c)=>{jn(this,c,l)})};this.awareness.on("update",n),this.on("update",pm),!1}},Ss=(t,e=!0)=>ll.setIfUndefined(sn,t,()=>{let n=new vs(t);return n.gc=e,Gr!==null&&Gr.bindState(t,n),sn.set(t,n),n}),fm=(t,e,n)=>{try{let r=me.createEncoder(),o=un.createDecoder(n);switch(un.readVarUint(o)){case Wr:me.writeVarUint(r,Wr),an.readSyncMessage(o,r,e,t),me.length(r)>1&&jn(e,t,me.toUint8Array(r));break;case bs:{dt.applyAwarenessUpdate(e.awareness,un.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},on=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),dt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Gr!==null&&(Gr.writeState(t.name,t).then(()=>{t.destroy()}),sn.delete(t.name))}e.close()},jn=(t,e,n)=>{e.readyState!==um&&e.readyState!==lm&&on(t,e);try{e.send(n,r=>{r!=null&&on(t,e)})}catch{on(t,e)}},mm=3e4,cl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Ss(n,r);o.conns.set(t,new Set),t.on("message",a=>fm(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&on(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{on(o,t),clearInterval(i)}}},mm);t.on("close",()=>{on(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=me.createEncoder();me.writeVarUint(a,Wr),an.writeSyncStep1(a,o),jn(o,t,me.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=me.createEncoder();me.writeVarUint(l,bs),me.writeVarUint8Array(l,dt.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),jn(o,t,me.toUint8Array(l))}}};var ks="/doc/",ml=30,gm=1e4,pl="llm";function hm(t){if(!t.startsWith(ks))return null;let e=t.slice(ks.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 ln(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
84
+ ${o}`)}function Su(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new Bt.WebSocketServer({noServer:!0,handleProtocols:(m,_)=>{let R=wu(new URL(_.url??"/","http://localhost").pathname);if(!R)return!1;let v=Xr(R.name);return m.has(v)?v:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,_,R)=>{r>0&&l.set(m,{at:Date.now(),label:_,reap:R})},d=m=>{let _=l.get(m);_&&(_.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[_,R]of l)m-R.at<r||(l.delete(_),console.warn(`[lane-stream] ${R.label}: lease expired (no data for ${r} ms) \u2014 terminating`),R.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,_,R,v)=>{let b={client:R,upstream:v,laneId:m,name:_};i.add(b);let p=g=>{if(i.delete(b)){l.delete(R),console.warn(`[lane-stream] ${m}/${_}: host-affinity pump torn down (${g})`);for(let y of[R,v])try{(y.readyState===Bt.default.OPEN||y.readyState===Bt.default.CONNECTING)&&y.close(1001,"lane stream pump closed")}catch{}}};if(u(R,`${m}/${_} pump`,()=>{for(let g of[R,v])try{g.terminate()}catch{}p("lease expired")}),n>0){let g=(y,k)=>{let O=!0,x=()=>{O=!0};y.on("pong",x),y.on("message",x);let P=setInterval(()=>{if(!O){console.warn(`[lane-stream] ${m}/${_}: pong timeout on ${k} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${k} dial never sends a close)`),clearInterval(P);try{y.terminate()}catch{}p(`${k} pong timeout`);return}O=!1;try{y.ping()}catch{}},n);P.unref?.();let E=()=>clearInterval(P);y.once("close",E),y.once("error",E)};g(R,"client"),g(v,"host")}R.on("message",g=>{d(R);try{v.send(g,{binary:!0})}catch(y){p(`upstream send failed: ${String(y)}`)}}),v.on("message",g=>{d(R);try{R.send(g,{binary:!0})}catch(y){p(`client send failed: ${String(y)}`)}}),R.on("close",()=>p("client socket closed")),R.on("error",()=>p("client socket error")),v.on("close",()=>p("host socket closed")),v.on("error",()=>p("host socket error"))},h=(m,_,R)=>{let v;try{v=new URL(m.url??"/","http://localhost")}catch{xs(_,400,"malformed upgrade URL");return}_.on("error",()=>_.destroy());let b=wu(v.pathname);b&&(a||_.destroyed||(async()=>{let p=v.searchParams.get("token")??"",g=null;try{g=p===""?null:await e.verifyToken(p,b.laneId,b.name)}catch{g=null}if(g===null){xs(_,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let y=await e.hostOf(b.laneId).catch(()=>null);if(y&&y!==e.selfAddress)try{let k=await e.podToPodDial(b.laneId,b.name,y);o.handleUpgrade(m,_,R,O=>{f(b.laneId,b.name,O,k)});return}catch(k){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${y} failed (${String(k)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,_,R,y=>{let k=Lm(y,()=>d(y));if(s.set(y,k),rt.attach(b.laneId,b.name,k),u(y,`${b.laneId}/${b.name}`,()=>y.terminate()),n>0){let x=!0,P=()=>{x=!0};y.on("pong",P),y.on("message",P);let E=setInterval(()=>{if(!x){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(E),y.terminate();return}x=!1;try{y.ping()}catch{}},n);E.unref?.();let C=()=>clearInterval(E);y.once("close",C),y.once("error",C)}y.on("message",x=>{d(y);let P=new Uint8Array(x);try{zr(P)}catch(E){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(E)}`);return}rt.deliver(b.laneId,b.name,k,P),P[1]===Ht.ENVELOPE_KIND.END&&rt.detach(b.laneId,b.name,k)});let O=()=>{s.delete(y),l.delete(y),rt.detach(b.laneId,b.name,k)};y.on("close",O),y.on("error",O)})})().catch(()=>{_.destroyed||xs(_,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),rt.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let _ of[m.client,m.upstream])try{_.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}I();var bt=require("crypto"),$m=["sfu","urun-doc"],Ru="runtime:lease",Mm="lane:join",Nm="urun-runtime-key-v1";function Is(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,bt.createHmac)("sha256",t).update(`${Nm}|${e}`).digest("base64url")}var Um=120;function ku(t){return Buffer.from(t).toString("base64url")}function Dm(t,e,n){let r=ku(JSON.stringify(t)),o=ku(JSON.stringify(e)),s=(0,bt.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Wn(t,e,n=Um,r=Mm,o){let s=o?Is(e,o):e;return Fm(t,s,n,r,o)}function Fm(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return Dm({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,bt.randomUUID)()},e)}function Os(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(Is(n,f)),o&&h.push(Is(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let p=(0,bt.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===p.length&&(0,bt.timingSafeEqual)(c,p)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&$m.some(b=>b===_||Array.isArray(_)&&_.includes(b))))return null;let v=d.session_id??d.sub;return typeof v!="string"||v!==e?null:{sessionId:v,aud:_,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}I();var Bm=3,Hm="llm",jm=new Set(["paused","error"]);function Qr(t,e,n){let r=t.doc(Hm),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,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Bm||d(new ee(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&jm.has(c.name)&&d(new ee(`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),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Ts(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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 qm(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new He(`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??""}`}var Gm={"prod-usw2":["us-west1"]};function Iu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,_,R,v,b,p)=>{let g=R?x=>vu(m,x):x=>bu(m,x,{hostUrl:`ws://${v}/stream/${m}`,token:()=>Wn(m,t.tokenSecret,void 0,void 0,p)}),y=R?Es({laneId:m,roomDoc:x=>t.roomDoc(m,x),streamEndpoint:g}):Es({laneId:m,streamEndpoint:g,connector:(0,xu.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:m,token:()=>Wn(m,t.tokenSecret,void 0,void 0,p),WebSocketPolyfill:Au.default})}),k=R?l(m):Qr(y,`lane:${m}`,{armOnFirstSync:!0}),O={session:y,responses:new Ft(y,{sessionTag:null}),gone:k,goneWatch:k,laneId:m,pool:_,inFlight:0,laneSession:y,self:R,host:v??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,O),k.onGone(()=>u(O)),O},l=m=>{let _=null,R=!1,v=new Set,b=g=>{if(!_){_=g;for(let y of[...v])y(g);v.clear()}},p=t.hostedSignal?.(m,g=>{if(g){R=!0;return}R&&b(new ee(`the lane ${m} 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:()=>_,onGone(g){return _?(g(_),()=>{}):(v.add(g),()=>v.delete(g))},dispose(){p?.(),v.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),rt.forgetLane(m.laneId))},d=m=>{let _=m.laneId;return typeof _=="string"&&n.get(_)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,_)=>{throw t.metrics?.observeLane503Fast(_??""),s.set(m,e()),new xe(m)},h=async(m,_)=>{let R=qm(_);o.add(R);let v=e();try{let b=await t.laneWarmWaitMsFor?.(m,_)??t.laneColdWakeDefaultMs??0,p;try{p=await t.plane.pick({pool:R,app:_.appSlug,fn:_.fnName??"",model:m,holdMs:b,..._.sharedApp?{sharedApp:!0}:{}})}catch(P){throw P instanceof Gn?new Eu.SessionAllocationError(`lane pick hold expired for ${R}: ${P.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):P}t.metrics?.observeLaneReady(m??"",p.length);let g=await t.currentReleaseOf?.(_)??null,y=new Set(p.map(P=>P.laneId));for(let P of i)y.has(P)||i.delete(P);let O=p.filter(P=>{let E=n.get(P.laneId);return E!==void 0&&g!==null&&E.mintedRelease!==""&&E.mintedRelease!==g&&(E.retireWhenIdle=!0,E.inFlight===0)?(c(E),!1):!i.has(P.laneId)}).map(P=>({laneId:P.laneId,self:P.host===t.selfAddress,host:P.host,region:P.region})).sort((P,E)=>{let C=Gm[t.seatRegion??""]??[],w=new Map(C.map((M,F)=>[M,F])),T=C.length===0?0:(P.region!==void 0?w.get(P.region):void 0)??C.length,$=C.length===0?0:(E.region!==void 0?w.get(E.region):void 0)??C.length;return T!==$?T-$:P.self!==E.self?P.self?-1:1:(r.get(P.laneId)??0)-(r.get(E.laneId)??0)})[0];O||f(R,m);let x=n.get(O.laneId);return x?.goneWatch?.gone()&&(u(x),x=void 0),x&&(x.pool!==R||x.self!==O.self||x.host!==O.host)&&(u(x),x=void 0),x||(x=a(O.laneId,R,O.self,O.host,g,_.sharedOrgId??void 0)),x.inFlight+=1,r.set(O.laneId,(r.get(O.laneId)??0)+1),{app:R,entry:x,identity:{kind:"catalog",model_id:_.modelId??m??"",variant:_.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-v)}};return{sessionFor(m,_){return h(m,_)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),_=await t.plane.status().catch(()=>[]),R=new Map(Wm(_));return Promise.all(m.map(async v=>{let b=R.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(p=>p.pool===v).map(p=>({laneId:p.laneId,inFlight:p.inFlight,self:p.self,host:p.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function Wm(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}I();var Jm="urun:node-scheduler:apps:v1";function Vm(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Ou(t){return async e=>{let n=Vm(e);if(n===null)return null;try{let r=await t.hget(Jm,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}I();var Nu=require("ws");I();var Pu=Re(require("yjs"),1),pn=Re(require("y-protocols/sync"),1),ct=Re(require("y-protocols/awareness"),1),ye=Re(require("lib0/encoding"),1),fn=Re(require("lib0/decoding"),1),Cu=Re(require("lib0/map"),1),Lu=Re(require("lodash.debounce"),1);I();var Tu=()=>{};var zm=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Ym=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Xm=0,Qm=1;var Zm=process.env.GC!=="false"&&process.env.GC!=="0",eg=process.env.YPERSISTENCE,Zr=null;if(typeof eg=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var cn=new Map,eo=0,Cs=1,tg=(t,e,n)=>{let r=ye.createEncoder();ye.writeVarUint(r,eo),pn.writeUpdate(r,t);let o=ye.toUint8Array(r);n.conns.forEach((s,i)=>Jn(n,i,o))},Ps=class extends Pu.Doc{constructor(e){super({gc:Zm}),this.name=e,this.conns=new Map,this.awareness=new ct.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 l=ye.createEncoder();ye.writeVarUint(l,Cs),ye.writeVarUint8Array(l,ct.encodeAwarenessUpdate(this.awareness,a));let u=ye.toUint8Array(l);this.conns.forEach((d,c)=>{Jn(this,c,u)})};this.awareness.on("update",n),this.on("update",tg),!1}},Ls=(t,e=!0)=>Cu.setIfUndefined(cn,t,()=>{let n=new Ps(t);return n.gc=e,Zr!==null&&Zr.bindState(t,n),cn.set(t,n),n}),ng=(t,e,n)=>{try{let r=ye.createEncoder(),o=fn.createDecoder(n);switch(fn.readVarUint(o)){case eo:ye.writeVarUint(r,eo),pn.readSyncMessage(o,r,e,t),ye.length(r)>1&&Jn(e,t,ye.toUint8Array(r));break;case Cs:{ct.applyAwarenessUpdate(e.awareness,fn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},dn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),ct.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Zr!==null&&(Zr.writeState(t.name,t).then(()=>{t.destroy()}),cn.delete(t.name))}e.close()},Jn=(t,e,n)=>{e.readyState!==Xm&&e.readyState!==Qm&&dn(t,e);try{e.send(n,r=>{r!=null&&dn(t,e)})}catch{dn(t,e)}},rg=3e4,$u=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Ls(n,r);o.conns.set(t,new Set),t.on("message",a=>ng(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&dn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{dn(o,t),clearInterval(i)}}},rg);t.on("close",()=>{dn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ye.createEncoder();ye.writeVarUint(a,eo),pn.writeSyncStep1(a,o),Jn(o,t,ye.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ye.createEncoder();ye.writeVarUint(u,Cs),ye.writeVarUint8Array(u,ct.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Jn(o,t,ye.toUint8Array(u))}}};var $s="/doc/",Uu=30,og=1e4,Mu="llm";function sg(t){if(!t.startsWith($s))return null;let e=t.slice($s.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 mn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
81
85
  `;t.end(`HTTP/1.1 ${e} ${r}\r
82
86
  Connection: close\r
83
87
  Content-Type: text/plain; charset=utf-8\r
84
88
  Content-Length: ${Buffer.byteLength(o)}\r
85
89
  \r
86
- ${o}`)}function gl(t,e){let n=new fl.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=g=>o.get(`${g}/${pl}`)??0,a=g=>s.get(g)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=new Map,h=new Map,m=4096,_=!1,S=(g,y,k)=>{let T=i(g)>0,w=a(g),O=w>0,x=`${g}/${y}`,P=o.get(x)??0;k>0?o.set(x,k):o.delete(x);let I=w+k-P;I>0?s.set(g,I):s.delete(g);let M=i(g)>0,G=I>0;if(T!==M){M?b(g):A(g);for(let V of u.get(g)??[])V(M)}O&&!G&&queueMicrotask(()=>{let V=`${g}/`;for(let[Z,Y]of[...sn.entries()])!Z.startsWith(V)||Y.conns.size>0||(sn.delete(Z),Y.destroy())})},b=g=>{if(!e.hostRegistry||l.has(g))return;let y=()=>{e.hostRegistry?.setHost(g,e.selfAddress).catch(()=>{})};y();let k=setInterval(y,gm);k.unref?.(),l.set(g,k)},A=g=>{let y=l.get(g);y&&(clearInterval(y),l.delete(g)),e.hostRegistry&&e.hostRegistry.delHost(g,e.selfAddress).catch(()=>{})},f=(g,y,k)=>{let T;try{T=new URL(g.url??"/","http://localhost")}catch{ln(y,400,"malformed upgrade URL");return}y.on("error",()=>y.destroy()),y.on("close",()=>c.delete(y));let w=hm(T.pathname);if(!w){if(T.pathname.startsWith(ks)){ln(y,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(y);return}d.add(y);let O=!1;(async()=>{if(h.has(w.laneId)){ln(y,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let x=T.searchParams.get("token")??"",P=null;try{P=x===""?null:await e.verifyToken(x,w.laneId,w.docName)}catch{P=null}if(P===null){ln(y,401,"invalid or missing lane doc token");return}let I=P;if(I.tenant!==void 0&&e.laneTenantOf){let M=null;try{M=await e.laneTenantOf(w.laneId)}catch{M=null}if(M==null||M==="")e.onLaneTenantMissing?.();else if(I.tenant!==M){ln(y,403,"lane doc token org does not match the lane record");return}}_||y.destroyed||(O=!0,n.handleUpgrade(g,y,k,M=>{d.delete(y),r.add(M),M.on("close",()=>r.delete(M));let G=p.get(w.laneId);G||(G=new Set,p.set(w.laneId,G)),G.add(M),M.on("close",()=>{G.delete(M),G.size===0&&p.delete(w.laneId)});let V=I.scope===tl||I.scope===void 0&&typeof I.app=="string"&&typeof I.fn=="string"&&I.aud==="sfu";if(V){let Y=`${w.laneId}/${w.docName}`,Te=(o.get(Y)??0)+1;S(w.laneId,w.docName,Te),Te>1&&w.docName===pl&&e.hostRegistry?.setHost(w.laneId,e.selfAddress).catch(()=>{})}M.on("close",()=>{if(!V)return;let Y=`${w.laneId}/${w.docName}`;S(w.laneId,w.docName,Math.max(0,(o.get(Y)??1)-1))}),cl(M,g,{docName:`${w.laneId}/${w.docName}`,gc:!0})}))})().catch(()=>{!O&&!y.destroyed&&ln(y,500,"lane doc upgrade failed")}).finally(()=>d.delete(y))};return t.on("upgrade",f),{async close(){_=!0,t.off("upgrade",f);for(let y of[...l.keys()])A(y);await new Promise(y=>{if(r.size===0&&d.size===0){y();return}let k=r.size+d.size,T=()=>{k-=1,k<=0&&y()};for(let w of r)w.once("close",T);for(let w of d)w.once("close",T);for(let w of r)w.close(1001,"lane doc host shutting down");for(let w of d)w.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(g,y){return Ss(`${g}/${y}`,!0)},isHosted(g){return i(g)>0},onHostedChange(g,y){let k=u.get(g);return k||(k=new Set,u.set(g,k)),k.add(y),y(i(g)>0),()=>{k.delete(y)}},closeLane(g){if(h.set(g,!0),h.size>m){let y=h.keys().next().value;y!==void 0&&h.delete(y)}A(g);for(let y of p.get(g)??[])y.close(1001,`lane ${g} retired \u2014 the app's release moved`)}}}var Hl=ke(require("ws"),1);E();var ym="urun:catalog:v1";function hl(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(ym),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)
87
- `)}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 jl=ke(require("ioredis"),1);E();var Kr=require("@urun-sh/core"),zr=require("crypto"),yl="urun-session-gateway",wm="machine",_m=3e5;function vm(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ye=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Bn=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},Xe=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Yr(t){let e=(t??"").trim();if(e==="")throw new ye("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 ye("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var bm=60,Sm=6e4,km=4096;function Rm(t){return t===401||t===403}var Vr=class{constructor(e){this.opts=e;this.mint=e.mint??Kr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ye("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Sm)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:bm});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof Kr.ClientTokenError&&Rm(s.status)?(this.cache.delete(e),new ye("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Xe("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}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new Xe("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>=km){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function wl(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var Jr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<_m)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new Xe("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new Xe("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new Xe("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof Xe?i:new Xe("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ye("malformed machine token");let s,i;try{s=wl(n),i=wl(r)}catch{throw new ye("malformed machine token")}if(s.alg!=="RS256")throw new ye(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",u=typeof i.iss=="string"?i.iss:"";if(u===""||!this.opts.issuers.includes(u))throw new ye(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(i.aud!==yl)throw new ye(`machine token audience must be ${yl} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==wm)throw new ye(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let l=typeof i.org_id=="string"?i.org_id:"";if(l==="")throw new ye("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new ye("machine token is expired \u2014 re-mint and retry");let c=b=>b.kty==="RSA"&&b.n!==void 0&&b.e!==void 0,p=await this.jwksKeys(!1),h=a===""?void 0:p.find(b=>b.kid===a&&c(b));if(h===void 0&&(p=await this.jwksKeys(!0),h=a===""?void 0:p.find(b=>b.kid===a&&c(b))),h===void 0)throw new ye(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let m=Buffer.from(`${n}.${r}`,"ascii"),_=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),S=!1;try{let b=(0,zr.createPublicKey)({key:h,format:"jwk"});S=(0,zr.verify)("RSA-SHA256",m,b,_)}catch{S=!1}if(!S)throw new ye("machine token signature failed verification");return{apiKey:e,orgId:l,credential:"machine"}}};function Rs(t,e,n){return n!==null&&vm(t)?n.verify(t):e.resolve(t)}E();var qn=require("crypto");E();var Re=require("@urun-sh/core");E();async function _l(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()}E();var vl=require("@urun-sh/core"),Es=2;function Em(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function xm(t){let e=t?.type;return e==="response.completed"||e==="error"}function bl(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 h of p){if(xm(h)&&(d=!0),Em(h)){if(i>1)continue}else c=!0;yield h}}catch(p){if(p instanceof vl.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 Os=require("crypto");E();var Sl=require("@urun-sh/core"),Am="audio";function kl(t){let e=t.streamEndpoint(Am);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,Sl.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}E();var Rl=require("@urun-sh/core"),Om="rt-video-in";function El(t){let e=t.streamEndpoint(Om);return{sendInputFrame:async n=>{e.send((0,Rl.encodeStreamEnvelope)(n))}}}var Tm=0,Pm=4,Cm=4;function xl(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):Tm;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,Pm));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Cm),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function xs(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 Al(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=_=>({session:_,responses:new Mt(_),gone:qr(_,n)});if(i.lane==="jwt"){let _=(0,Re.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(xs(_,e.appSlug,a,l))}if(i.lane==="machine"){let{machineToken:_,gatewayUrl:S}=i,b=(typeof t.subject=="function"?t.subject():t.subject)??(0,Os.randomUUID)(),A=(0,Re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Re.createClientToken)(_,{baseUrl:S,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:b,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(xs(A,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Os.randomUUID)(),m=(0,Re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Re.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(xs(m,e.appSlug,a,l))}function Ol(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 Is(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 Lm=new Set(["error","paused"]);function Ts(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Al(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 Kn({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"?()=>gi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>_l(n):null),listPrices:n?()=>Zs(n):null,shared:e.lane==="api-key"?()=>Ks({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return Js(i)}:null,sessionKey:Ol});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ft({appSlug:t.defaultApp}))),s}function Il(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}
88
- `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let h=new dr({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let _=Al(t,d,c,{concurrencyKey:m.concurrencyKey});return _.gone.onGone(()=>h.markSessionDead(_)),await Qr(_.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async m=>{m.gone.dispose(),await m.session.end()},onDetach:(m,_)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${_}`),terminalOpenFailure:m=>m instanceof Re.SessionFailedError&&Is(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},l=async(d,c)=>{let p=s.get(c);if(p)try{let h=await e.poolTuningFor(d);u(d,c).retune({min:h?.min??p.env.min,max:h?.max??p.env.max,inFlightCap:h?.in_flight_cap??p.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,ft(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=ft(c),h=u(c,p);await l(c,p);let m=await h.acquire({timeoutMs:h.requestWaitMs}),_=i.get(m.entry)??[];return _.push(m),i.set(m.entry,_),{app:p,entry:m.entry,identity:Jn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,ft(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 Mm(t){return(0,Re.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Re.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Re.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Re.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Qr(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:Mm(t.phase),signal:e})}async function As(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Xr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Ps(t,e=Zi,n,r,o=Bo,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",h=f=>{let g=wn(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new Q(`the lane behind this handle (${g.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:g.key,entry:y}},m=async f=>h(f)?.entry??(await t.sessionForHandle(f)).entry,_=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await Qr(f.session,y.gone.signal),y.gone.signal.aborted)throw Xr(y.gone.signal);d.get(f)===y&&d.delete(f);let k=await Qi(f.session,await e());return Object.assign(k,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},S=f=>{let g=l.get(f);return g||(g=(async()=>{let y=await _(f);return{appendInputAudio:k=>y.appendInputAudio(k),onOutputAudio:k=>y.onOutputAudio(k),sessionId:c(f)}})(),l.set(f,g),g.catch(()=>{l.get(f)===g&&l.delete(f)})),g},b=async(f,g,y)=>{if(y?.aborted){let w=d.get(f);throw(i.get(f)===void 0||w!==void 0&&w.waiting===0)&&await As(f.session),Xr(y)}let k=g(f),T=d.get(f);return T!==void 0&&T.waiting++,y===void 0?k:new Promise((w,O)=>{let x=()=>{T!==void 0&&--T.waiting===0&&d.get(f)===T&&(T.gone.abort(),d.delete(f),i.delete(f),l.delete(f),As(f.session).catch(()=>{})),O(Xr(y))};y.addEventListener("abort",x,{once:!0});let P=()=>y.removeEventListener("abort",x);k.then(I=>{P(),w(I)},I=>{P(),O(I)})})},A=async(f,g,y)=>{try{return await y}catch(k){throw(k instanceof Q||k instanceof Re.SessionFailedError&&Is(k))&&(t.evict(f,g),k instanceof Re.SessionFailedError&&n?.(f,k.kind==="never-live"?"never-live":"create-failed")),k}};return{createResponse:bl({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{Is(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await Qr(f.session);let y=Ta(_s(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let k=f;return(async function*(){try{yield*y}catch(w){throw Pa(w)&&(s&&s.owns(k)?s.evict(k):r&&(w instanceof Q?r.markSessionDead(k):r.evict(k))),w}finally{s&&s.owns(k)?s.release(k):r?.end(k)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),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,g)=>{let{app:y,entry:k}=await t.sessionFor(f);return await A(y,k,b(k,_,g))},openAudioOn:async(f,g,y)=>{let k=h(f);if(k){let O=k.entry.session;return kl(O)}let{app:T,entry:w}=await t.sessionForHandle(f);return await A(T,w,b(w,S,g))},openTurnsOn:async function*(f,g){if(g?.aborted)throw Xr(g);let y=await m(f);yield*ci(y.session,g)},openVideoOn:async f=>{let g=h(f);if(g)return El(g.entry.session);let{entry:y}=await t.sessionForHandle(f),k=a.get(y);return k||(k=Co(y.session),a.set(y,k)),k},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=Co(g.session),a.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=u.get(g);return y||(y=ta(g.session),u.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),k=c(y.entry);if(k===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return yn(p,k)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:k}=await t.dedicatedSessionFor(f);return yn(y,Ol(k))},releaseSessionHandle:f=>{let g=wn(f);if(!g)return;if(g.app.startsWith(jt)){(async()=>{let k=null;try{k=(await t.sessionForHandle(f)).entry}catch{return}await As(k.session).catch(()=>{}),await t.evict(g.app,k)})();return}if(!s||g.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let k=await m(f);await Qr(k.session);let T=y!==void 0&&h(f)?new Mt({...k.session,consumerId:y},{sessionTag:y}):k.responses;return _s(await T.responses.create(g),k.gone)},onSessionEnd:async(f,g)=>{let y=h(f);if(y)return y.entry.gone.onGone(O=>g({timeLeftMs:null,reason:O.message}));let{entry:k}=await t.sessionForHandle(f),T=k.session;if(typeof T.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let w=!1;return T.onPhase(O=>{if(w||!Lm.has(O.name))return;w=!0;let x=T.endsAt??null;g({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}E();var Pl=require("http");var $m="/pooler/v1/inference",dn=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},Nm=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)},Um=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)}},Cl=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)}),Dm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Cl(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 dn(t.status,e,n,t.retryAfterSeconds)};async function Fm(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${$m}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Nm(e),firstMessage:Um(e)}});return new Promise((a,u)=>{let l=(0,Pl.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 dn(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var Tl=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*Hm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
89
-
90
- `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Tl(s);i!==null&&(yield i)}let n=Tl(e);n!==null&&(yield n)}async function Ll(t,e,n,r){let o=Nr(e,n,r),s=o.model??"";if(s==="")throw new dn(400,"missing_model","the pooler submit requires a model");let i=await Fm(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Dm(i);let a=e.stream===!0?Dr(n,Hm(i)):await jm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function jm(t,e){let n=await Cl(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 dn(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Dr(e,(async function*(){yield o})())}var Bm=512;function Zr(t){return`urun-inference-proxy-${(0,qn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var eo=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,u)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,u);let l=`px_${(0,qn.randomUUID)()}`;return Ll(s,a,l,l)}})}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,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:To,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{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:xl(process.env,process.env.HOSTNAME)??void 0},r=Ts(n),o=n.decisionPool?Il(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Ps(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),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>=Bm;){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("; ")}`)}},Ml=512,qm=1024,to=class extends Error{constructor(){super(`conversation capacity reached (${Ml} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Gm(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Ht))return{concurrencyKey:e};if(n.startsWith(Ht)||n.startsWith(jt))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Ht)||n.startsWith(jt)||t.set(n,r)}}}function Wm(t,e,n,r,o){let s=Ts({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:To,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:{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",...Gm(r,o)});return{clients:Ps(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var no=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${Zr(e.apiKey)}:live`:`${Zr(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Wm(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.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>=Ml;){let e=this.byCaller.keys().next();if(e.done)throw new to;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 to;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,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,qn.randomUUID)(),n)),r),i={createResponse:(a,u)=>s().backhaul.clients.createResponse(a,u),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let u=s().backhaul.clients.servingAppSlug;if(u===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 u(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let u=s().backhaul.clients.dedicatedSessionHandle;return u===void 0?s().backhaul.clients.sessionHandle(a):u(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,u,l)=>s().backhaul.clients.createResponseOn(a,u,l),onSessionEnd:(a,u)=>s().backhaul.clients.onSessionEnd(a,u)};return i.openAudio=async(a,u)=>{let l=s().backhaul.clients.openAudio;if(l===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return l(a,u)},i.openVideo=async a=>{let u=s().backhaul.clients.openVideo;if(u===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return u(a)},i.openVideoOut=async a=>{let u=s().backhaul.clients.openVideoOut;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return u(a)},i.supportsAudio=async a=>{let u=s().backhaul.clients.supportsAudio;if(u===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return u(a)},i.supportsSpeech=async a=>{let u=s().backhaul.clients.supportsSpeech;if(u===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return u(a)},i.speechVoices=async a=>{let u=s().backhaul.clients.speechVoices;if(u===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 u(a)},i.speechSessionHandle=async a=>{let u=s().backhaul.clients.speechSessionHandle;if(u===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 u(a)},i.openAudioOn=async(a,u,l)=>{let d=s().backhaul.clients.openAudioOn;if(d===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 d(a,u,l)},i.openVideoOn=async(a,u)=>{let l=s().backhaul.clients.openVideoOn;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return l(a,u)},i.openTurnsOn=(a,u)=>{let l=s().backhaul.clients.openTurnsOn;if(l===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 l(a,u)},i.evictSpeechSession=async a=>{let u=s().backhaul.clients.evictSpeechSession;if(u===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 u(a)},i.supportsTranscription=async a=>{let u=s().backhaul.clients.supportsTranscription;if(u===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return u(a)},i.transcriptStreamFor=async a=>{let u=s().backhaul.clients.transcriptStreamFor;if(u===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 u(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===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 a()},{clients:i,bindResumeHandle:a=>{let u=r;if(u===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=qm;){let l=this.byHandle.keys().next();if(l.done)break;this.byHandle.delete(l.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:u.id})},clientsForResume:async a=>{let u=this.byHandle.get(a),l=u===void 0?void 0:this.byCaller.get(u.apiKey),d=u===void 0||l===void 0?void 0:l.get(u.conversationId);if(u===void 0||d===void 0||u.apiKey!==e.apiKey)throw new Q("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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.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("; ")}`)}};E();var ro="/inference-usage",$l=25e3;var Vm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Nl(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Vm.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 oo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ro}`,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($l)})}catch(i){throw new ge(`the uRun usage surface (POST ${ro}) could not be reached within ${$l}ms: ${Nl(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ye("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 ge(`the uRun usage surface (POST ${ro}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new ge(`the uRun usage surface (POST ${ro}) answered HTTP ${o.status} with a body that is not JSON: ${Nl(i)}`)}return Bi(s,this.opts.onRejectedRow)}};E();var Jm="/inference-ledger",Km=1e4,so=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Ms=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Ie=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},$s=class extends ye{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ns=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},zm=[["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",Cs],["output_minutes",Cs],["cost_nano_usd",Cs],["price_version",t=>t===null||typeof t=="string"]];function Ym(t){for(let[e,n]of zm){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Xm(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"}:Ym(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Cs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Ls(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Qm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ul(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 Zm(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&&Ul(t.started_at,n.started_at)&&Ul(t.completed_at,n.completed_at)&&Ls(t.prompt_tokens,n.prompt_tokens)&&Ls(t.completion_tokens,n.completion_tokens)&&Ls(t.output_units,n.output_units)&&Qm(t.output_minutes,n.output_minutes)}function eg(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(`
91
- `)}async function tg(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(eg(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function ng(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ie(`${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 Ie(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Ie(`${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 Ie(`${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 Ie(`${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 Ie(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Ie(`${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 Ie(`${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 Ie(`${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 io=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Jm}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await tg(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new Ie(`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(Km)})}catch(l){throw new Ie(`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=Xm(l);throw d.status==="found"&&Zm(n,d.row)?new Ms(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 so(`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 so(`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 $s("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 Ns(`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 Ie(`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 Ie(`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 Ie(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=ng(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new Ie(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var rg=5e3,og=1e3,sg=1500,ig=3e3,ag="/api/client-tokens";function ao(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Dl(t,e,n,r){ao(t,e,{error:{message:n,type:r}})}async function ug(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ag}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(ig)});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 Bl(t){let e=t.resolver??new Vr({gatewayUrl:t.baseUrl}),n=t.machine?new Jr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new rr(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{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 w=new jl.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),O=hl({redis:w});return{registry:sl({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:ju({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(P,I)=>o?.onHostedChange(P,I)??(()=>()=>{}),roomDoc:(P,I)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(P,I)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(P,I)=>O.rows().then(M=>{let G=So(M,I);return G?.warm_wait_s!==void 0?G.warm_wait_s*1e3:void 0}),currentReleaseOf:il(w),closeLane:P=>o?.closeLane(P)}),catalog:O,redis:w}})(),a=t.registry??new eo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>ug(t.baseUrl)),l=async()=>{let w=null;for(let P of a.decisionPools()){w=P;break}if(!w)return null;let O=w.stats();if(O.some(P=>P.draining))return{ok:!1,detail:"decision pool draining"};if(O.every(P=>P.attached===0&&P.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let x=await w.pingReady(sg);return{ok:x,detail:x?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new oo({apiUrl:t.apiUrl}),c=t.ledgerClient??new io({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),h=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&h&&(async()=>{try{await a.decisionWarmerFor({orgId:p,apiKey:h})?.warmFor(Mr)}catch(w){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(w instanceof Error?w.message:w)}
92
- `)}})();let m=async w=>Rs(Yr(w.headers.authorization),e,n),_=async w=>{let O=await m(w);if(O.billingAudience==="platform"&&O.creditsAdmissionOk===!1){let x=O.creditsRefusalReason;throw new Bn(x==="spend_cap_reached"||x==="insufficient_credits"?x:void 0)}return O},S=w=>w instanceof ye?{status:w.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:w instanceof Bn?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...w.code!==void 0?{code:w.code}:{}}:w instanceof Xe?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:w.detail}:null,b=Tu({clients:async w=>a.clientsFor(await _(w)),usage:{authorize:w=>Yr(w.headers.authorization),lookup:(w,O)=>d.lookup(w,O)},statusOf:S,...t.requestLog?{requestLog:t.requestLog}:{},observe:w=>r.observe(w),ledger:{write:(w,O)=>c.write(Yr(w.headers.authorization),O),observe:w=>r.observeLedger(w),...t.ledgerLog?{report:t.ledgerLog}:{}}}),A=null,f=null,g=(0,Fl.createServer)((w,O)=>{let x=new URL(w.url??"/","http://localhost");(async()=>{if(w.method==="GET"&&x.pathname==="/healthz"){ao(O,200,{ok:!0});return}if(w.method==="GET"&&x.pathname==="/readyz"){let M=Date.now();if((!A||M-A.at>=rg)&&(A={at:M,...await u()}),!f||M-f.at>=og){let Z=await l();f=Z===null?{at:M,ok:!0,detail:null}:{at:M,ok:Z.ok,detail:Z.detail}}let G=(A?.ready??!1)&&f.ok,V=f.detail===null?A?.detail??"control plane not yet probed":`${A?.detail??"control plane not yet probed"}; ${f.detail}`;ao(O,G?200:503,{ok:G,control_plane:V});return}if(w.method==="GET"&&x.pathname==="/lanez"){ao(O,200,{pools:i?await i.registry.status():null});return}let P=x.pathname==="/v1"||x.pathname.startsWith("/v1/"),I=x.pathname.startsWith("/partners/");if(!P&&!I){Dl(O,404,`no route for ${w.method} ${x.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}b(w,O)})().catch(P=>{if(!O.headersSent){Dl(O,500,String(P instanceof Error?P.message:P),"proxy_error");return}O.end()})}),y=t.conversations??new no({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),k=[No(g,{authenticate:async w=>{let O=await Rs(w,e,n),x=y.connectionFor(O);return{clients:x.clients,scope:Zr(O.apiKey),onBindResumeHandle:x.bindResumeHandle,clientsForResume:x.clientsForResume,release:x.release}}}),Jo(g,{clients:async w=>a.clientsFor(await _(w)),statusOf:S}).close,vr(g,{resolver:{resolve:async(w,O)=>{let x=await _(w),P=y.connectionFor(x,$u(w)),I;try{I=await Nu(ps(P.clients,t.realtimeCompanions),Lu(w),O,Mu(w))}catch(G){throw P.release().catch(()=>{}),G}let M=I.release;return{...I,release:async()=>{await M?.(),await P.release()}}}}})];if(t.lane&&i){let w=t.lane,O=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=gl(g,{verifyToken:(P,I)=>ws(P,I,w.tokenSecret,void 0,O),selfAddress:w.selfAddress,laneTenantOf:P=>i.redis.get(`lane_tenant:${P}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:O,hostRegistry:{setHost:(P,I)=>i.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:${P}`,I,String(ml)),delHost:P=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${P}`,w.selfAddress)}}),s=Zu(g,{verifyToken:(P,I)=>ws(P,I,w.tokenSecret,void 0,O),selfAddress:w.selfAddress,hostOf:async P=>{let I=await i.redis.get(`lane_hosts:${P}`);return I&&I.trim()!==""?I.trim():null},podToPodDial:(P,I,M)=>new Promise((G,V)=>{(async()=>{let Z=await i.redis.get(`lane_tenant:${P}`),Y=Hn(P,w.tokenSecret,void 0,void 0,Z||void 0),Te=`ws://${M}/stream/${encodeURIComponent(P)}/${encodeURIComponent(I)}?token=${encodeURIComponent(Y)}`,oe=new Hl.default(Te,Br(I));oe.once("open",()=>G(oe)),oe.once("error",V)})().catch(V)})});let x=i;k.push(async()=>{await o.close(),await s.close(),await x.registry.close(),x.redis.quit().catch(()=>{})})}g.on("upgrade",(w,O)=>{let x=new URL(w.url??"/","http://localhost");x.pathname===ur||x.pathname===Wo||x.pathname===Ln||o!==null&&x.pathname.startsWith("/doc/")||s!==null&&x.pathname.startsWith("/stream/")||O.destroyed||(O.write(`HTTP/1.1 404 Not Found\r
90
+ ${o}`)}function Du(t,e){let n=new Nu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=g=>o.get(`${g}/${Mu}`)??0,a=g=>s.get(g)??0,l=new Map,u=new Map,d=new Set,c=new Set,f=new Map,h=new Map,m=4096,_=!1,R=(g,y,k)=>{let O=i(g)>0,x=a(g),P=x>0,E=`${g}/${y}`,C=o.get(E)??0;k>0?o.set(E,k):o.delete(E);let w=x+k-C;w>0?s.set(g,w):s.delete(g);let T=i(g)>0,$=w>0;if(O!==T){T?v(g):b(g);for(let M of l.get(g)??[])M(T)}P&&!$&&queueMicrotask(()=>{let M=`${g}/`;for(let[F,G]of[...cn.entries()])!F.startsWith(M)||G.conns.size>0||(cn.delete(F),G.destroy())})},v=g=>{if(!e.hostRegistry||u.has(g))return;let y=()=>{e.hostRegistry?.setHost(g,e.selfAddress).catch(()=>{})};y();let k=setInterval(y,og);k.unref?.(),u.set(g,k)},b=g=>{let y=u.get(g);y&&(clearInterval(y),u.delete(g)),e.hostRegistry&&e.hostRegistry.delHost(g,e.selfAddress).catch(()=>{})},p=(g,y,k)=>{let O;try{O=new URL(g.url??"/","http://localhost")}catch{mn(y,400,"malformed upgrade URL");return}y.on("error",()=>y.destroy()),y.on("close",()=>c.delete(y));let x=sg(O.pathname);if(!x){if(O.pathname.startsWith($s)){mn(y,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(y);return}d.add(y);let P=!1;(async()=>{if(h.has(x.laneId)){mn(y,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let E=O.searchParams.get("token")??"",C=null;try{C=E===""?null:await e.verifyToken(E,x.laneId,x.docName)}catch{C=null}if(C===null){mn(y,401,"invalid or missing lane doc token");return}let w=C;if(w.tenant!==void 0&&e.laneTenantOf){let T=null;try{T=await e.laneTenantOf(x.laneId)}catch{T=null}if(T==null||T==="")e.onLaneTenantMissing?.();else if(w.tenant!==T){mn(y,403,"lane doc token org does not match the lane record");return}}_||y.destroyed||(P=!0,n.handleUpgrade(g,y,k,T=>{d.delete(y),r.add(T),T.on("close",()=>r.delete(T));let $=f.get(x.laneId);$||($=new Set,f.set(x.laneId,$)),$.add(T),T.on("close",()=>{$.delete(T),$.size===0&&f.delete(x.laneId)});let M=w.scope===Ru||w.scope===void 0&&typeof w.app=="string"&&typeof w.fn=="string"&&w.aud==="sfu";if(M){let G=`${x.laneId}/${x.docName}`,se=(o.get(G)??0)+1;R(x.laneId,x.docName,se),se>1&&x.docName===Mu&&e.hostRegistry?.setHost(x.laneId,e.selfAddress).catch(()=>{})}T.on("close",()=>{if(!M)return;let G=`${x.laneId}/${x.docName}`;R(x.laneId,x.docName,Math.max(0,(o.get(G)??1)-1))}),$u(T,g,{docName:`${x.laneId}/${x.docName}`,gc:!0})}))})().catch(()=>{!P&&!y.destroyed&&mn(y,500,"lane doc upgrade failed")}).finally(()=>d.delete(y))};return t.on("upgrade",p),{async close(){_=!0,t.off("upgrade",p);for(let y of[...u.keys()])b(y);await new Promise(y=>{if(r.size===0&&d.size===0){y();return}let k=r.size+d.size,O=()=>{k-=1,k<=0&&y()};for(let x of r)x.once("close",O);for(let x of d)x.once("close",O);for(let x of r)x.close(1001,"lane doc host shutting down");for(let x of d)x.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(g,y){return Ls(`${g}/${y}`,!0)},isHosted(g){return i(g)>0},onHostedChange(g,y){let k=l.get(g);return k||(k=new Set,l.set(g,k)),k.add(y),y(i(g)>0),()=>{k.delete(y)}},closeLane(g){if(h.set(g,!0),h.size>m){let y=h.keys().next().value;y!==void 0&&h.delete(y)}b(g);for(let y of f.get(g)??[])y.close(1001,`lane ${g} retired \u2014 the app's release moved`)}}}var ad=Re(require("ws"),1);I();var ig="urun:catalog:v1";function Fu(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(ig),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
91
+ `)}return r=u,o=n(),u},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 ld=Re(require("ioredis"),1);I();var Kn=require("@urun-sh/core"),oo=require("crypto"),Bu="urun-session-gateway",ag="machine",lg=3e5;function ju(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ie=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},gn=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},pt=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function so(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 ug=60,dg=6e4,cg=4096;function pg(t){return t===401||t===403}var zn=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.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<dg)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:ug});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Kn.ClientTokenError&&i.status===402?(this.cache.delete(e),new gn(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Kn.ClientTokenError&&pg(i.status)?(this.cache.delete(e),new ie(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new pt(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new pt(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=cg){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function Vn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Hu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var to=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof pt?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<lg)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Hu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Hu(s))),o}};function qu(t,e,n){try{let r=(0,oo.createPublicKey)({key:n,format:"jwk"});return(0,oo.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var no=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new to(e.fetchImpl??fetch,e.now??Date.now,n=>new pt("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ie("malformed machine token");let s,i;try{s=Vn(n),i=Vn(r)}catch{throw new ie("malformed machine token")}if(s.alg!=="RS256")throw new ie(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ie(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Bu)throw new ie(`machine token audience must be ${Bu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==ag)throw new ie(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ie("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ie("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new ie(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!qu(f,h,c))throw new ie("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ie("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},fg="https://api.workos.com/sso/jwks/";function mg(t){return`${fg}${t.slice(t.lastIndexOf("/")+1)}`}var Ms=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new to(e.fetchImpl??fetch,this.now,n=>new pt("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!ju(e))return!1;try{let n=Vn(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ie("malformed user token");let s,i;try{s=Vn(n),i=Vn(r)}catch{throw new ie("malformed user token")}if(s.alg!=="RS256")throw new ie(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ie(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ie("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ie("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(mg(l),a);if(c===void 0)throw new ie(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!qu(f,h,c))throw new ie("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ie("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},ro=class{verifier;bindings;constructor(e){this.verifier=new Ms({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new zn({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new ie("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Ns(t,e,n,r){if(ju(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}I();var Yn=require("crypto");I();var Ee=require("@urun-sh/core");I();async function Gu(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()}I();var Wu=require("@urun-sh/core"),Us=2;function gg(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function hg(t){let e=t?.type;return e==="response.completed"||e==="error"}function Ju(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Us;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(hg(h)&&(d=!0),gg(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof Wu.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Us&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Us&&!c){await t.evict(a,l);continue}return}})()}}var Bs=require("crypto");I();var Ds=require("@urun-sh/core"),yg="audio";function Vu(t){let e=t.streamEndpoint(yg);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,Ds.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,Ds.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}I();var Ku=require("@urun-sh/core"),wg="rt-video-in";function zu(t){let e=t.streamEndpoint(wg);return{sendInputFrame:async n=>{e.send((0,Ku.encodeStreamEnvelope)(n))}}}var vg=0,bg=4,Sg=4;function Xu(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):vg;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,bg));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Sg),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Fs(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 Qu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u=r||l||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...l,...r}:void 0,d=_=>({session:_,responses:new Ft(_),gone:Qr(_,n)});if(i.lane==="jwt"){let _=(0,Ee.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Fs(_,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let _=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:R}=i,v=(typeof t.subject=="function"?t.subject():t.subject)??(0,Bs.randomUUID)(),b=(0,Ee.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ee.createClientToken)(_,{baseUrl:R,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:v,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Fs(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Bs.randomUUID)(),m=(0,Ee.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ee.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Fs(m,e.appSlug,a,u))}function Zu(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 Hs(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 kg=new Set(["error","paused"]);function js(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=Qu(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new er({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),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"?()=>Ii({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Gu(n):null),listPrices:n?()=>pi(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return ii(i)}:e.lane==="api-key"?()=>ai({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Zu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},gt({appSlug:t.defaultApp}))),s}function ed(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}
92
+ `)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new wr({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let _=Qu(t,d,c,{concurrencyKey:m.concurrencyKey});return _.gone.onGone(()=>h.markSessionDead(_)),await ao(_.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,_)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${_}`),terminalOpenFailure:m=>m instanceof Ee.SessionFailedError&&Hs(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,gt(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=gt(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),_=i.get(m.entry)??[];return _.push(m),i.set(m.entry,_),{app:f,entry:m.entry,identity:Sn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,gt(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 Rg(t){return(0,Ee.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ee.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ee.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ee.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function ao(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:Rg(t.phase),signal:e})}async function Eg(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()}async function Yu(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function io(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function qs(t,e=ca,n,r,o=Xo,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},f="lane",h=p=>{let g=Wt(p);if(!s||!g||g.app!==f)return null;let y=s.entryFor(g.key);if(!y)throw new ee(`the lane behind this handle (${g.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:g.key,entry:y}},m=async p=>h(p)?.entry??(await t.sessionForHandle(p)).entry,_=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};d.set(p,y),g=(async()=>{if(await ao(p.session,y.gone.signal),y.gone.signal.aborted)throw io(y.gone.signal);d.get(p)===y&&d.delete(p);let k=await da(p.session,await e());return Object.assign(k,{sessionId:p.session.id})})(),i.set(p,g),g.then(k=>{i.get(p)===g&&(p.audioDispose=()=>k.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{d.get(p)===y&&d.delete(p)},()=>{d.get(p)===y&&d.delete(p)})}return g},R=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await _(p);return{appendInputAudio:(k,O)=>y.appendInputAudio(k,O),onOutputAudio:k=>y.onOutputAudio(k),sessionId:c(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},v=async(p,g,y,k=!1)=>{let O=()=>k?Yu(p.session):Eg(p.session);if(y?.aborted){let E=d.get(p);throw(i.get(p)===void 0||E!==void 0&&E.waiting===0)&&await O().catch(()=>{}),io(y)}let x=g(p),P=d.get(p);return P!==void 0&&P.waiting++,y===void 0?x:new Promise((E,C)=>{let w=()=>{P!==void 0&&--P.waiting===0&&d.get(p)===P&&(P.gone.abort(),d.delete(p),i.delete(p),u.delete(p),O().catch(()=>{})),C(io(y))};y.addEventListener("abort",w,{once:!0});let T=()=>y.removeEventListener("abort",w);x.then($=>{T(),E($)},$=>{T(),C($)})})},b=async(p,g,y)=>{try{return await y}catch(k){throw(k instanceof ee||k instanceof Ee.SessionFailedError&&Hs(k))&&(t.evict(p,g),k instanceof Ee.SessionFailedError&&n?.(p,k.kind==="never-live"?"never-live":"create-failed")),k}};return{createResponse:Ju({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp)try{let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Mt)return r?r.sessionFor(p):t.sessionFor(p);if(y instanceof Qe)return console.error(`[pooler-fallback] pooler channel failed for ${p} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(p):t.sessionFor(p);throw y}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>c(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{Hs(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await ao(p.session);let y=ja(Ts(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let k=p;return(async function*(){try{yield*y}catch(x){throw qa(x)&&(s&&s.owns(k)?s.evict(k):r&&(x instanceof ee?r.markSessionDead(k):r.evict(k))),x}finally{s&&s.owns(k)?s.release(k):r?.end(k)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),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,g)=>{let{app:y,entry:k}=await t.sessionFor(p);return await b(y,k,v(k,_,g))},openAudioOn:async(p,g,y,k)=>{let O=h(p);if(O){let C=O.entry.session;return Vu(C)}let{app:x,entry:P}=await t.sessionForHandle(p);if(k&&P.session.phase?.name!=="live"){let C=P.session.phase?.name;k({status:C==="queued"||C==="waiting_for_capacity"?C:"pending",reason:`the dial's session is ${C??"not yet admitted"} \u2014 the connection waits for admission`})}let E=Wt(p)?.app.startsWith(Et)??!1;return await b(x,P,v(P,R,g,E))},openTurnsOn:async function*(p,g){if(g?.aborted)throw io(g);let y=await m(p);yield*Ri(y.session,g)},openVideoOn:async p=>{let g=h(p);if(g)return zu(g.entry.session);let{entry:y}=await t.sessionForHandle(p),k=a.get(y);return k||(k=Ho(y.session),a.set(y,k)),k},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=Ho(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=fa(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),k=c(y.entry);if(k===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return kn(f,k)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:k}=await t.dedicatedSessionFor(p);return kn(y,Zu(k))},releaseSessionHandle:p=>{let g=Wt(p);if(!g)return;if(g.app.startsWith(Et)){(async()=>{let k=null;try{k=(await t.sessionForHandle(p)).entry}catch{return}await Yu(k.session).catch(()=>{}),await t.evict(g.app,k)})();return}if(!s||g.app!==f)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let k=await m(p);await ao(k.session);let O=y!==void 0&&h(p)?new Ft({...k.session,consumerId:y},{sessionTag:y}):k.responses;return Ts(await O.responses.create(g),k.gone)},onSessionEnd:async(p,g)=>{let y=h(p);if(y)return y.entry.gone.onGone(P=>g({timeLeftMs:null,reason:P.message}));let{entry:k}=await t.sessionForHandle(p),O=k.session;if(typeof O.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let x=!1;return O.onPhase(P=>{if(x||!kg.has(P.name))return;x=!0;let E=O.endsAt??null;g({timeLeftMs:E?Math.max(0,E.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}var xg=512;function lo(t){return`urun-inference-proxy-${(0,Yn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var uo=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,Yn.randomUUID)()}`;return lu(s,a,u,u)}})}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,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Do,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{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:Xu(process.env,process.env.HOSTNAME)??void 0},r=js(n),o=n.decisionPool?ed(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(qs(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),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>=xg;){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("; ")}`)}},td=512,Ag=1024,Gs=class extends Error{constructor(){super(`conversation capacity reached (${td} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Ig(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Jt))return{concurrencyKey:e};if(n.startsWith(Jt)||n.startsWith(Et))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Jt)||n.startsWith(Et)||t.set(n,r)}}}function Og(t,e,n,r,o){let s=js({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Do,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{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",...Ig(r,o)});return{clients:qs(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var co=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${lo(e.apiKey)}:live`:`${lo(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Og(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.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>=td;){let e=!1;for(let[n,r]of this.byCaller){for(let[o,s]of r)if(!(s.attachments>0)){r.delete(o),this.dropHandleIndexFor(n,o),s.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Gs}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,Yn.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===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 l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().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(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===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 l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===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 l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===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 d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().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(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===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 l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===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 l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===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 a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Ag;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new ee("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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.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("; ")}`)}};I();var po="/inference-usage",nd=25e3;var Tg=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function rd(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Tg.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 fo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${po}`,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(nd)})}catch(i){throw new we(`the uRun usage surface (POST ${po}) could not be reached within ${nd}ms: ${rd(i)}`)}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 i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new we(`the uRun usage surface (POST ${po}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new we(`the uRun usage surface (POST ${po}) answered HTTP ${o.status} with a body that is not JSON: ${rd(i)}`)}return ea(s,this.opts.onRejectedRow)}};I();var Pg="/inference-ledger",Cg=1e4,mo=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Vs=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Te=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Ks=class extends ie{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},zs=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Lg=[["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",Ws],["output_minutes",Ws],["cost_nano_usd",Ws],["price_version",t=>t===null||typeof t=="string"]];function $g(t){for(let[e,n]of Lg){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Mg(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"}:$g(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ws(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Js(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Ng(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function od(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 Ug(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&&od(t.started_at,n.started_at)&&od(t.completed_at,n.completed_at)&&Js(t.prompt_tokens,n.prompt_tokens)&&Js(t.completion_tokens,n.completion_tokens)&&Js(t.output_units,n.output_units)&&Ng(t.output_minutes,n.output_minutes)}function Dg(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(`
93
+ `)}async function Fg(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(Dg(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Bg(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Te(`${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 Te(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Te(`${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 Te(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new Te(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new Te(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Te(`${e} answered a BLANK ${u} (${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"),l=o!=null;if(l&&(i===null||a!==null))throw new Te(`${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(!l&&(i!==null||a===null))throw new Te(`${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 go=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Pg}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Fg(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new Te(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Cg)})}catch(u){throw new Te(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Mg(u);throw d.status==="found"&&Ug(n,d.row)?new Vs(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 mo(`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 mo(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Ks("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 u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new zs(`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: `+u.slice(0,400)):new Te(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new Te(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new Te(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Bg(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new Te(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Hg=5e3,jg=1e3,qg=1500,Gg=3e3,Wg="/api/client-tokens";function ho(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function sd(t,e,n,r){ho(t,e,{error:{message:n,type:r}})}async function Jg(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Wg}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Gg)});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 ud(t){let e=t.resolver??new zn({gatewayUrl:t.baseUrl}),n=t.machine?new no({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new ro({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new dr(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{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 w=new ld.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),T=Fu({redis:w});return{registry:Iu({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:fu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(M,F)=>s?.onHostedChange(M,F)??(()=>()=>{}),roomDoc:(M,F)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(M,F)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(M,F)=>T.rows().then(G=>{let se=To(G,F);return se?.warm_wait_s!==void 0?se.warm_wait_s*1e3:void 0}),currentReleaseOf:Ou(w),closeLane:M=>s?.closeLane(M)}),catalog:T,redis:w}})(),l=t.registry??new uo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Jg(t.baseUrl)),d=async()=>{let w=null;for(let M of l.decisionPools()){w=M;break}if(!w)return null;let T=w.stats();if(T.some(M=>M.draining))return{ok:!1,detail:"decision pool draining"};if(T.every(M=>M.attached===0&&M.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let $=await w.pingReady(qg);return{ok:$,detail:$?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new fo({apiUrl:t.apiUrl}),f=t.ledgerClient??new go({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(qr)}catch(w){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(w instanceof Error?w.message:w)}
94
+ `)}})();let _=async w=>Ns(so(w.headers.authorization),e,n,r),R=async w=>{let T=await _(w);if(T.billingAudience==="platform"&&T.creditsAdmissionOk===!1){let $=T.creditsRefusalReason;throw new gn($==="spend_cap_reached"||$==="insufficient_credits"?$:void 0)}return T},v=w=>w instanceof ie?{status:w.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:w instanceof gn?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...w.code!==void 0?{code:w.code}:{}}:w instanceof pt?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:w.detail}:null,b={write:(w,T)=>f.write(so(w.headers.authorization),T),observe:w=>o.observeLedger(w),...t.ledgerLog?{report:t.ledgerLog}:{}},p=zl({clients:async w=>l.clientsFor(await R(w)),usage:{authorize:w=>so(w.headers.authorization),lookup:(w,T)=>c.lookup(w,T)},statusOf:v,...t.requestLog?{requestLog:t.requestLog}:{},observe:w=>o.observe(w),ledger:b}),g=il({authorize:async w=>{await R(w)},...t.lane?{secret:t.lane.tokenSecret}:{}}),y=null,k=null,O=(0,id.createServer)((w,T)=>{let $=new URL(w.url??"/","http://localhost");(async()=>{if(w.method==="GET"&&$.pathname==="/healthz"){ho(T,200,{ok:!0});return}if(w.method==="GET"&&$.pathname==="/readyz"){let G=Date.now();if((!y||G-y.at>=Hg)&&(y={at:G,...await u()}),!k||G-k.at>=jg){let ae=await d();k=ae===null?{at:G,ok:!0,detail:null}:{at:G,ok:ae.ok,detail:ae.detail}}let se=(y?.ready??!1)&&k.ok,X=k.detail===null?y?.detail??"control plane not yet probed":`${y?.detail??"control plane not yet probed"}; ${k.detail}`;ho(T,se?200:503,{ok:se,control_plane:X});return}if(w.method==="GET"&&$.pathname==="/lanez"){ho(T,200,{pools:a?await a.registry.status():null});return}let M=$.pathname==="/v1"||$.pathname.startsWith("/v1/"),F=$.pathname.startsWith("/partners/");if(!M&&!F){sd(T,404,`no route for ${w.method} ${$.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}await g(w,T)||p(w,T)})().catch(M=>{if(!T.headersSent){sd(T,500,String(M instanceof Error?M.message:M),"proxy_error");return}T.end()})}),x=t.conversations??new co({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),P=new WeakMap,E=[Wo(O,{authenticate:async w=>{let T=await Ns(w,e,n,r),$=x.connectionFor(T);return{clients:$.clients,scope:lo(T.apiKey),onBindResumeHandle:$.bindResumeHandle,clientsForResume:$.clientsForResume,release:$.release}}}),ns(O,{clients:async w=>l.clientsFor(await R(w)),statusOf:v}).close,Or(O,{resolver:{resolve:async(w,T,$)=>{let M=await R(w),F=x.connectionFor(M,eu(w)),G;try{G=await tu(ks(F.clients,t.realtimeCompanions),Ql(w),T,Zl(w),$)}catch(ae){throw F.release().catch(()=>{}),ae}let se=G.release,X={...G,release:async()=>{await se?.(),await F.release()}};return P.set(X,M.orgId),X}},onSessionEnded:w=>{rr({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:Tt(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:w.binding.model??null,stream:null,org:P.get(w.binding)??null,duration_ms:w.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:w.connected_ms/1e3,session_id:w.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:w.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:w.req})}})];if(t.lane&&a){let w=t.lane,T=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=Du(O,{verifyToken:(M,F)=>Os(M,F,w.tokenSecret,void 0,T),selfAddress:w.selfAddress,laneTenantOf:M=>a.redis.get(`lane_tenant:${M}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:T,hostRegistry:{setHost:(M,F)=>a.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:${M}`,F,String(Uu)),delHost:M=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${M}`,w.selfAddress)}}),i=Su(O,{verifyToken:(M,F)=>Os(M,F,w.tokenSecret,void 0,T),selfAddress:w.selfAddress,hostOf:async M=>{let F=await a.redis.get(`lane_hosts:${M}`);return F&&F.trim()!==""?F.trim():null},podToPodDial:(M,F,G)=>new Promise((se,X)=>{(async()=>{let ae=await a.redis.get(`lane_tenant:${M}`),z=Wn(M,w.tokenSecret,void 0,void 0,ae||void 0),N=`ws://${G}/stream/${encodeURIComponent(M)}/${encodeURIComponent(F)}?token=${encodeURIComponent(z)}`,te=new ad.default(N,Xr(F));te.once("open",()=>se(te)),te.once("error",X)})().catch(X)})});let $=a;E.push(async()=>{await s.close(),await i.close(),await $.registry.close(),$.redis.quit().catch(()=>{})})}O.on("upgrade",(w,T)=>{let $=new URL(w.url??"/","http://localhost");$.pathname===hr||$.pathname===es||$.pathname===Dn||s!==null&&$.pathname.startsWith("/doc/")||i!==null&&$.pathname.startsWith("/stream/")||T.destroyed||(T.write(`HTTP/1.1 404 Not Found\r
93
95
  Connection: close\r
94
96
  \r
95
- no WS route for ${x.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),O.destroy())});let T=async()=>{for(let w of k)await w();await y.detachAll()};return{server:g,metricsServer:Wi(r),metrics:r,edgeIdentityServer:Ki(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:T}}async function ql(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Ii()||Ti(),await e()}function lg(){let t=null;return t=vi({streams:Qe.default,note:e=>{t?.isDead("stderr")!==!0&&Ze(Qe.default.stderr,e)}}),t}async function dg(){lg();let t=zi(Qe.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Bl(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,kt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(Ao,kt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(Io,kt,a)}),Qe.default.stdout.write(`inference-proxy listening on http://${kt}:${t.port}/v1 (metrics http://${kt}:${Ao}${er}, edge identity http://${kt}:${Io}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
96
- `);let i=async a=>{Qe.default.stdout.write(`inference-proxy: ${a} \u2014 draining
97
- `),await ql(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Qe.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Qe.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}dg().then(()=>Qe.default.exit(0),t=>{Qe.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
98
- `),Qe.default.exit(1)});
97
+ no WS route for ${$.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),T.destroy())});let C=async()=>{for(let w of E)await w();await x.detachAll()};return{server:O,metricsServer:ra(o),metrics:o,edgeIdentityServer:ia(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:C}}async function dd(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ji()||qi(),await e()}function Vg(){let t=null;return t=Li({streams:Ze.default,note:e=>{t?.isDead("stderr")!==!0&&et(Ze.default.stderr,e)}}),t}async function Kg(){Vg();let t=aa(Ze.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=ud(t);await new Promise((a,l)=>{e.once("error",l),e.listen(t.port,At,a)}),await new Promise((a,l)=>{n.once("error",l),n.listen(Mo,At,a)}),await new Promise((a,l)=>{r.once("error",l),r.listen(Uo,At,a)}),Ze.default.stdout.write(`inference-proxy listening on http://${At}:${t.port}/v1 (metrics http://${At}:${Mo}${ar}, edge identity http://${At}:${Uo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
98
+ `);let i=async a=>{Ze.default.stdout.write(`inference-proxy: ${a} \u2014 draining
99
+ `),await dd(e,o,s),await new Promise(l=>n.close(()=>l())),await new Promise(l=>r.close(()=>l()))};await new Promise(a=>{Ze.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Ze.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}Kg().then(()=>Ze.default.exit(0),t=>{Ze.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
100
+ `),Ze.default.exit(1)});
99
101
  /*! Bundled license information:
100
102
 
101
103
  reflect-metadata/Reflect.js: