@urun-sh/openai 0.6.35 → 0.6.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-_OZERUjH.d.cts → ResponsesClient-6QsC7NPJ.d.cts} +4 -1
- package/dist/{ResponsesClient-CSSrOYD8.d.ts → ResponsesClient-gfg7qUoE.d.ts} +4 -1
- package/dist/chunk-4NMMWAKD.js +1 -0
- package/dist/chunk-EPG5XWHE.js +64 -0
- package/dist/{chunk-ETX6IX25.js → chunk-GX243AIV.js} +1 -1
- package/dist/chunk-KKCUIOL4.js +1 -0
- package/dist/{chunk-ITPXS7D4.js → chunk-KXKTXZKG.js} +1 -1
- package/dist/chunk-OEITGJY2.js +2 -0
- package/dist/chunk-T6RD7TSR.js +23 -0
- package/dist/{composite-DGytPb8F.d.cts → composite-C6Gw4HfK.d.cts} +4 -4
- package/dist/gemini-live.cjs +1 -1
- package/dist/gemini-live.d.cts +10 -1
- package/dist/gemini-live.d.ts +3 -1
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +57 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +53 -43
- package/dist/hosted/index.d.cts +2 -2
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +4 -4
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +51 -51
- package/dist/pooler/bin.cjs +20 -20
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +58 -54
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.cjs +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +33 -29
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-5VMB5HKE.js +0 -17
- package/dist/chunk-EV4DZCHN.js +0 -1
- package/dist/chunk-LOPBORFM.js +0 -60
- package/dist/chunk-PAYCMH5F.js +0 -1
- package/dist/chunk-UO6N5FH7.js +0 -2
- /package/dist/{composite-D4oZXeX4.d.ts → composite-DAZrZyLN.d.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as _}from"./chunk-YSFSRI3D.js";_();import{createHmac as y,randomUUID as A,timingSafeEqual as S}from"crypto";var k=["sfu","urun-doc"],B="runtime:lease",b="lane:join",D="urun-runtime-key-v1";function p(r,t){if(!r)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!t)throw new Error("deriveOrgRuntimeKey requires an orgId");return y("sha256",r).update(`${D}|${t}`).digest("base64url")}var x=120,U=1440*60;function N(r){return Buffer.from(r).toString("base64url")}function K(r,t,i){let s=N(JSON.stringify(r)),e=N(JSON.stringify(t)),o=y("sha256",i).update(`${s}.${e}`).digest("base64url");return`${s}.${e}.${o}`}function J(r,t,i=x,s=b,e){let o=e?p(t,e):t;return L(r,o,i,s,e)}function M(r,t,i,s=x,e=b){return L(r,i,s,e,t)}function L(r,t,i,s,e){let o=Math.floor(Date.now()/1e3);return K({alg:"HS256",typ:"JWT"},{session_id:r,aud:"sfu",sub:r,scope:s,...e?{tenant:e}:{},iat:o,exp:o+i,jti:A()},t)}function j(r,t,i,s=Math.floor(Date.now()/1e3),e){let o=r.split(".");if(o.length!==3)return null;let[E,m,O]=o,h,n;try{h=JSON.parse(Buffer.from(E,"base64url").toString()),n=JSON.parse(Buffer.from(m,"base64url").toString())}catch{return null}if(h.alg!=="HS256")return null;let d;try{d=Buffer.from(O,"base64url")}catch{return null}let f=typeof n.tenant=="string"&&n.tenant!==""?n.tenant:void 0,u=[];if(f!==void 0?(u.push(p(i,f)),e&&u.push(p(e,f))):(u.push(i),e&&u.push(e)),!u.some(g=>{let T=y("sha256",g).update(`${E}.${m}`).digest();return d.length===T.length&&S(d,T)}))return null;let c=n.exp;if(typeof c!="number"||c<=s)return null;let a=typeof n.aud=="string"||Array.isArray(n.aud)?n.aud:void 0;if(!(a!==void 0&&k.some(g=>g===a||Array.isArray(a)&&a.includes(g))))return null;let l=n.session_id??n.sub;return typeof l!="string"||l!==t?null:{sessionId:l,aud:a,scope:typeof n.scope=="string"?n.scope:void 0,tenant:f,app:typeof n.app=="string"?n.app:void 0,fn:typeof n.fn=="string"?n.fn:void 0,exp:c}}export{B as a,U as b,J as c,M as d,j as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.
|
|
1
|
+
import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.36";var y=4141,R=g,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \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 e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
|
|
2
2
|
`)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
3
|
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ie(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
4
4
|
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as G}from"./chunk-CAR4AEQJ.js";import{f as Z,g as D,h as ee,i as ne}from"./chunk-EPG5XWHE.js";import{c as j,f as H,g as W,p as B}from"./chunk-6M5JK4YC.js";import{a as oe,b as N}from"./chunk-GQTWIDJ6.js";import{a as F}from"./chunk-4NMMWAKD.js";import{b as V,c as q,d as K,g as J,j as R,k as X,l as M,m as Q,p as b,q as z,r as Y}from"./chunk-6K7NOPD5.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as C,createClientToken as ae,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Se,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ce,isWakingPhase as Pe,SessionFailedError as Ee}from"@urun-sh/core";A();import{SessionFailedError as fe}from"@urun-sh/core";var U=2;function me(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function ge(e){let i=e?.type;return i==="response.completed"||i==="error"}function ie(e){return async function(c,l){let u=await e.sessionFor(c.model);return(async function*(){for(let d=1;d<=U;d++){let{app:w,entry:g,identity:S}=d===1?u:await e.sessionFor(c.model);l?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let s=!1,a=!1;try{let p=await e.createStream(g,c);for await(let f of p){if(ge(f)&&(s=!0),me(f)){if(d>1)continue}else a=!0;yield f}}catch(p){if(p instanceof fe&&(p.kind==="never-live"||p.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,p)}catch{}throw p}if(d<U&&!a){await e.evict(w,g);continue}throw p}if(s)return;if(d<U&&!a){await e.evict(w,g);continue}return}})()}}import{randomUUID as de}from"crypto";A();import{encodeStreamEnvelope as we}from"@urun-sh/core";var ye="audio";function re(e){let i=e.streamEndpoint(ye);return{sessionId:e.id,appendInputAudio(c){let l=Buffer.from(c,"base64");l.byteLength!==0&&i.send(we(new Uint8Array(l)))},onOutputAudio(){return()=>{}}}}var ve=0,Ae=4,Oe=4;function Xe(e,i){let c=(d,w)=>{let g=(e[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(e[d])})`);return S},l=(e.URUN_DECISION_POOL_MIN??"").trim();if(l==="0")return null;let u=l?Number.parseInt(l,10):ve;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=c("URUN_DECISION_POOL_MAX",Math.max(u,Ae));return{min:u,max:r,idleGraceMs:3e4,inFlightCap:c("URUN_DECISION_POOL_INFLIGHT_CAP",Oe),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function Qe(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return D;let c=Number.parseInt(i,10);if(!Number.isInteger(c)||c<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return c*1e3}function x(e,i,c,l){let u=e[c];if(typeof u!="function")throw new Error(`app "${i}" has no function "${c}" (set URUN_FUNCTION)`);let r=l?u(void 0,l):u();if(typeof r.end!="function")throw new Error(`app "${i}" function "${c}" returned a session without end()`);return r}function pe(e,i,c,l){let{baseUrl:u,orgId:r,auth:d}=e,w=i.fnName??e.fnName,g=e.sessionStartOptions?.(c),S=l||g||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...g,...l}:void 0,s=y=>({session:y,responses:new F(y),gone:oe(y,c)});if(d.lane==="jwt"){let y=C(i.appSlug,{baseUrl:u,orgId:r,jwt:d.jwt});return s(x(y,i.appSlug,w,S))}if(d.lane==="machine"){let{machineToken:y,gatewayUrl:k}=d,I=(typeof e.subject=="function"?e.subject():e.subject)??de(),n=C(i.appSlug,{baseUrl:u,orgId:r,getAccessToken:async()=>(await ae(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(n,i.appSlug,w,S))}let{apiKey:a,gatewayUrl:p}=d,f=(typeof e.subject=="function"?e.subject():e.subject)??de(),h=C(i.appSlug,{baseUrl:u,orgId:r,getAccessToken:async()=>(await ae(a,{baseUrl:p,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:f,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(h,i.appSlug,w,S))}function be(e){let i=e.session.id;if(typeof i!="string"||i.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 i}function ue(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,c=e.status.error?.code;return i===410||i===409&&(c==="cancelled"||c==="expired")?!0:c==="client_ended"}var Ie=new Set(["error","paused"]);function ze(e){let{auth:i,catalog:c}=e,l=null,u=(d,w)=>{let g=pe(e,d,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{l?.evict(w,g)}),g},r=new Y({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async d=>{if(d.gone.dispose(),e.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:i.lane==="api-key"?()=>Q({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(c?()=>G(c):null),listPrices:c?()=>K(c):null,shared:i.lane==="api-key"?()=>q({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let d=await e.catalogRows();return V(d)}:null,sessionKey:be});return l=r,e.defaultApp!==null&&r.seed(e.defaultApp,u({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Ye(e,i){let c=e.decisionPool;if(!c)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let l=c.replicaId??"proxy",u=new Map,r=new Map,d=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
|
|
2
|
+
`)},g=(s,a)=>{let p=u.get(a);if(p)return p;let f=new Z({min:c.min,max:c.max,idleGraceMs:c.idleGraceMs,inFlightCap:c.inFlightCap,replicaId:l,openSlot:async h=>{let y=pe(e,s,a,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>f.markSessionDead(y)),await L(y.session),w(`slot attached pool=${a} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${a} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof Ee&&ue(h)});return r.set(a,{target:s,env:c}),u.set(a,f),f},S=async(s,a)=>{let p=r.get(a);if(p)try{let f=await i.poolTuningFor(s);g(s,a).retune({min:f?.min??p.env.min,max:f?.max??p.env.max,inFlightCap:f?.in_flight_cap??p.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){w(`pool tuning refresh failed pool=${a} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await g(s,b(s)).boot()},async sessionFor(s){let a=await i.resolveTargetFor(s),p=b(a),f=g(a,p);await S(a,p);let h=await f.acquire({timeoutMs:f.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:p,entry:h.entry,identity:z(a)}},async warmFor(s){let a=await i.resolveTargetFor(s);await g(a,b(a)).boot()},end(s){let a=d.get(s)?.shift();a&&(d.get(s)?.length===0&&d.delete(s),a.release())},evict(s){for(let a of u.values())a.evict(s)},markSessionDead(s){for(let a of u.values())a.markSessionDead(s)},reap(){for(let[s,{target:a}]of r)S(a,s).then(()=>{let p=u.get(s);p&&p.reap()})},async pingReady(s){for(let a of u.values())if(await a.pingReady(s))return!0;return!1},stats(){return[...u.entries()].map(([s,a])=>({poolKey:s,...a.stats()}))},async drain(s){await Promise.all([...u.values()].map(a=>a.drain({timeoutMs:s})))},async close(){await Promise.all([...u.values()].map(s=>s.close()))}}}function _e(e){return Pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ce:Se:ce}async function L(e,i){let c=e.whenLive;if(typeof c!="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 c.call(e,{timeout:_e(e.phase),signal:i})}async function le(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.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");e.detach()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Ze(e,i=W,c,l,u=D,r){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,s=new WeakMap,a=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},p="lane",f=n=>{let o=M(n);if(!r||!o||o.app!==p)return null;let t=r.entryFor(o.key);if(!t)throw new R(`the lane behind this handle (${o.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:o.key,entry:t}},h=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=d.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let m=await j(n.session,await i());return Object.assign(m,{sessionId:n.session.id})})(),d.set(n,o),o.catch(()=>{d.get(n)===o&&d.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:m=>t.appendInputAudio(m),onOutputAudio:m=>t.onOutputAudio(m),sessionId:a(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(d.get(n)===void 0||E!==void 0&&E.waiting===0)&&await le(n.session),_(t)}let m=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?m:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),d.delete(n),S.delete(n),le(n.session).catch(()=>{})),v(_(t))};t.addEventListener("abort",O,{once:!0});let $=()=>t.removeEventListener("abort",O);m.then(T=>{$(),E(T)},T=>{$(),v(T)})})};return{createResponse:ie({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return l?l.sessionFor(n):e.sessionFor(n)}:l?n=>l.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>a(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):l?l.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{ue(t)&&(r&&r.owns(o)?r.evict(o):l?l.markSessionDead(o):e.evict(n,o),c?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=ee(N(await n.responses.responses.create(o),n.gone),u);if(!l&&!r)return t;let m=n;return(async function*(){try{yield*t}catch(E){throw ne(E)&&(r&&r.owns(m)?r.evict(m):l&&(E instanceof R?l.markSessionDead(m):l.evict(m))),E}finally{r&&r.owns(m)?r.release(m):l?.end(m)}})()}catch(t){throw r&&r.owns(n)?r.release(n):l&&l.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let m=f(n);if(m){let E=m.entry.session;return re(E)}let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await h(n);yield*J(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=H(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=B(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),m=a(t.entry);if(m===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return X(p,m)}}return(await e.handleFor(n)).handle},releaseSessionHandle:n=>{let o=M(n);if(!r||o?.app!==p)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let m=await h(n);await L(m.session);let P=t!==void 0&&f(n)?new F({...m.session,consumerId:t},{sessionTag:t}):m.responses;return N(await P.responses.create(o),m.gone)},onSessionEnd:async(n,o)=>{let t=f(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:m}=await e.sessionForHandle(n),P=m.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!Ie.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{Xe as a,Qe as b,ze as c,Ye as d,Ze as e};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{a as bt,c as Ae,d as vt,e as Pe}from"./chunk-OEITGJY2.js";import{A as ht,B as gt,C as mt,D as yt,b as Xe,d as Qe,e as W,j as Ze,k as et,m as nt,n as rt,o as ot,p as st,q as it,r as at,t as lt,u as ne,v as ct,w as dt,x as ut,y as ft,z as pt}from"./chunk-EPG5XWHE.js";import{a as qe}from"./chunk-3JWYIKHM.js";import{a as wt}from"./chunk-GQTWIDJ6.js";import{l as tt,m as te}from"./chunk-KXKTXZKG.js";import{a as _t,c as Y,e as Te}from"./chunk-KKCUIOL4.js";import{a as Ve}from"./chunk-4NMMWAKD.js";import{b as Je,d as Le}from"./chunk-GX243AIV.js";import{e as ze,j as ee,n as Ye,o as Ce}from"./chunk-6K7NOPD5.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as F,Gauge as re,Histogram as oe,Registry as an,collectDefaultMetrics as ln}from"@prometheus-io/client";import{createServer as cn}from"http";var eo=9464,St="/metrics",se="(other)",dn="(none)",un=64,fn=128,pn=["/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",lt,dt,ze],hn=new Set(pn);function gn(t){return hn.has(t)?t:se}function mn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var ie=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?dn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,se):(this.admitted.add(e),e):se}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ae=class{registry=new an;modelLabel=new ie(un);orgLabel=new ie(fn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new re({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 F({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 oe({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 oe({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 F({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 F({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 F({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 ut)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new re({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"},ft()),this.ledgerQueue.set({measure:"oldest_age_seconds"},pt()/1e3)}}),this.labelCardinality=new re({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 F({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 re({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 oe({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 oe({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 F({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 F({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&&ln({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=gn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?se:e.method,status_class:mn(e.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function kt(t){return cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==St){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${St}
|
|
2
|
+
`);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)}
|
|
3
|
+
`);return}n.end()})})}L();import{createHash as Rt}from"crypto";import{createServer as yn}from"http";var so=9465,wn="x-urun-key-id",bn="x-urun-key-fingerprint",vn="urun-ratelimit-bucket:",_n="urun-ratelimit-tier:",Et="anonymous",Sn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function kn(t){return Rt("sha256").update(`${vn}${t}`).digest("hex")}function En(t){return Rt("sha256").update(`${_n}${t}`).digest("hex")}function Rn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Sn.test(n)?n:null}function Lt(){return yn((t,e)=>{let n=Rn(t.headers.authorization);e.setHeader(wn,n===null?Et:kn(n)),e.setHeader(bn,n===null?Et:En(n)),e.writeHead(200),e.end()})}L();import{createClientToken as Ln,ClientTokenError as Cn}from"@urun-sh/core";import{createPublicKey as An,verify as Pn}from"crypto";var Ct="urun-session-gateway",Tn="machine",Nn=3e5;function Un(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var P=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=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}},D=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function de(t){let e=(t??"").trim();if(e==="")throw new P("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 P("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var In=60,On=6e4,xn=4096;function $n(t){return t===401||t===403}var le=class{constructor(e){this.opts=e;this.mint=e.mint??Ln,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new P("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<On)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 i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:In});r=i.orgId,o={...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 Cn&&$n(i.status)?(this.cache.delete(e),new P("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new D("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}: ${i instanceof Error?i.message:String(i)}`)}if(!r)throw new D("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=xn){let i=this.cache.keys().next();i.done||this.cache.delete(i.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 At(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var ce=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<Nn)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(s){throw new D("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}: ${s instanceof Error?s.message:String(s)}`)}if(!o.ok)throw new D("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 i;try{let s=await o.json();if(!Array.isArray(s.keys))throw new D("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`);i=s.keys}catch(s){throw s instanceof D?s:new D("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 i})().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 P("malformed machine token");let i,s;try{i=At(n),s=At(r)}catch{throw new P("malformed machine token")}if(i.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(i.alg??null)})`);let a=typeof i.kid=="string"?i.kid:"",u=typeof s.iss=="string"?s.iss:"";if(u===""||!this.opts.issuers.includes(u))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(s.aud!==Ct)throw new P(`machine token audience must be ${Ct} (got ${JSON.stringify(s.aud??null)})`);if(s.token_use!==Tn)throw new P(`bearer is a ${JSON.stringify(String(s.token_use??""))} token, not a machine token`);let c=typeof s.org_id=="string"?s.org_id:"";if(c==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");if((typeof s.exp=="number"?s.exp:0)<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let h=f=>f.kty==="RSA"&&f.n!==void 0&&f.e!==void 0,l=await this.jwksKeys(!1),m=a===""?void 0:l.find(f=>f.kid===a&&h(f));if(m===void 0&&(l=await this.jwksKeys(!0),m=a===""?void 0:l.find(f=>f.kid===a&&h(f))),m===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let E=Buffer.from(`${n}.${r}`,"ascii"),w=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),R=!1;try{let f=An({key:m,format:"jwk"});R=Pn("RSA-SHA256",E,f,w)}catch{R=!1}if(!R)throw new P("machine token signature failed verification");return{apiKey:e,orgId:c,credential:"machine"}}};function Ne(t,e,n){return n!==null&&Un(t)?n.verify(t):e.resolve(t)}L();var Dn=8080,Ue="serve",ho="0.0.0.0";function Hn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function go(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Dn: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=tt(te(Hn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?te(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=s?{catalogUrl:te(s,"URUN_CATALOG_URL"),anonKey:a}:null,c=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!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 h=c?{keyId:d,key:c}:void 0,l={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()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],E=m.filter((y,_)=>Object.values(l)[_]==="");if(E.length!==0&&E.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${E.join(", ")}, which would half-configure the lane plane`);let w=E.length===0?l:void 0,R={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},f=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=f.filter((y,_)=>Object.values(R)[_]==="");if(g.length!==0&&g.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let S=g.length===0?R:void 0,k={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},v=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],N=v.filter((y,_)=>Object.values(k)[_]==="");if(N.length!==0&&N.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${N.join(", ")}, which would half-configure the machine-identity rung`);let $=k.issuers.split(",").map(y=>y.trim()).filter(y=>y!=="");if($.length===0&&N.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 p=Number(k.tokenTtlS);if(N.length===0&&(!Number.isFinite(p)||p<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(k.tokenTtlS)}`);let b=N.length===0?{jwksBaseUrl:k.jwksBaseUrl,issuers:$,tokenTtlS:p}:void 0;return{port:n,baseUrl:r,apiUrl:i,catalog:u,ledgerSigning:h,lane:w,pooler:S,machine:b}}L();import{createHash as Vn,randomUUID as Ut}from"crypto";L();import{request as Mn}from"http";var Fn="/pooler/v1/inference",G=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterSeconds=i;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Wn=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)},Gn=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)}},Tt=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)}),Kn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Tt(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 G(t.status,e,n,t.retryAfterSeconds)};async function Bn(t,e,n,r,o){let i=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Fn}`),s=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Wn(e),firstMessage:Gn(e)}});return new Promise((a,u)=>{let c=Mn({hostname:i.hostname,port:i.port===""?void 0:Number(i.port),path:`${i.pathname}${i.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(s))}},d=>{let h=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:d})});c.on("error",d=>u(new G(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),c.end(s)})}var Pt=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*jn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);if(o===-1)break;let i=e.slice(0,o);e=e.slice(o+2);let s=Pt(i);s!==null&&(yield s)}let n=Pt(e);n!==null&&(yield n)}async function Nt(t,e,n,r){let o=Je(e,n,r),i=o.model??"";if(i==="")throw new G(400,"missing_model","the pooler submit requires a model");let s=await Bn(t,o,n,i,e.stream===!0);if(s.status>=400)throw await Kn(s);let a=e.stream===!0?Le(n,jn(s)):await Jn(s,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Jn(t,e){let n=await Tt(t.body),r=null;try{let i=JSON.parse(n);i!==null&&typeof i=="object"&&(r=i)}catch{r=null}if(r===null)throw new G(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Le(e,(async function*(){yield o})())}var zn=512;function Ie(t){return`urun-inference-proxy-${Vn("sha256").update(t).digest("hex").slice(0,32)}`}var ue=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),i=this.opts.pooler;if(i===void 0)return o;let s=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,u)=>{if(s!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,u)}catch(h){if(!(h instanceof W))throw h}let c=`px_${Ut()}`;return Nt(i,a,c,c)}})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e,i.router),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ue,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:bt(process.env,process.env.HOSTNAME)??void 0},r=Ae(n),o=n.decisionPool?vt(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Pe(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>=zn;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},It=512,Yn=1024,fe=class extends Error{constructor(){super(`conversation capacity reached (${It} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function qn(t){return{sessionStartOptions:e=>{if(e.startsWith(Ce))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Ce)||t.set(e,n)}}}function Xn(t,e,n,r){let o=Ae({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ue,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",...qn(r)});return{clients:Pe(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var pe=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Ie(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Xn(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=It;){let e=this.byCaller.keys().next();if(e.done)throw new fe;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new fe;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,Ut())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),releaseSessionHandle:s=>o().backhaul.clients.releaseSessionHandle?.(s),createResponseOn:(s,a,u)=>o().backhaul.clients.createResponseOn(s,a,u),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a,u)=>{let c=o().backhaul.clients.openAudioOn;if(c===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 c(s,a,u)},i.openTurnsOn=(s,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Yn;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),c=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||c===void 0||a.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 n=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var Qn="/inference-ledger",Zn=1e4,he=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},$e=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},U=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},De=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},He=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},er=[["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",Oe],["output_minutes",Oe],["cost_nano_usd",Oe],["price_version",t=>t===null||typeof t=="string"]];function tr(t){for(let[e,n]of er){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function nr(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"}:tr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Oe(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function xe(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function rr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ot(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 or(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&&Ot(t.started_at,n.started_at)&&Ot(t.completed_at,n.completed_at)&&xe(t.prompt_tokens,n.prompt_tokens)&&xe(t.completion_tokens,n.completion_tokens)&&xe(t.output_units,n.output_units)&&rr(t.output_minutes,n.output_minutes)}function sr(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(`
|
|
6
|
+
`)}async function ir(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(sr(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function ar(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new U(`${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 U(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new U(`${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 U(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=c=>{if(!(c in n))throw new U(`${e} answered a row with no ${c} field: ${JSON.stringify(t)}`);let d=n[c];if(d===null)return null;if(typeof d!="string")throw new U(`${e} answered a non-string ${c}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new U(`${e} answered a BLANK ${c} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},s=i("price_version"),a=i("unpriced_reason"),u=o!=null;if(u&&(s===null||a!==null))throw new U(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new U(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Qn}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ir(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new U(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let i;try{i=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Zn)})}catch(c){throw new U(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(i.status===409){let c=await i.text().catch(()=>""),d=nr(c);throw d.status==="found"&&or(n,d.row)?new $e(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 he(`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 he(`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). ${c.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new De("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!i.ok){let c=await i.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),d;try{let h=JSON.parse(c);if(h!==null&&typeof h=="object"&&"error"in h){let l=h.error;l!==null&&typeof l=="object"&&"code"in l&&(d=l.code)}}catch{}throw d==="ledger_signature_invalid"?new He(`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: `+c.slice(0,400)):new U(`the uRun ledger surface at ${r} answered HTTP ${i.status}: ${c.slice(0,400)}`)}let s;try{s=await i.json()}catch(c){throw new U(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let a=s?.recorded;if(a===void 0)throw new U(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=ar(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new U(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};L();import{createServer as Mr}from"http";L();import{createWebsocketDocConnector as gr}from"@urun-sh/core/internal";import mr from"ws";L();import*as K from"yjs";import{SessionDocumentImpl as lr}from"@urun-sh/core/internal";var cr=3e4;function dr(t){return(e,n,r)=>{let o=t(e);K.applyUpdate(n,K.encodeStateAsUpdate(o));let i=a=>K.applyUpdate(o,a),s=a=>K.applyUpdate(n,a);return n.on("update",i),o.on("update",s),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",i),o.off("update",s)}}}}function Me(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?dr(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,i=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=r.get(d);return h||(h=new lr(d,e,n),r.set(d,h)),h},s=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 h=s.get(d);if(!h){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);h=t.streamEndpoint(d),s.set(d,h)}return h},u=d=>{let h="llm-resp:";if(!d.startsWith(h))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${h}<rid>)`);async function*l(){let m=a(d);try{yield*m.messages()}finally{s.delete(d),await m.close()}}return{messages:()=>l(),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 i(d)},stream:u,streamEndpoint:a,async end(){},async whenLive(d){let h=i("llm");if(h.synced===!0)return;let l=d?.timeout??t.whenLiveTimeoutMs??cr;await new Promise((m,E)=>{let w=setTimeout(()=>{R(),E(new Error(`lane ${e} llm doc never synced within ${l}ms`))},l),R=h.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",f),m()}),f=()=>{clearTimeout(w),R(),E(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",f,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,h]of s)s.delete(d),h.close()}}}L();import me,{WebSocketServer as ur}from"ws";import{ENVELOPE_KIND as Mt,STREAM_END as fr,StreamFragmentReassembler as pr}from"@urun-sh/core";var xt="/stream/";function $t(t){if(!t.startsWith(xt))return null;let e=t.slice(xt.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 be(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function ye(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>Mt.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var we=class{reassembler=new pr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===fr&&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})}}},We=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 i=this.chan(e,n),s=[...i.peers].filter(a=>a!==r);if(s.length===0){let a=i.pending;(a.list.length>=Dt||a.bytes+o.byteLength>Ht)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Dt} frames / ${Ht} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of s)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let i=o.pending;if(i.list.length===0)return;let s=i.list.filter(a=>a.producer!==r);i.list=i.list.filter(a=>a.producer===r),i.bytes=i.list.reduce((a,u)=>a+u.envelope.byteLength,0);for(let{envelope:a}of s)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,i=this.channels.get(o);if(i){for(let s of[...i.peers])s===r&&i.peers.delete(s);i.peers.size===0&&i.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 i of o?.peers??[])i.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")}}},Dt=256,Ht=8*1024*1024,H=new We;function Ft(t,e){let n=new we,r={send(o){H.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{ye(o)}catch(i){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(i)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),H.detach(t,e,r)}};return H.attach(t,e,r),r}function hr(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 Wt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new me(r,be(e)),i=new we;return o.addEventListener("message",s=>{let a=new Uint8Array(s.data);try{ye(a)}catch(u){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(u)}`);return}i.push(i.feed(a))}),o.addEventListener("close",()=>{i.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{i.finish(new Error(`lane stream ${r} socket error`))}),{send(s){if(ye(s),o.readyState!==me.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(s,{binary:!0})},deliver(s){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>i.iterate(),async close(){i.finish();try{o.close(1e3)}catch{}}}}function Fe(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
7
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
8
|
+
Connection: close\r
|
|
9
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
10
|
+
Content-Length: ${Buffer.byteLength(o)}\r
|
|
11
|
+
\r
|
|
12
|
+
${o}`)}function Gt(t,e){let n=new ur({noServer:!0,handleProtocols:(u,c)=>{let d=$t(new URL(c.url??"/","http://localhost").pathname);if(!d)return!1;let h=be(d.name);return u.has(h)?h:!1}}),r=new Map,o=new Set,i=!1,s=(u,c,d,h)=>{let l={client:d,upstream:h,laneId:u,name:c};o.add(l);let m=E=>{if(o.delete(l)){console.warn(`[lane-stream] ${u}/${c}: host-affinity pump torn down (${E})`);for(let w of[d,h])try{(w.readyState===me.OPEN||w.readyState===me.CONNECTING)&&w.close(1001,"lane stream pump closed")}catch{}}};d.on("message",E=>{try{h.send(E,{binary:!0})}catch(w){m(`upstream send failed: ${String(w)}`)}}),h.on("message",E=>{try{d.send(E,{binary:!0})}catch(w){m(`client send failed: ${String(w)}`)}}),d.on("close",()=>m("client socket closed")),d.on("error",()=>m("client socket error")),h.on("close",()=>m("host socket closed")),h.on("error",()=>m("host socket error"))},a=(u,c,d)=>{let h;try{h=new URL(u.url??"/","http://localhost")}catch{Fe(c,400,"malformed upgrade URL");return}c.on("error",()=>c.destroy());let l=$t(h.pathname);l&&(i||c.destroyed||(async()=>{let m=h.searchParams.get("token")??"",E=null;try{E=m===""?null:await e.verifyToken(m,l.laneId,l.name)}catch{E=null}if(E===null){Fe(c,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let w=await e.hostOf(l.laneId).catch(()=>null);if(w&&w!==e.selfAddress)try{let R=await e.podToPodDial(l.laneId,l.name,w);n.handleUpgrade(u,c,d,f=>{s(l.laneId,l.name,f,R)});return}catch(R){console.warn(`[lane-stream] ${l.laneId}/${l.name}: host dial to ${w} failed (${String(R)}) \u2014 falling back to the local relay`)}}n.handleUpgrade(u,c,d,w=>{let R=hr(w);r.set(w,R),H.attach(l.laneId,l.name,R),w.on("message",g=>{let S=new Uint8Array(g);try{ye(S)}catch(k){console.warn(`[lane-stream] ${l.laneId}/${l.name}: dropped malformed envelope: ${String(k)}`);return}H.deliver(l.laneId,l.name,R,S),S[1]===Mt.END&&H.detach(l.laneId,l.name,R)});let f=()=>{r.delete(w),H.detach(l.laneId,l.name,R)};w.on("close",f),w.on("error",f)})})().catch(()=>{c.destroyed||Fe(c,500,"lane stream upgrade failed")}))};return t.on("upgrade",a),{async close(){i=!0,t.off("upgrade",a),H.clear();for(let u of r.values())u.close(1001,"lane stream host shutting down");r.clear();for(let u of o)for(let c of[u.client,u.upstream])try{c.close(1001,"lane stream host shutting down")}catch{}o.clear()}}}function yr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Qe(`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 Kt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,i=new Map,s=(l,m,E,w,R)=>{let f=E?v=>Ft(l,v):v=>Wt(l,v,{hostUrl:`ws://${w}/stream/${l}`,token:()=>Y(l,t.tokenSecret,void 0,void 0,R)}),g=E?Me({laneId:l,roomDoc:v=>t.roomDoc(l,v),streamEndpoint:f}):Me({laneId:l,streamEndpoint:f,connector:gr({serverUrl:`ws://${w}/doc`,sessionId:l,token:()=>Y(l,t.tokenSecret,void 0,void 0,R),WebSocketPolyfill:mr})}),S=E?a(l):wt(g,`lane:${l}`,{armOnFirstSync:!0}),k={session:g,responses:new Ve(g,{sessionTag:null}),gone:S,goneWatch:S,laneId:l,pool:m,inFlight:0,laneSession:g,self:E,host:w??""};return n.set(l,k),S.onGone(()=>u(k)),k},a=l=>{let m=null,E=!1,w=new Set,R=g=>{if(!m){m=g;for(let S of[...w])S(g);w.clear()}},f=t.hostedSignal?.(l,g=>{if(g){E=!0;return}E&&R(new ee(`the lane ${l} 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:()=>m,onGone(g){return m?(g(m),()=>{}):(w.add(g),()=>w.delete(g))},dispose(){f?.(),w.clear()}}},u=l=>{c(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose(),H.forgetLane(l.laneId))},c=l=>{let m=l.laneId;return typeof m=="string"&&n.get(m)===l},d=(l,m)=>{throw t.metrics?.observeLane503Fast(m??""),i.set(l,e()),new W(l)},h=async(l,m)=>{let E=yr(m);o.add(E);let w=e();try{let R=await t.laneWarmWaitMsFor?.(l,m)??t.laneColdWakeDefaultMs??0,f=await t.plane.pick({pool:E,model:l,holdMs:R});t.metrics?.observeLaneReady(l??"",f.length);let S=f.map(v=>({laneId:v.laneId,self:v.host===t.selfAddress,host:v.host})).sort((v,N)=>v.self!==N.self?v.self?-1:1:(r.get(v.laneId)??0)-(r.get(N.laneId)??0))[0];S||d(E,l);let k=n.get(S.laneId);return k?.goneWatch?.gone()&&(u(k),k=void 0),k&&(k.pool!==E||k.self!==S.self||k.host!==S.host)&&(u(k),k=void 0),k||(k=s(S.laneId,E,S.self,S.host,m.sharedOrgId??void 0)),k.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:k,identity:{kind:"catalog",model_id:m.modelId??l??"",variant:m.variant??""}}}finally{t.metrics?.observeLanePick(l??"",e()-w)}};return{sessionFor(l,m){return h(l,m)},release(l){c(l)&&(l.inFlight=Math.max(0,l.inFlight-1),r.set(l.laneId,l.inFlight))},owns(l){return c(l)},entryFor(l){return n.get(l)??null},evict(l){c(l)&&(l.gone.dispose(),n.delete(l.laneId),r.set(l.laneId,0),l.laneSession.destroy())},async status(){let l=[...new Set([...o,...[...n.values()].map(w=>w.pool)])].sort(),m=await t.plane.status().catch(()=>[]),E=new Map(wr(m));return Promise.all(l.map(async w=>{let R=E.get(w)??{pool:w,lanes:[],lastDemandAt:null};return{pool:w,lanes:R.lanes,lastDemandAt:R.lastDemandAt,local:[...n.values()].filter(f=>f.pool===w).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:i.get(w)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function wr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();import{request as br}from"http";var vr="/pooler/v1/lanes/pick",_r="/pooler/v1/lanes/status",Sr=1e4;function Bt(t,e,n,r,o){return new Promise((i,s)=>{let a=new URL(n,t.baseUrl),u=r===void 0?void 0:Buffer.from(JSON.stringify(r)),c=br({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 h=[];d.on("data",l=>h.push(l)),d.on("end",()=>{let l=Buffer.concat(h).toString("utf8"),m=null;try{m=l===""?null:JSON.parse(l)}catch{m=null}i({status:d.statusCode??0,json:m})}),d.on("error",s)});c.on("timeout",()=>{c.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),c.on("error",s),c.end(u)})}function jt(t,e,n){if(t===503)return new W(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 Jt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await Bt(t,"POST",vr,{pool:e,model:n,hold_ms:r},r+Sr);if(o.status!==200)throw jt(o.status,o.json,e);return(o.json?.lanes??[]).filter(s=>typeof s.lane_id=="string"&&s.lane_id!==""&&typeof s.host=="string"&&s.host!=="").map(s=>({laneId:s.lane_id,host:s.host}))},async status(){let e=await Bt(t,"GET",_r,void 0,5e3);if(e.status!==200)throw jt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import{WebSocketServer as Or}from"ws";L();import*as zt from"yjs";import*as J from"y-protocols/sync";import*as M from"y-protocols/awareness";import*as A from"lib0/encoding";import*as V from"lib0/decoding";import*as Yt from"lib0/map";import Er from"lodash.debounce";L();var Vt=()=>{};var Rr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Lr=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Cr=0,Ar=1;var Pr=process.env.GC!=="false"&&process.env.GC!=="0",Tr=process.env.YPERSISTENCE,ve=null;if(typeof Tr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var j=new Map,_e=0,Ke=1,Nr=(t,e,n)=>{let r=A.createEncoder();A.writeVarUint(r,_e),J.writeUpdate(r,t);let o=A.toUint8Array(r);n.conns.forEach((i,s)=>X(n,s,o))},Ge=class extends zt.Doc{constructor(e){super({gc:Pr}),this.name=e,this.conns=new Map,this.awareness=new M.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:i},s)=>{let a=r.concat(o,i);if(s!==null){let d=this.conns.get(s);d!==void 0&&(r.forEach(h=>{d.add(h)}),i.forEach(h=>{d.delete(h)}))}let u=A.createEncoder();A.writeVarUint(u,Ke),A.writeVarUint8Array(u,M.encodeAwarenessUpdate(this.awareness,a));let c=A.toUint8Array(u);this.conns.forEach((d,h)=>{X(this,h,c)})};this.awareness.on("update",n),this.on("update",Nr),!1}},Be=(t,e=!0)=>Yt.setIfUndefined(j,t,()=>{let n=new Ge(t);return n.gc=e,ve!==null&&ve.bindState(t,n),j.set(t,n),n}),Ur=(t,e,n)=>{try{let r=A.createEncoder(),o=V.createDecoder(n);switch(V.readVarUint(o)){case _e:A.writeVarUint(r,_e),J.readSyncMessage(o,r,e,t),A.length(r)>1&&X(e,t,A.toUint8Array(r));break;case Ke:{M.applyAwarenessUpdate(e.awareness,V.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},B=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),M.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&ve!==null&&(ve.writeState(t.name,t).then(()=>{t.destroy()}),j.delete(t.name))}e.close()},X=(t,e,n)=>{e.readyState!==Cr&&e.readyState!==Ar&&B(t,e);try{e.send(n,r=>{r!=null&&B(t,e)})}catch{B(t,e)}},Ir=3e4,qt=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Be(n,r);o.conns.set(t,new Set),t.on("message",a=>Ur(t,o,new Uint8Array(a)));let i=!0,s=setInterval(()=>{if(!i)o.conns.has(t)&&B(o,t),clearInterval(s);else if(o.conns.has(t)){i=!1;try{t.ping()}catch{B(o,t),clearInterval(s)}}},Ir);t.on("close",()=>{B(o,t),clearInterval(s)}),t.on("pong",()=>{i=!0});{let a=A.createEncoder();A.writeVarUint(a,_e),J.writeSyncStep1(a,o),X(o,t,A.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let c=A.createEncoder();A.writeVarUint(c,Ke),A.writeVarUint8Array(c,M.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),X(o,t,A.toUint8Array(c))}}};var je="/doc/",Qt=30,xr=1e4,Xt="llm";function $r(t){if(!t.startsWith(je))return null;let e=t.slice(je.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 Q(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
14
|
+
Connection: close\r
|
|
15
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
16
|
+
Content-Length: ${Buffer.byteLength(o)}\r
|
|
17
|
+
\r
|
|
18
|
+
${o}`)}function Zt(t,e){let n=new Or({noServer:!0}),r=new Set,o=new Map,i=new Map,s=f=>o.get(`${f}/${Xt}`)??0,a=f=>i.get(f)??0,u=new Map,c=new Map,d=new Set,h=new Set,l=!1,m=(f,g,S)=>{let k=s(f)>0,v=a(f),N=v>0,$=`${f}/${g}`,p=o.get($)??0;S>0?o.set($,S):o.delete($);let b=v+S-p;b>0?i.set(f,b):i.delete(f);let y=s(f)>0,_=b>0;if(k!==y){y?E(f):w(f);for(let C of u.get(f)??[])C(y)}N&&!_&&queueMicrotask(()=>{let C=`${f}/`;for(let[T,x]of[...j.entries()])!T.startsWith(C)||x.conns.size>0||(j.delete(T),x.destroy())})},E=f=>{if(!e.hostRegistry||c.has(f))return;let g=()=>{e.hostRegistry?.setHost(f,e.selfAddress).catch(()=>{})};g();let S=setInterval(g,xr);S.unref?.(),c.set(f,S)},w=f=>{let g=c.get(f);g&&(clearInterval(g),c.delete(f)),e.hostRegistry&&e.hostRegistry.delHost(f,e.selfAddress).catch(()=>{})},R=(f,g,S)=>{let k;try{k=new URL(f.url??"/","http://localhost")}catch{Q(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>h.delete(g));let v=$r(k.pathname);if(!v){if(k.pathname.startsWith(je)){Q(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(g);return}d.add(g);let N=!1;(async()=>{let $=k.searchParams.get("token")??"",p=null;try{p=$===""?null:await e.verifyToken($,v.laneId,v.docName)}catch{p=null}if(p===null){Q(g,401,"invalid or missing lane doc token");return}let b=p;if(b.tenant!==void 0&&e.laneTenantOf){let y=null;try{y=await e.laneTenantOf(v.laneId)}catch{y=null}if(y==null||y==="")e.onLaneTenantMissing?.();else if(b.tenant!==y){Q(g,403,"lane doc token org does not match the lane record");return}}l||g.destroyed||(N=!0,n.handleUpgrade(f,g,S,y=>{d.delete(g),r.add(y),y.on("close",()=>r.delete(y));let _=b.scope===_t||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(_){let T=`${v.laneId}/${v.docName}`,x=(o.get(T)??0)+1;m(v.laneId,v.docName,x),x>1&&v.docName===Xt&&e.hostRegistry?.setHost(v.laneId,e.selfAddress).catch(()=>{})}y.on("close",()=>{if(!_)return;let T=`${v.laneId}/${v.docName}`;m(v.laneId,v.docName,Math.max(0,(o.get(T)??1)-1))}),qt(y,f,{docName:`${v.laneId}/${v.docName}`,gc:!0})}))})().catch(()=>{!N&&!g.destroyed&&Q(g,500,"lane doc upgrade failed")}).finally(()=>d.delete(g))};return t.on("upgrade",R),{async close(){l=!0,t.off("upgrade",R);for(let g of[...c.keys()])w(g);await new Promise(g=>{if(r.size===0&&d.size===0){g();return}let S=r.size+d.size,k=()=>{S-=1,S<=0&&g()};for(let v of r)v.once("close",k);for(let v of d)v.once("close",k);for(let v of r)v.close(1001,"lane doc host shutting down");for(let v of d)v.destroy()}),o.clear(),i.clear(),u.clear()},roomDoc(f,g){return Be(`${f}/${g}`,!0)},isHosted(f){return s(f)>0},onHostedChange(f,g){let S=u.get(f);return S||(S=new Set,u.set(f,S)),S.add(g),g(s(f)>0),()=>{S.delete(g)}}}}import Fr from"ws";L();var Dr="urun:catalog:v1";function en(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,i=null,s=async()=>{let u=await t.redis.hgetall(Dr),c=[];for(let d of Object.values(u))try{c.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
19
|
+
`)}return r=c,o=n(),c},a=()=>r===null||n()-o>=e;return{rows(){return a()?(i||(i=s().finally(()=>{i=null})),i):Promise.resolve(r)},close(){r=null,i=null}}}import Wr from"ioredis";L();var Se="/inference-usage",tn=25e3;var Hr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function nn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Hr.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 ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Se}`,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(tn)})}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) could not be reached within ${tn}ms: ${nn(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new P("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} with a body that is not JSON: ${nn(s)}`)}return ct(i,this.opts.onRejectedRow)}};var Gr=5e3,Kr=1e3,Br=1500,jr=3e3,Jr="/api/client-tokens";function Ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function rn(t,e,n,r){Ee(t,e,{error:{message:n,type:r}})}async function Vr(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Jr}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(jr)});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 Ks(t){let e=t.resolver??new le({gatewayUrl:t.baseUrl}),n=t.machine?new ce({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ae(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,i=null,s=(()=>{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 p=new Wr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),b=en({redis:p});return{registry:Kt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Jt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(_,C)=>o?.onHostedChange(_,C)??(()=>()=>{}),roomDoc:(_,C)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(_,C)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(_,C)=>b.rows().then(T=>{let x=Ye(T,C);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:b,redis:p}})(),a=t.registry??new ue({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Vr(t.baseUrl)),c=async()=>{let p=null;for(let _ of a.decisionPools()){p=_;break}if(!p)return null;let b=p.stats();if(b.some(_=>_.draining))return{ok:!1,detail:"decision pool draining"};if(b.every(_=>_.attached===0&&_.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let y=await p.pingReady(Br);return{ok:y,detail:y?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new ke({apiUrl:t.apiUrl}),h=t.ledgerClient??new ge({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),l=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();l&&m&&(async()=>{try{await a.decisionWarmerFor({orgId:l,apiKey:m})?.warmFor(mt)}catch(p){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(p instanceof Error?p.message:p)}
|
|
20
|
+
`)}})();let E=async p=>Ne(de(p.headers.authorization),e,n),w=async p=>{let b=await E(p);if(b.billingAudience==="platform"&&b.creditsAdmissionOk===!1){let y=b.creditsRefusalReason;throw new q(y==="spend_cap_reached"||y==="insufficient_credits"?y:void 0)}return b},R=p=>p instanceof P?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...p.code!==void 0?{code:p.code}:{}}:p instanceof D?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:p.detail}:null,f=yt({clients:async p=>a.clientsFor(await w(p)),usage:{authorize:p=>de(p.headers.authorization),lookup:(p,b)=>d.lookup(p,b)},statusOf:R,...t.requestLog?{requestLog:t.requestLog}:{},observe:p=>r.observe(p),ledger:{write:(p,b)=>h.write(de(p.headers.authorization),b),observe:p=>r.observeLedger(p),...t.ledgerLog?{report:t.ledgerLog}:{}}}),g=null,S=null,k=Mr((p,b)=>{let y=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&y.pathname==="/healthz"){Ee(b,200,{ok:!0});return}if(p.method==="GET"&&y.pathname==="/readyz"){let T=Date.now();if((!g||T-g.at>=Gr)&&(g={at:T,...await u()}),!S||T-S.at>=Kr){let z=await c();S=z===null?{at:T,ok:!0,detail:null}:{at:T,ok:z.ok,detail:z.detail}}let x=(g?.ready??!1)&&S.ok,Z=S.detail===null?g?.detail??"control plane not yet probed":`${g?.detail??"control plane not yet probed"}; ${S.detail}`;Ee(b,x?200:503,{ok:x,control_plane:Z});return}if(p.method==="GET"&&y.pathname==="/lanez"){Ee(b,200,{pools:s?await s.registry.status():null});return}let _=y.pathname==="/v1"||y.pathname.startsWith("/v1/"),C=y.pathname.startsWith("/partners/");if(!_&&!C){rn(b,404,`no route for ${p.method} ${y.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}f(p,b)})().catch(_=>{if(!b.headersSent){rn(b,500,String(_ instanceof Error?_.message:_),"proxy_error");return}b.end()})}),v=t.conversations??new pe({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),N=[Xe(k,{authenticate:async p=>{let b=await Ne(p,e,n),y=v.connectionFor(b);return{clients:y.clients,scope:Ie(b.apiKey),onBindResumeHandle:y.bindResumeHandle,clientsForResume:y.clientsForResume,release:y.release}}}),et(k,{clients:async p=>a.clientsFor(await w(p)),statusOf:R}).close,rt(k,{resolver:{resolve:async(p,b)=>{let y=await w(p),_=v.connectionFor(y),C;try{C=await at(ot(_.clients,t.realtimeCompanions),st(p),b,it(p))}catch(x){throw _.release().catch(()=>{}),x}let T=C.release;return{...C,release:async()=>{await T?.(),await _.release()}}}}})];if(t.lane&&s){let p=t.lane,b=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Zt(k,{verifyToken:(_,C)=>Te(_,C,p.tokenSecret,void 0,b),selfAddress:p.selfAddress,laneTenantOf:_=>s.redis.get(`lane_tenant:${_}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:b,hostRegistry:{setHost:(_,C)=>s.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:${_}`,C,String(Qt)),delHost:_=>s.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.selfAddress)}}),i=Gt(k,{verifyToken:(_,C)=>Te(_,C,p.tokenSecret,void 0,b),selfAddress:p.selfAddress,hostOf:async _=>{let C=await s.redis.get(`lane_hosts:${_}`);return C&&C.trim()!==""?C.trim():null},podToPodDial:(_,C,T)=>new Promise((x,Z)=>{(async()=>{let z=await s.redis.get(`lane_tenant:${_}`),on=Y(_,p.tokenSecret,void 0,void 0,z||void 0),sn=`ws://${T}/stream/${encodeURIComponent(_)}/${encodeURIComponent(C)}?token=${encodeURIComponent(on)}`,Re=new Fr(sn,be(C));Re.once("open",()=>x(Re)),Re.once("error",Z)})().catch(Z)})});let y=s;N.push(async()=>{await o.close(),await i.close(),await y.registry.close(),y.redis.quit().catch(()=>{})})}k.on("upgrade",(p,b)=>{let y=new URL(p.url??"/","http://localhost");y.pathname===qe||y.pathname===Ze||y.pathname===nt||o!==null&&y.pathname.startsWith("/doc/")||i!==null&&y.pathname.startsWith("/stream/")||b.destroyed||(b.write(`HTTP/1.1 404 Not Found\r
|
|
21
|
+
Connection: close\r
|
|
22
|
+
\r
|
|
23
|
+
no WS route for ${y.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),b.destroy())});let $=async()=>{for(let p of N)await p();await v.detachAll()};return{server:k,metricsServer:kt(r),metrics:r,edgeIdentityServer:Lt(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:$}}async function Bs(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ht()||gt(),await e()}export{eo as a,St as b,se as c,dn as d,un as e,fn as f,gn as g,mn as h,ie as i,ae as j,kt as k,so as l,wn as m,bn as n,vn as o,_n as p,Et as q,kn as r,En as s,Rn as t,Lt as u,P as v,D as w,de as x,On as y,xn as z,le as A,Dn as B,Ue as C,ho as D,go as E,zn as F,Ie as G,ue as H,It as I,Yn as J,fe as K,pe as L,Qn as M,Zn as N,he as O,U as P,ar as Q,ge as R,Gr as S,jr as T,Ks as U,Bs as V};
|
|
@@ -151,10 +151,10 @@ interface InferenceRecord {
|
|
|
151
151
|
readonly decode_ms: number | null;
|
|
152
152
|
readonly total_ms: number | null;
|
|
153
153
|
/**
|
|
154
|
-
* THE DECISION
|
|
155
|
-
* Present only on `/v1/systemone` requests (absent keys
|
|
156
|
-
* lane); `null` means the lane reached the decision but that
|
|
157
|
-
* produced a measurement.
|
|
154
|
+
* THE DECISION LANES' HOP SPANS — see {@link InferenceTurn.decision}.
|
|
155
|
+
* Present only on `/v1/systemone` and `/v1/decisions` requests (absent keys
|
|
156
|
+
* on every other lane); `null` means the lane reached the decision but that
|
|
157
|
+
* hop never produced a measurement.
|
|
158
158
|
*/
|
|
159
159
|
readonly decision_resolve_ms?: number | null;
|
|
160
160
|
readonly decision_dial_ms?: number | null;
|
package/dist/gemini-live.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var be=Object.create;var E=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Se=(e,t)=>{for(var n in t)E(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Oe(t))!Ee.call(e,r)&&r!==n&&E(e,r,{get:()=>t[r],enumerable:!(o=ve(t,r))||o.enumerable});return e};var $=(e,t,n)=>(n=e!=null?be(Ae(e)):{},W(t||!e||!e.__esModule?E(n,"default",{value:e,enumerable:!0}):n,e)),Te=e=>W(E({},"__esModule",{value:!0}),e);var je={};Se(je,{AudioBridge:()=>O,CLOSE_PROTOCOL:()=>H,CLOSE_SESSION_GONE:()=>re,CLOSE_UNKNOWN_MODEL:()=>oe,CLOSE_UPSTREAM:()=>U,GEMINI_AUDIO_IN_RATE:()=>b,GEMINI_AUDIO_OUT_MIME:()=>F,GEMINI_AUDIO_OUT_RATE:()=>D,GEMINI_LIVE_PATH:()=>ne,GeminiLiveError:()=>s,NATIVE_AUDIO_SAMPLE_RATE:()=>R,OUTBOUND_AUDIO_FLUSH_B64:()=>pe,RT_VIDEO_IN_STREAM:()=>S,RT_VIDEO_OUT_STREAM:()=>_,SdkTransport:()=>P,VIDEO_FRAME_MESSAGE_BUDGET:()=>T,VIDEO_OUT_DEFAULT_CODEC:()=>I,VIDEO_OUT_FRAMING:()=>B,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>C,consumeVideoOut:()=>ee,decodeResponsesLane:()=>A,decodeVideoOutRecord:()=>x,enableSessionAudio:()=>J,enableSessionVideo:()=>Y,encodeVideoOutRecord:()=>z,goAwayMsg:()=>le,negotiateSessionVideoOutQuic:()=>X,nodeAudioBackend:()=>K,openSessionVideoOutLane:()=>Z,parseClientMessage:()=>ie,resamplePcm16:()=>j,responseCreateToEnvelope:()=>V,responsesCreateToEnvelope:()=>M,serverContentOfAudio:()=>we,serverContentOfDelta:()=>ye,sessionResumptionUpdateMsg:()=>ce,translateClientContent:()=>fe,translateRealtimeInput:()=>me,translateSetup:()=>de,translateToolResponse:()=>ge,turnEndOfCompleted:()=>he,videoOutAck:()=>ae,videoOutChunkMsg:()=>ue,weriftAudioBackend:()=>q});module.exports=Te(je);var R=24e3,G="audio",O=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),o=Math.floor(n.byteLength/2),r=new Int16Array(o);for(let i=0;i<o;i++)r[i]=n.readInt16LE(i*2);this.source.onData(r)}async startInbound(t){if(t==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(t),this.sink.onframe=n=>{let o=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function J(e,t,n=1e4){let o=new O(t,{sampleRate:24e3}),r=await o.startOutbound();await e.stream(G).attach(r);let i=await Re(e,n);return await o.startInbound(i),o}function Re(e,t){let n=e.stream(G);return n.track!=null?Promise.resolve(n.track):new Promise((o,r)=>{let i,a=setTimeout(()=>{i?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),c=u=>{u!=null&&(clearTimeout(a),i?.(),o(u))};i=n.on?.("track",c),n.track!=null&&c(n.track)})}var S="rt-video-in",T=256e3;function Y(e){let t=e.stream(S),n=t.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${S}') 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 o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>T)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${T}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(t,o)}}}var Ie=24e3,v=480,xe=111;async function Ce(){let e=await import("opusscript"),t=e.default??e;return new t(Ie,1,2048)}async function q(){let e=await import("werift"),t=await Ce();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:c=>{let u=new Int16Array(a.length+c.length);u.set(a,0),u.set(c,a.length);let d=0;for(;u.length-d>=v;){let l=u.subarray(d,d+v);d+=v;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,v);r=r+1&65535,i=i+v>>>0;let g=new e.RtpHeader({version:2,payloadType:xe,sequenceNumber:r,timestamp:i,ssrc:o,marker:!1}),h=new e.RtpPacket(g,p);n.writeRtp(h)}a=u.slice(d)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(i=>{let a;try{a=t.decode(i.payload)}catch{return}let c=new Int16Array(a.length/2);for(let u=0;u<c.length;u++)c[u]=a.readInt16LE(u*2);o.onframe?.({samples:c})}),o}}}async function K(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:o=>t.onData({samples:o,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},o=new e.nonstandard.RTCAudioSink(t);return o.ondata=r=>{n.onframe?.(r)},n}}}var w=require("@urun-sh/core"),_="rt-video-out",B="urun.videoOut.v1",I="h264";function Q(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function z(e,t){if(Q(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let o=new Uint8Array(2+n.byteLength+t.byteLength);return o[0]=n.byteLength&255,o[1]=n.byteLength>>8,o.set(n,2),o.set(t,2+n.byteLength),o}function x(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let o=n;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Q(r,"decodeVideoOutRecord");let i=e.subarray(2+t);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:i.slice()}}async function X(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),o=n.sessionId??e.sessionId;if(typeof o!="string"||o.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:o,stream:_,codec:I,framing:B}}var C="urun.videoOut.v2-ws";function Z(e){let t=e.stream(_);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${_}') 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,o=new Set,r=new Set,i=u=>{for(let d of o)d(u)},a=!1,c=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${_}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=x(u)}catch(l){i(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of r)u()};return{codec:I,onOutputFrame:u=>(n.add(u),a||(a=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function Le(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function ee(e,t,n){let o=n??(typeof globalThis.WebTransport=="function"?(d,l)=>new globalThis.WebTransport(d,l):void 0);if(!o)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let r=o(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:Le(d)}))});await r.ready;let i=await r.createBidirectionalStream();await i.writable.getWriter().write((0,w.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=i.readable.getReader(),c=new w.WtControlDecoder,u=!1;for(;!u;){let{value:d,done:l}=await a.read();if(l)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let f of c.push(d)){if(f.t==="hello-ack"){u=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await(0,w.consumeWtDataStreams)(r.incomingUnidirectionalStreams,{onData:(d,l)=>{if(d===e.stream){if(l===w.STREAM_END){t.onEnd?.();return}if(!(l instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(x(l))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:d=>t.onLaneError(d)})}var ne="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",H=1007,oe=1008,U=1011,re=1008,s=class extends Error{constructor(n,o=H){super(n);this.closeCode=o}closeCode},m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,L=["setup","clientContent","realtimeInput","toolResponse"];function ie(e){let t;try{t=JSON.parse(e)}catch{throw new s("client message is not valid JSON")}let n=m(t);if(!n)throw new s("client message must be a JSON object");let o=L.filter(c=>n[c]!==void 0),r=Object.keys(n).filter(c=>!L.includes(c));if(r.length>0)throw new s(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${L.join(", ")}`);if(o.length!==1)throw new s(`client message must contain exactly one of ${L.join(", ")} (got ${o.length})`);let i=o[0],a=m(n[i]);if(!a)throw new s(`"${i}" must be a JSON object`);return{kind:i,[i]:a}}function se(e,t){if(typeof e=="string")return e;let n=m(e),o=n?n.parts:void 0;if(!Array.isArray(o))throw new s(`${t}: expected a Content with a parts array`);let r=[];for(let i of o){let a=m(i);if(a&&typeof a.text=="string"){r.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new s(`${t}: 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`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new s(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new s(`${t}: unsupported part ${JSON.stringify(i)}`)}return r.join(`
|
|
2
|
-
`)}var Ue={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function ae(e){return{framing:C,codec:e}}function ue(e){let{seq:t,ptsUs:n,codec:o,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:n,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var De={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ve=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],te=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Me(e){let t=m(e);if(!t)throw new s("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new s(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new s("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new s(`automaticActivityDetection.${r} 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 s("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 o="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!te.includes(t.activityHandling))throw new s(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${te.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var Ne=["temperature","maxOutputTokens","responseModalities"];function de(e){for(let[f,p]of Object.entries(De))if(e[f]!==void 0)throw new s(p);for(let f of Object.keys(e))if(!Ve.includes(f))throw new s(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new s('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),n,o,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new s("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!Ne.includes(f))throw new s(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new s("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new s("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let f=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of f){let g=String(p).toUpperCase();if(g==="AUDIO"){r=!0;continue}if(g!=="TEXT")throw new s(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:se(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new s("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new s("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new s(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new s("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let h=m(g);if(!h||typeof h.name!="string")throw new s("functionDeclarations entries require a string name");c.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}c.length===0&&(c=void 0)}let u={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=m(e.sessionResumption);if(!f)throw new s("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new s(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new s("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?Ue:Me(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new s(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:n,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function ce(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function le(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function fe(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new s(`unsupported clientContent field "${o}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new s("clientContent.turns must be an array");let n=[];for(let o of t){let r=m(o);if(!r)throw new s("clientContent.turns entries must be Content objects");let i=r.role===void 0?"user":String(r.role).toLowerCase();if(i!=="user"&&i!=="model")throw new s(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:i==="model"?"assistant":"user",content:se(r,"clientContent.turns")})}return{items:n,turnComplete:e.turnComplete===!0}}var b=16e3,D=24e3,F=`audio/pcm;rate=${D}`,pe=Buffer.alloc(960).toString("base64");function j(e,t,n){if(t===n)return e;let o=Math.floor(e.length*n/t),r=new Int16Array(o),i=t/n,a=e.length-1;for(let c=0;c<o;c++){let u=c*i,d=Math.floor(u);if(d>=a){r[c]=e[a];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function Pe(e){let t=m(e);if(!t)throw new s("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new s("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function $e(e){let t=m(e);if(!t)throw new s("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(t.mimeType);if(n&&Number(n[1])!==b)throw new s(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length===0||o.length%2!==0)throw new s(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let a=0;a<r.length;a++)r[a]=o.readInt16LE(a*2);let i=j(r,b,D);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function me(e){if(e.mediaChunks!==void 0)throw new s('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new s("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",i=m(e[r]);if(!i||Object.keys(i).length!==0)throw new s(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!t.includes(o))throw new s(`unsupported realtimeInput field "${o}"`);let n=t.filter(o=>e[o]!==void 0);if(n.length!==1)throw new s(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${n.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:$e(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Pe(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new s("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new s("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function ge(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new s(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new s("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let n=m(t);if(!n||typeof n.id!="string"||n.id.length===0)throw new s("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 ye(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function we(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:F,data:e}}]}}}}function he(e){let t=m(e)??{},n=Array.isArray(t.output)?t.output:[],o=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of n){let l=m(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let f of l.content){let p=m(f);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&r.push({role:"assistant",content:i});for(let d of n){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new s(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,U);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new s(`upstream function_call arguments are not valid JSON: ${f}`,U)}o.push({id:l.call_id,name:l.name,args:p}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:f})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let c=m(t.usage),u={serverContent:{turnComplete:!0}};if(c){let d={};typeof c.input_tokens=="number"&&(d.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(d.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(d.totalTokenCount=c.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return a.push(u),{messages:a,assistantItems:r}}async function ke(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let o;await new Promise((r,i)=>{let a=e.onSynced(()=>{clearTimeout(o),r()});o=setTimeout(()=>{a(),i(new Error(`[urun] llm doc plane never synced within ${t}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)`))},t)})}function V(e,t,n,o){let r=e.response??{},i={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(i.instructions=r.instructions),Array.isArray(r.modalities)&&(i.modalities=r.modalities),typeof r.temperature=="number"&&(i.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(i.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(i.tools=r.tools),i}function M(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(o.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(o.response_format=e.response_format),typeof e.voice=="string"&&(o.voice=e.voice),typeof e.language=="string"&&(o.language=e.language),o}function _e(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},o=n.error,r=o?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:o?.type??"urun_error",code:t.code??o?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Be="llm-resp";async function*He(e,t){let n=`resp_${e}`,o=new Map;for await(let r of t){let i=r;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=o.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield _e(i);return}}}async function*A(e,t){let n=`${Be}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*He(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var P=class{constructor(t,n=15e3){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let o=M(t,n,this.consumerId);return this.write(o),A(this.session,n)})}sendResponseCreate(t,n,o){return this.writeGated(o,()=>{let r=V(t,n,o,this.consumerId);return this.write(r),A(this.session,o)})}async writeGated(t,n){try{await ke(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(o){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${o instanceof Error?o.message:String(o)}`)}return n()}};0&&(module.exports={AudioBridge,CLOSE_PROTOCOL,CLOSE_SESSION_GONE,CLOSE_UNKNOWN_MODEL,CLOSE_UPSTREAM,GEMINI_AUDIO_IN_RATE,GEMINI_AUDIO_OUT_MIME,GEMINI_AUDIO_OUT_RATE,GEMINI_LIVE_PATH,GeminiLiveError,NATIVE_AUDIO_SAMPLE_RATE,OUTBOUND_AUDIO_FLUSH_B64,RT_VIDEO_IN_STREAM,RT_VIDEO_OUT_STREAM,SdkTransport,VIDEO_FRAME_MESSAGE_BUDGET,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_SETUP_KEY,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeResponsesLane,decodeVideoOutRecord,enableSessionAudio,enableSessionVideo,encodeVideoOutRecord,goAwayMsg,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,parseClientMessage,resamplePcm16,responseCreateToEnvelope,responsesCreateToEnvelope,serverContentOfAudio,serverContentOfDelta,sessionResumptionUpdateMsg,translateClientContent,translateRealtimeInput,translateSetup,translateToolResponse,turnEndOfCompleted,videoOutAck,videoOutChunkMsg,weriftAudioBackend});
|
|
2
|
+
`)}var Ue={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function ae(e){return{framing:C,codec:e}}function ue(e){let{seq:t,ptsUs:n,codec:o,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:n,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var De={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ve=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],te=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Me(e){let t=m(e);if(!t)throw new s("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new s(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new s("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new s(`automaticActivityDetection.${r} 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 s("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 o="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!te.includes(t.activityHandling))throw new s(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${te.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var Ne=["temperature","maxOutputTokens","responseModalities"];function de(e){for(let[f,p]of Object.entries(De))if(e[f]!==void 0)throw new s(p);for(let f of Object.keys(e))if(!Ve.includes(f))throw new s(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new s('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),n,o,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new s("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!Ne.includes(f))throw new s(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new s("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new s("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let f=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of f){let g=String(p).toUpperCase();if(g==="AUDIO"){r=!0;continue}if(g!=="TEXT")throw new s(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:se(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new s("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new s("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new s(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new s("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let h=m(g);if(!h||typeof h.name!="string")throw new s("functionDeclarations entries require a string name");c.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}c.length===0&&(c=void 0)}let u={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=m(e.sessionResumption);if(!f)throw new s("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new s(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new s("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?Ue:Me(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new s(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:n,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function ce(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function le(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function fe(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new s(`unsupported clientContent field "${o}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new s("clientContent.turns must be an array");let n=[];for(let o of t){let r=m(o);if(!r)throw new s("clientContent.turns entries must be Content objects");let i=r.role===void 0?"user":String(r.role).toLowerCase();if(i!=="user"&&i!=="model")throw new s(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:i==="model"?"assistant":"user",content:se(r,"clientContent.turns")})}return{items:n,turnComplete:e.turnComplete===!0}}var b=16e3,D=24e3,F=`audio/pcm;rate=${D}`,pe=Buffer.alloc(960).toString("base64");function j(e,t,n){if(t===n)return e;let o=Math.floor(e.length*n/t),r=new Int16Array(o),i=t/n,a=e.length-1;for(let c=0;c<o;c++){let u=c*i,d=Math.floor(u);if(d>=a){r[c]=e[a];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function Pe(e){let t=m(e);if(!t)throw new s("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new s("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function $e(e){let t=m(e);if(!t)throw new s("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(t.mimeType);if(n&&Number(n[1])!==b)throw new s(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length===0||o.length%2!==0)throw new s(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let a=0;a<r.length;a++)r[a]=o.readInt16LE(a*2);let i=j(r,b,D);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function me(e){if(e.mediaChunks!==void 0)throw new s('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new s("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",i=m(e[r]);if(!i||Object.keys(i).length!==0)throw new s(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!t.includes(o))throw new s(`unsupported realtimeInput field "${o}"`);let n=t.filter(o=>e[o]!==void 0);if(n.length!==1)throw new s(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${n.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:$e(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Pe(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new s("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new s("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function ge(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new s(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new s("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let n=m(t);if(!n||typeof n.id!="string"||n.id.length===0)throw new s("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 ye(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function we(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:F,data:e}}]}}}}function he(e){let t=m(e)??{},n=Array.isArray(t.output)?t.output:[],o=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of n){let l=m(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let f of l.content){let p=m(f);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&r.push({role:"assistant",content:i});for(let d of n){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new s(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,U);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new s(`upstream function_call arguments are not valid JSON: ${f}`,U)}o.push({id:l.call_id,name:l.name,args:p}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:f})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let c=m(t.usage),u={serverContent:{turnComplete:!0}};if(c){let d={};typeof c.input_tokens=="number"&&(d.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(d.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(d.totalTokenCount=c.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return a.push(u),{messages:a,assistantItems:r}}async function ke(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let o;await new Promise((r,i)=>{let a=e.onSynced(()=>{clearTimeout(o),r()});o=setTimeout(()=>{a(),i(new Error(`[urun] llm doc plane never synced within ${t}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)`))},t)})}function V(e,t,n,o){let r=e.response??{},i={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(i.instructions=r.instructions),Array.isArray(r.modalities)&&(i.modalities=r.modalities),typeof r.temperature=="number"&&(i.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(i.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(i.tools=r.tools),i}function M(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(o.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(o.response_format=e.response_format),typeof e.voice=="string"&&(o.voice=e.voice),typeof e.language=="string"&&(o.language=e.language),o}function _e(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},o=n.error,r=o?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:o?.type??"urun_error",code:t.code??o?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Be="llm-resp";async function*He(e,t){let n=`resp_${e}`,o=new Map;for await(let r of t){let i=r;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=o.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield _e(i);return}}}async function*A(e,t){let n=`${Be}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*He(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var P=class{constructor(t,n=15e3,o){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=o===void 0?t.sessionId??globalThis.crypto.randomUUID():o}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let o=M(t,n,this.consumerId);return this.write(o),A(this.session,n)})}sendResponseCreate(t,n,o){return this.writeGated(o,()=>{let r=V(t,n,o,this.consumerId);return this.write(r),A(this.session,o)})}async writeGated(t,n){try{await ke(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(o){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${o instanceof Error?o.message:String(o)}`)}return n()}};0&&(module.exports={AudioBridge,CLOSE_PROTOCOL,CLOSE_SESSION_GONE,CLOSE_UNKNOWN_MODEL,CLOSE_UPSTREAM,GEMINI_AUDIO_IN_RATE,GEMINI_AUDIO_OUT_MIME,GEMINI_AUDIO_OUT_RATE,GEMINI_LIVE_PATH,GeminiLiveError,NATIVE_AUDIO_SAMPLE_RATE,OUTBOUND_AUDIO_FLUSH_B64,RT_VIDEO_IN_STREAM,RT_VIDEO_OUT_STREAM,SdkTransport,VIDEO_FRAME_MESSAGE_BUDGET,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_SETUP_KEY,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeResponsesLane,decodeVideoOutRecord,enableSessionAudio,enableSessionVideo,encodeVideoOutRecord,goAwayMsg,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,parseClientMessage,resamplePcm16,responseCreateToEnvelope,responsesCreateToEnvelope,serverContentOfAudio,serverContentOfDelta,sessionResumptionUpdateMsg,translateClientContent,translateRealtimeInput,translateSetup,translateToolResponse,turnEndOfCompleted,videoOutAck,videoOutChunkMsg,weriftAudioBackend});
|
package/dist/gemini-live.d.cts
CHANGED
|
@@ -116,7 +116,16 @@ declare class SdkTransport {
|
|
|
116
116
|
private readonly sessionTag;
|
|
117
117
|
constructor(session: UrunSessionLike,
|
|
118
118
|
/** Test seam for the gate deadline; never an env knob or config surface. */
|
|
119
|
-
docSyncTimeoutMs?: number
|
|
119
|
+
docSyncTimeoutMs?: number,
|
|
120
|
+
/**
|
|
121
|
+
* The conversation identity to stamp, or `null` for NONE. A shared lane
|
|
122
|
+
* carries MANY conversations: stamping the lane id made every request on
|
|
123
|
+
* the lane one "session", and the runtime's per-tag FIFO lock then ran
|
|
124
|
+
* them one at a time (prod-usw2 2026-10-26: 10 concurrent 27b requests
|
|
125
|
+
* completed 4.2 s apart while the engine could batch them). Absent ⇒
|
|
126
|
+
* the session id (one transport = one persistent session).
|
|
127
|
+
*/
|
|
128
|
+
sessionTag?: string | null);
|
|
120
129
|
get consumerId(): string;
|
|
121
130
|
private write;
|
|
122
131
|
sendResponses(params: {
|
package/dist/gemini-live.d.ts
CHANGED
|
@@ -70,7 +70,9 @@ declare class SdkTransport {
|
|
|
70
70
|
private readonly sessionTag;
|
|
71
71
|
constructor(session: UrunSessionLike,
|
|
72
72
|
|
|
73
|
-
docSyncTimeoutMs?: number
|
|
73
|
+
docSyncTimeoutMs?: number,
|
|
74
|
+
|
|
75
|
+
sessionTag?: string | null);
|
|
74
76
|
get consumerId(): string;
|
|
75
77
|
private write;
|
|
76
78
|
sendResponses(params: {
|
package/dist/gemini-live.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,b as C,c as L,d as M,e as R,f as D,g as f,h as N,i as v,j as g,k as x,l as k,m as y,n as G,o as B,p as F,q as P,r as H,s as W,t as b,u as w,v as K,w as h,x as Q}from"./chunk-3JWYIKHM.js";import{a as i,b as s,c as O,d,e as a,f as E,g as _,h as p,i as u,j as A,k as S,l as I,m as T,n as l,o as m,p as U,q as V}from"./chunk-6M5JK4YC.js";import{a as o,b as t,e as n,f as r}from"./chunk-
|
|
1
|
+
import{a as c,b as C,c as L,d as M,e as R,f as D,g as f,h as N,i as v,j as g,k as x,l as k,m as y,n as G,o as B,p as F,q as P,r as H,s as W,t as b,u as w,v as K,w as h,x as Q}from"./chunk-3JWYIKHM.js";import{a as i,b as s,c as O,d,e as a,f as E,g as _,h as p,i as u,j as A,k as S,l as I,m as T,n as l,o as m,p as U,q as V}from"./chunk-6M5JK4YC.js";import{a as o,b as t,e as n,f as r}from"./chunk-GX243AIV.js";import"./chunk-7KRHHEKZ.js";import{c as e}from"./chunk-YSFSRI3D.js";e();export{s as AudioBridge,C as CLOSE_PROTOCOL,R as CLOSE_SESSION_GONE,L as CLOSE_UNKNOWN_MODEL,M as CLOSE_UPSTREAM,B as GEMINI_AUDIO_IN_RATE,P as GEMINI_AUDIO_OUT_MIME,F as GEMINI_AUDIO_OUT_RATE,c as GEMINI_LIVE_PATH,D as GeminiLiveError,i as NATIVE_AUDIO_SAMPLE_RATE,H as OUTBOUND_AUDIO_FLUSH_B64,d as RT_VIDEO_IN_STREAM,u as RT_VIDEO_OUT_STREAM,r as SdkTransport,a as VIDEO_FRAME_MESSAGE_BUDGET,S as VIDEO_OUT_DEFAULT_CODEC,A as VIDEO_OUT_FRAMING,N as VIDEO_OUT_SETUP_KEY,m as VIDEO_OUT_WS_FRAMING,V as consumeVideoOut,n as decodeResponsesLane,T as decodeVideoOutRecord,O as enableSessionAudio,E as enableSessionVideo,I as encodeVideoOutRecord,y as goAwayMsg,l as negotiateSessionVideoOutQuic,p as nodeAudioBackend,U as openSessionVideoOutLane,f as parseClientMessage,W as resamplePcm16,o as responseCreateToEnvelope,t as responsesCreateToEnvelope,h as serverContentOfAudio,K as serverContentOfDelta,k as sessionResumptionUpdateMsg,G as translateClientContent,b as translateRealtimeInput,x as translateSetup,w as translateToolResponse,Q as turnEndOfCompleted,v as videoOutAck,g as videoOutChunkMsg,_ as weriftAudioBackend};
|