@urun-sh/openai 0.6.39 → 0.6.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-G7CSAISC.js +1 -0
- package/dist/chunk-HBKAN6PP.js +2 -0
- package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
- package/dist/{chunk-USLITFIB.js → chunk-ILYHXVNZ.js} +1 -1
- package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
- package/dist/chunk-PAAFRUQZ.js +64 -0
- package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
- package/dist/chunk-VVQSFACF.js +23 -0
- package/dist/chunk-Z3QCHKJB.js +1 -0
- package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
- package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +2 -2
- package/dist/gemini-live.d.ts +2 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -48
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +46 -46
- package/dist/hosted/index.d.cts +3 -3
- package/dist/hosted/index.d.ts +3 -3
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +56 -56
- package/dist/pooler/bin.cjs +10 -10
- package/dist/pooler/bin.js +25 -25
- package/dist/proxy/cli.cjs +51 -51
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +28 -28
- package/dist/proxy/index.d.cts +35 -5
- package/dist/proxy/index.d.ts +11 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
- package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
- package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
- package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
- package/package.json +3 -3
- package/dist/chunk-4XOYE4A7.js +0 -23
- package/dist/chunk-6M5JK4YC.js +0 -1
- package/dist/chunk-7IWRLQOZ.js +0 -64
- package/dist/chunk-DO6EIHE5.js +0 -2
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-HBKAN6PP.js";import{A as wt,B as bt,C as vt,D as _t,E as St,b as tt,d as nt,e as oe,j as rt,k as ot,m as it,n as at,o as lt,p as ct,q as dt,r as ut,s as ft,u as pt,v as ie,w as ht,x as gt,y as mt,z as yt}from"./chunk-PAAFRUQZ.js";import{a as et}from"./chunk-QTHFMDZY.js";import{a as At}from"./chunk-G7CSAISC.js";import{a as kt}from"./chunk-L4QBHSVY.js";import{l as st,m as se}from"./chunk-ILYHXVNZ.js";import{a as Lt,c as X,e as xe}from"./chunk-KKCUIOL4.js";import{a as Xe}from"./chunk-4NMMWAKD.js";import{b as qe,d as Ne}from"./chunk-GX243AIV.js";import{e as Qe,j as ne,n as Ze,o as re,p as Ie}from"./chunk-HPUX2H65.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as K,Gauge as ae,Histogram as le,Registry as fn,collectDefaultMetrics as pn}from"@prometheus-io/client";import{createServer as hn}from"http";var lo=9464,Ct="/metrics",ce="(other)",gn="(none)",mn=64,yn=128,wn=["/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",pt,gt,Qe],bn=new Set(wn);function vn(t){return bn.has(t)?t:ce}function _n(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var de=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?gn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,ce):(this.admitted.add(e),e):ce}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ue=class{registry=new fn;modelLabel=new de(mn);orgLabel=new de(yn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ae({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 K({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 le({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 le({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 K({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 K({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 K({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 mt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ae({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"},yt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},wt()/1e3)}}),this.labelCardinality=new ae({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 K({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 ae({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 le({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 le({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 K({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 K({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&&pn({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=vn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let c=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?ce:e.method,status_class:_n(e.status),stream:c,model:s,org:i}),this.duration.observe({lane:n,stream:c,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Pt(t){return hn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ct){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ct}
|
|
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 Nt}from"crypto";import{createServer as Sn}from"http";var ho=9465,kn="x-urun-key-id",En="x-urun-key-fingerprint",Rn="urun-ratelimit-bucket:",Ln="urun-ratelimit-tier:",Tt="anonymous",An=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Cn(t){return Nt("sha256").update(`${Rn}${t}`).digest("hex")}function Pn(t){return Nt("sha256").update(`${Ln}${t}`).digest("hex")}function Tn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return An.test(n)?n:null}function It(){return Sn((t,e)=>{let n=Tn(t.headers.authorization);e.setHeader(kn,n===null?Tt:Cn(n)),e.setHeader(En,n===null?Tt:Pn(n)),e.writeHead(200),e.end()})}L();import{createClientToken as Nn,ClientTokenError as In}from"@urun-sh/core";import{createPublicKey as On,verify as Un}from"crypto";var Ot="urun-session-gateway",xn="machine",$n=3e5;function Dn(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var I=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}},H=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function he(t){let e=(t??"").trim();if(e==="")throw new I("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 I("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Hn=60,Mn=6e4,Fn=4096;function Wn(t){return t===401||t===403}var fe=class{constructor(e){this.opts=e;this.mint=e.mint??Nn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new I("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Mn)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Hn});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof In&&Wn(s.status)?(this.cache.delete(e),new I("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new H("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new H("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>=Fn){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function Ut(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var pe=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<$n)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof H?i:new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new I("malformed machine token");let s,i;try{s=Ut(n),i=Ut(r)}catch{throw new I("malformed machine token")}if(s.alg!=="RS256")throw new I(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",c=typeof i.iss=="string"?i.iss:"";if(c===""||!this.opts.issuers.includes(c))throw new I(`machine token issuer is not one this endpoint accepts (${JSON.stringify(c)})`);if(i.aud!==Ot)throw new I(`machine token audience must be ${Ot} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==xn)throw new I(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new I("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new I("machine token is expired \u2014 re-mint and retry");let h=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,k=await this.jwksKeys(!1),v=a===""?void 0:k.find(w=>w.kid===a&&h(w));if(v===void 0&&(k=await this.jwksKeys(!0),v=a===""?void 0:k.find(w=>w.kid===a&&h(w))),v===void 0)throw new I(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),S=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),g=!1;try{let w=On({key:v,format:"jwk"});g=Un("RSA-SHA256",f,w,S)}catch{g=!1}if(!g)throw new I("machine token signature failed verification");return{apiKey:e,orgId:u,credential:"machine"}}};function $e(t,e,n){return n!==null&&Dn(t)?n.verify(t):e.resolve(t)}L();var Gn=8080,De="serve",So="0.0.0.0";function Kn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function ko(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Gn: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=st(se(Kn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?se(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let c=i?{catalogUrl:se(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let h=u?{keyId:d,key:u}:void 0,k={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()},v=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],f=v.filter((b,_)=>Object.values(k)[_]==="");if(f.length!==0&&f.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the lane plane`);let S=f.length===0?k:void 0,g={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],A=w.filter((b,_)=>Object.values(g)[_]==="");if(A.length!==0&&A.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${A.join(", ")}, which would half-configure the pooler cutover`);let E=A.length===0?g:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},m=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],C=m.filter((b,_)=>Object.values(p)[_]==="");if(C.length!==0&&C.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${C.join(", ")}, which would half-configure the machine-identity rung`);let T=p.issuers.split(",").map(b=>b.trim()).filter(b=>b!=="");if(T.length===0&&C.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 l=Number(p.tokenTtlS);if(C.length===0&&(!Number.isFinite(l)||l<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let y=C.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:T,tokenTtlS:l}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:c,ledgerSigning:h,lane:S,pooler:E,machine:y}}L();import{createHash as Qn,randomUUID as Ht}from"crypto";L();import{request as Bn}from"http";var jn="/pooler/v1/inference",B=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Jn=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)},Vn=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)}},$t=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)}),zn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await $t(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 B(t.status,e,n,t.retryAfterSeconds)};async function Yn(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${jn}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Jn(e),firstMessage:Vn(e)}});return new Promise((a,c)=>{let u=Bn({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let h=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:d})});u.on("error",d=>c(new B(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var xt=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*qn(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 s=e.slice(0,o);e=e.slice(o+2);let i=xt(s);i!==null&&(yield i)}let n=xt(e);n!==null&&(yield n)}async function Dt(t,e,n,r){let o=qe(e,n,r),s=o.model??"";if(s==="")throw new B(400,"missing_model","the pooler submit requires a model");let i=await Yn(t,o,n,s,e.stream===!0);if(i.status>=400)throw await zn(i);let a=e.stream===!0?Ne(n,qn(i)):await Xn(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Xn(t,e){let n=await $t(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new B(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Ne(e,(async function*(){yield o})())}var Zn=512;function ge(t){return`urun-inference-proxy-${Qn("sha256").update(t).digest("hex").slice(0,32)}`}var me=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,c)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,c);let u=`px_${Ht()}`;return Dt(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:De,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:Et(process.env,process.env.HOSTNAME)??void 0},r=Oe(n),o=n.decisionPool?Rt(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Ue(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[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Mt=512,er=1024,ye=class extends Error{constructor(){super(`conversation capacity reached (${Mt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function tr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(re))return{concurrencyKey:e};if(n.startsWith(re)||n.startsWith(Ie))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(re)||n.startsWith(Ie)||t.set(n,r)}}}function nr(t,e,n,r,o){let s=Oe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:De,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",...tr(r,o)});return{clients:Ue(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var we=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${ge(e.apiKey)}:live`:`${ge(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):nr(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Mt;){let e=this.byCaller.keys().next();if(e.done)throw new ye;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new ye;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,Ht(),n)),r),i={createResponse:(a,c)=>s().backhaul.clients.createResponse(a,c),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let c=s().backhaul.clients.servingAppSlug;if(c===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 c(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let c=s().backhaul.clients.dedicatedSessionHandle;return c===void 0?s().backhaul.clients.sessionHandle(a):c(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,c,u)=>s().backhaul.clients.createResponseOn(a,c,u),onSessionEnd:(a,c)=>s().backhaul.clients.onSessionEnd(a,c)};return i.openAudio=async(a,c)=>{let u=s().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(a,c)},i.openVideo=async a=>{let c=s().backhaul.clients.openVideo;if(c===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return c(a)},i.openVideoOut=async a=>{let c=s().backhaul.clients.openVideoOut;if(c===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return c(a)},i.supportsAudio=async a=>{let c=s().backhaul.clients.supportsAudio;if(c===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return c(a)},i.supportsSpeech=async a=>{let c=s().backhaul.clients.supportsSpeech;if(c===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return c(a)},i.speechVoices=async a=>{let c=s().backhaul.clients.speechVoices;if(c===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 c(a)},i.speechSessionHandle=async a=>{let c=s().backhaul.clients.speechSessionHandle;if(c===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 c(a)},i.openAudioOn=async(a,c,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,c,u)},i.openVideoOn=async(a,c)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,c)},i.openTurnsOn=(a,c)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,c)},i.evictSpeechSession=async a=>{let c=s().backhaul.clients.evictSpeechSession;if(c===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 c(a)},i.supportsTranscription=async a=>{let c=s().backhaul.clients.supportsTranscription;if(c===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return c(a)},i.transcriptStreamFor=async a=>{let c=s().backhaul.clients.transcriptStreamFor;if(c===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 c(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let c=r;if(c===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=er;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:c.id})},clientsForResume:async a=>{let c=this.byHandle.get(a),u=c===void 0?void 0:this.byCaller.get(c.apiKey),d=c===void 0||u===void 0?void 0:u.get(c.conversationId);if(c===void 0||d===void 0||c.apiKey!==e.apiKey)throw new ne("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var rr="/inference-ledger",or=1e4,be=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Fe=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},$=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},We=class extends I{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ge=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},sr=[["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",He],["output_minutes",He],["cost_nano_usd",He],["price_version",t=>t===null||typeof t=="string"]];function ir(t){for(let[e,n]of sr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function ar(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"}:ir(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function He(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Me(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function lr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ft(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 cr(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&&Ft(t.started_at,n.started_at)&&Ft(t.completed_at,n.completed_at)&&Me(t.prompt_tokens,n.prompt_tokens)&&Me(t.completion_tokens,n.completion_tokens)&&Me(t.output_units,n.output_units)&&lr(t.output_minutes,n.output_minutes)}function dr(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 ur(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(dr(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function fr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new $(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new $(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new $(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new $(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new $(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new $(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new $(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),c=o!=null;if(c&&(i===null||a!==null))throw new $(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!c&&(i!==null||a===null))throw new $(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var ve=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${rr}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ur(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new $(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(or)})}catch(u){throw new $(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=ar(u);throw d.status==="found"&&cr(n,d.row)?new Fe(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 be(`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 be(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new We("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let u=await s.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),d;try{let h=JSON.parse(u);if(h!==null&&typeof h=="object"&&"error"in h){let k=h.error;k!==null&&typeof k=="object"&&"code"in k&&(d=k.code)}}catch{}throw d==="ledger_signature_invalid"?new Ge(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new $(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new $(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new $(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let c=fr(a,`the uRun ledger surface at ${r}`);if(c.inference_id!==n.inference_id)throw new $(`the uRun ledger surface at ${r} answered for inference_id ${c.inference_id} when asked about ${n.inference_id}`);return c}};L();import{createServer as Vr}from"http";L();import{SessionAllocationError as Er}from"@urun-sh/core";import{createWebsocketDocConnector as Rr}from"@urun-sh/core/internal";import Lr from"ws";L();import{request as pr}from"http";var hr="/pooler/v1/lanes/pick",gr="/pooler/v1/lanes/status",mr=1e4,Z=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function Wt(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),c=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=pr({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...c===void 0?{}:{"content-type":"application/json","content-length":String(c.byteLength)}},timeout:o},d=>{let h=[];d.on("data",k=>h.push(k)),d.on("end",()=>{let k=Buffer.concat(h).toString("utf8"),v=null;try{v=k===""?null:JSON.parse(k)}catch{v=null}s({status:d.statusCode??0,json:v})}),d.on("error",i)});u.on("timeout",()=>{u.destroy(new Z(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",i),u.end(c)})}function Gt(t,e,n){if(t===503)return new oe(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 Kt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=Math.min(Math.max(Math.trunc(r),0),At),s=await Wt(t,"POST",hr,{pool:e,model:n,hold_ms:o},o+mr);if(s.status!==200)throw Gt(s.status,s.json,e);return(s.json?.lanes??[]).filter(a=>typeof a.lane_id=="string"&&a.lane_id!==""&&typeof a.host=="string"&&a.host!=="").map(a=>({laneId:a.lane_id,host:a.host}))},async status(){let e=await Wt(t,"GET",gr,void 0,5e3);if(e.status!==200)throw Gt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import*as j from"yjs";import{SessionDocumentImpl as yr}from"@urun-sh/core/internal";var wr=3e4;function br(t){return(e,n,r)=>{let o=t(e);j.applyUpdate(n,j.encodeStateAsUpdate(o));let s=a=>j.applyUpdate(o,a),i=a=>j.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ke(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?br(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=r.get(d);return h||(h=new yr(d,e,n),r.set(d,h)),h},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=i.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),i.set(d,h)}return h},c=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*k(){let v=a(d);try{yield*v.messages()}finally{i.delete(d),await v.close()}}return{messages:()=>k(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:c,streamEndpoint:a,async end(){},async whenLive(d){let h=s("llm");if(h.synced===!0)return;let k=d?.timeout??t.whenLiveTimeoutMs??wr;await new Promise((v,f)=>{let S=setTimeout(()=>{g(),f(new Error(`lane ${e} llm doc never synced within ${k}ms`))},k),g=h.onSynced(()=>{clearTimeout(S),d?.signal?.removeEventListener("abort",w),v()}),w=()=>{clearTimeout(S),g(),f(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",w,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,h]of i)i.delete(d),h.close()}}}L();import _e,{WebSocketServer as vr}from"ws";import{ENVELOPE_KIND as zt,STREAM_END as _r,StreamFragmentReassembler as Sr}from"@urun-sh/core";var Bt="/stream/";function jt(t){if(!t.startsWith(Bt))return null;let e=t.slice(Bt.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 Ee(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Se(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>zt.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var ke=class{reassembler=new Sr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===_r&&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})}}},je=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=Jt||a.bytes+o.byteLength>Vt)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Jt} frames / ${Vt} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,c)=>a+c.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Jt=256,Vt=8*1024*1024,M=new je;function Yt(t,e){let n=new ke,r={send(o){M.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Se(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),M.detach(t,e,r)}};return M.attach(t,e,r),r}function kr(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 qt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new _e(r,Ee(e)),s=new ke;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Se(a)}catch(c){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(c)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Se(i),o.readyState!==_e.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Be(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 Xt(t,e){let n=e.heartbeatMs??3e4,r=new vr({noServer:!0,handleProtocols:(u,d)=>{let h=jt(new URL(d.url??"/","http://localhost").pathname);if(!h)return!1;let k=Ee(h.name);return u.has(k)?k:!1}}),o=new Map,s=new Set,i=!1,a=(u,d,h,k)=>{let v={client:h,upstream:k,laneId:u,name:d};s.add(v);let f=S=>{if(s.delete(v)){console.warn(`[lane-stream] ${u}/${d}: host-affinity pump torn down (${S})`);for(let g of[h,k])try{(g.readyState===_e.OPEN||g.readyState===_e.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let S=(g,w)=>{let A=!0;g.on("pong",()=>{A=!0});let E=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${u}/${d}: pong timeout on ${w} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${w} dial never sends a close)`),clearInterval(E);try{g.terminate()}catch{}f(`${w} pong timeout`);return}A=!1;try{g.ping()}catch{}},n);E.unref?.();let p=()=>clearInterval(E);g.once("close",p),g.once("error",p)};S(h,"client"),S(k,"host")}h.on("message",S=>{try{k.send(S,{binary:!0})}catch(g){f(`upstream send failed: ${String(g)}`)}}),k.on("message",S=>{try{h.send(S,{binary:!0})}catch(g){f(`client send failed: ${String(g)}`)}}),h.on("close",()=>f("client socket closed")),h.on("error",()=>f("client socket error")),k.on("close",()=>f("host socket closed")),k.on("error",()=>f("host socket error"))},c=(u,d,h)=>{let k;try{k=new URL(u.url??"/","http://localhost")}catch{Be(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let v=jt(k.pathname);v&&(i||d.destroyed||(async()=>{let f=k.searchParams.get("token")??"",S=null;try{S=f===""?null:await e.verifyToken(f,v.laneId,v.name)}catch{S=null}if(S===null){Be(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(v.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let w=await e.podToPodDial(v.laneId,v.name,g);r.handleUpgrade(u,d,h,A=>{a(v.laneId,v.name,A,w)});return}catch(w){console.warn(`[lane-stream] ${v.laneId}/${v.name}: host dial to ${g} failed (${String(w)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(u,d,h,g=>{let w=kr(g);if(o.set(g,w),M.attach(v.laneId,v.name,w),n>0){let E=!0;g.on("pong",()=>{E=!0});let p=setInterval(()=>{if(!E){console.warn(`[lane-stream] ${v.laneId}/${v.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(p),g.terminate();return}E=!1;try{g.ping()}catch{}},n);p.unref?.();let m=()=>clearInterval(p);g.once("close",m),g.once("error",m)}g.on("message",E=>{let p=new Uint8Array(E);try{Se(p)}catch(m){console.warn(`[lane-stream] ${v.laneId}/${v.name}: dropped malformed envelope: ${String(m)}`);return}M.deliver(v.laneId,v.name,w,p),p[1]===zt.END&&M.detach(v.laneId,v.name,w)});let A=()=>{o.delete(g),M.detach(v.laneId,v.name,w)};g.on("close",A),g.on("error",A)})})().catch(()=>{d.destroyed||Be(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",c),{async close(){i=!0,t.off("upgrade",c),M.clear();for(let u of o.values())u.close(1001,"lane stream host shutting down");o.clear();for(let u of s)for(let d of[u.client,u.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}function Ar(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new nt(`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 Qt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(f,S,g,w,A,E)=>{let p=g?l=>Yt(f,l):l=>qt(f,l,{hostUrl:`ws://${w}/stream/${f}`,token:()=>X(f,t.tokenSecret,void 0,void 0,E)}),m=g?Ke({laneId:f,roomDoc:l=>t.roomDoc(f,l),streamEndpoint:p}):Ke({laneId:f,streamEndpoint:p,connector:Rr({serverUrl:`ws://${w}/doc`,sessionId:f,token:()=>X(f,t.tokenSecret,void 0,void 0,E),WebSocketPolyfill:Lr})}),C=g?c(f):kt(m,`lane:${f}`,{armOnFirstSync:!0}),T={session:m,responses:new Xe(m,{sessionTag:null}),gone:C,goneWatch:C,laneId:f,pool:S,inFlight:0,laneSession:m,self:g,host:w??"",mintedRelease:A??"",retireWhenIdle:!1};return n.set(f,T),C.onGone(()=>u(T)),T},c=f=>{let S=null,g=!1,w=new Set,A=p=>{if(!S){S=p;for(let m of[...w])m(p);w.clear()}},E=t.hostedSignal?.(f,p=>{if(p){g=!0;return}g&&A(new ne(`the lane ${f} 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:()=>S,onGone(p){return S?(p(S),()=>{}):(w.add(p),()=>w.delete(p))},dispose(){E?.(),w.clear()}}},u=f=>{d(f)&&(n.delete(f.laneId),r.delete(f.laneId),f.goneWatch?.dispose(),M.forgetLane(f.laneId))},d=f=>{let S=f.laneId;return typeof S=="string"&&n.get(S)===f},h=f=>{d(f)&&(f.self&&!t.closeLane||(i.add(f.laneId),f.self&&t.closeLane?.(f.laneId),u(f)))},k=(f,S)=>{throw t.metrics?.observeLane503Fast(S??""),s.set(f,e()),new oe(f)},v=async(f,S)=>{let g=Ar(S);o.add(g);let w=e();try{let A=await t.laneWarmWaitMsFor?.(f,S)??t.laneColdWakeDefaultMs??0,E;try{E=await t.plane.pick({pool:g,model:f,holdMs:A})}catch(y){throw y instanceof Z?new Er(`lane pick hold expired for ${g}: ${y.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):y}t.metrics?.observeLaneReady(f??"",E.length);let p=await t.currentReleaseOf?.(S)??null,m=new Set(E.map(y=>y.laneId));for(let y of i)m.has(y)||i.delete(y);let T=E.filter(y=>{let b=n.get(y.laneId);return b!==void 0&&p!==null&&b.mintedRelease!==""&&b.mintedRelease!==p&&(b.retireWhenIdle=!0,b.inFlight===0)?(h(b),!1):!i.has(y.laneId)}).map(y=>({laneId:y.laneId,self:y.host===t.selfAddress,host:y.host})).sort((y,b)=>y.self!==b.self?y.self?-1:1:(r.get(y.laneId)??0)-(r.get(b.laneId)??0))[0];T||k(g,f);let l=n.get(T.laneId);return l?.goneWatch?.gone()&&(u(l),l=void 0),l&&(l.pool!==g||l.self!==T.self||l.host!==T.host)&&(u(l),l=void 0),l||(l=a(T.laneId,g,T.self,T.host,p,S.sharedOrgId??void 0)),l.inFlight+=1,r.set(T.laneId,(r.get(T.laneId)??0)+1),{app:g,entry:l,identity:{kind:"catalog",model_id:S.modelId??f??"",variant:S.variant??""}}}finally{t.metrics?.observeLanePick(f??"",e()-w)}};return{sessionFor(f,S){return v(f,S)},release(f){d(f)&&(f.inFlight=Math.max(0,f.inFlight-1),r.set(f.laneId,f.inFlight),f.inFlight===0&&f.retireWhenIdle&&h(f))},owns(f){return d(f)},entryFor(f){return n.get(f)??null},evict(f){d(f)&&(f.gone.dispose(),n.delete(f.laneId),r.set(f.laneId,0),f.laneSession.destroy())},async status(){let f=[...new Set([...o,...[...n.values()].map(w=>w.pool)])].sort(),S=await t.plane.status().catch(()=>[]),g=new Map(Cr(S));return Promise.all(f.map(async w=>{let A=g.get(w)??{pool:w,lanes:[],lastDemandAt:null};return{pool:w,lanes:A.lanes,lastDemandAt:A.lastDemandAt,local:[...n.values()].filter(E=>E.pool===w).map(E=>({laneId:E.laneId,inFlight:E.inFlight,self:E.self,host:E.host})),lastRefusalAt:s.get(w)??null}}))},async close(){for(let f of n.values())f.gone.dispose(),f.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(f=>({pool:f.pool,laneId:f.laneId,inFlight:f.inFlight}))}}}function Cr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();var Pr="urun:node-scheduler:apps:v1";function Tr(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Zt(t){return async e=>{let n=Tr(e);if(n===null)return null;try{let r=await t.hget(Pr,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}L();import{WebSocketServer as Gr}from"ws";L();import*as tn from"yjs";import*as z from"y-protocols/sync";import*as W from"y-protocols/awareness";import*as N from"lib0/encoding";import*as Y from"lib0/decoding";import*as nn from"lib0/map";import Ir from"lodash.debounce";L();var en=()=>{};var Or=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Ur=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,xr=0,$r=1;var Dr=process.env.GC!=="false"&&process.env.GC!=="0",Hr=process.env.YPERSISTENCE,Re=null;if(typeof Hr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var V=new Map,Le=0,Ve=1,Mr=(t,e,n)=>{let r=N.createEncoder();N.writeVarUint(r,Le),z.writeUpdate(r,t);let o=N.toUint8Array(r);n.conns.forEach((s,i)=>ee(n,i,o))},Je=class extends tn.Doc{constructor(e){super({gc:Dr}),this.name=e,this.conns=new Map,this.awareness=new W.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(h=>{d.add(h)}),s.forEach(h=>{d.delete(h)}))}let c=N.createEncoder();N.writeVarUint(c,Ve),N.writeVarUint8Array(c,W.encodeAwarenessUpdate(this.awareness,a));let u=N.toUint8Array(c);this.conns.forEach((d,h)=>{ee(this,h,u)})};this.awareness.on("update",n),this.on("update",Mr),!1}},ze=(t,e=!0)=>nn.setIfUndefined(V,t,()=>{let n=new Je(t);return n.gc=e,Re!==null&&Re.bindState(t,n),V.set(t,n),n}),Fr=(t,e,n)=>{try{let r=N.createEncoder(),o=Y.createDecoder(n);switch(Y.readVarUint(o)){case Le:N.writeVarUint(r,Le),z.readSyncMessage(o,r,e,t),N.length(r)>1&&ee(e,t,N.toUint8Array(r));break;case Ve:{W.applyAwarenessUpdate(e.awareness,Y.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},J=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),W.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Re!==null&&(Re.writeState(t.name,t).then(()=>{t.destroy()}),V.delete(t.name))}e.close()},ee=(t,e,n)=>{e.readyState!==xr&&e.readyState!==$r&&J(t,e);try{e.send(n,r=>{r!=null&&J(t,e)})}catch{J(t,e)}},Wr=3e4,rn=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=ze(n,r);o.conns.set(t,new Set),t.on("message",a=>Fr(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&J(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{J(o,t),clearInterval(i)}}},Wr);t.on("close",()=>{J(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=N.createEncoder();N.writeVarUint(a,Le),z.writeSyncStep1(a,o),ee(o,t,N.toUint8Array(a));let c=o.awareness.getStates();if(c.size>0){let u=N.createEncoder();N.writeVarUint(u,Ve),N.writeVarUint8Array(u,W.encodeAwarenessUpdate(o.awareness,Array.from(c.keys()))),ee(o,t,N.toUint8Array(u))}}};var Ye="/doc/",sn=30,Kr=1e4,on="llm";function Br(t){if(!t.startsWith(Ye))return null;let e=t.slice(Ye.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 an(t,e){let n=new Gr({noServer:!0}),r=new Set,o=new Map,s=new Map,i=p=>o.get(`${p}/${on}`)??0,a=p=>s.get(p)??0,c=new Map,u=new Map,d=new Set,h=new Set,k=new Map,v=new Map,f=4096,S=!1,g=(p,m,C)=>{let T=i(p)>0,l=a(p),y=l>0,b=`${p}/${m}`,_=o.get(b)??0;C>0?o.set(b,C):o.delete(b);let R=l+C-_;R>0?s.set(p,R):s.delete(p);let P=i(p)>0,O=R>0;if(T!==P){P?w(p):A(p);for(let D of c.get(p)??[])D(P)}y&&!O&&queueMicrotask(()=>{let D=`${p}/`;for(let[F,G]of[...V.entries()])!F.startsWith(D)||G.conns.size>0||(V.delete(F),G.destroy())})},w=p=>{if(!e.hostRegistry||u.has(p))return;let m=()=>{e.hostRegistry?.setHost(p,e.selfAddress).catch(()=>{})};m();let C=setInterval(m,Kr);C.unref?.(),u.set(p,C)},A=p=>{let m=u.get(p);m&&(clearInterval(m),u.delete(p)),e.hostRegistry&&e.hostRegistry.delHost(p,e.selfAddress).catch(()=>{})},E=(p,m,C)=>{let T;try{T=new URL(p.url??"/","http://localhost")}catch{q(m,400,"malformed upgrade URL");return}m.on("error",()=>m.destroy()),m.on("close",()=>h.delete(m));let l=Br(T.pathname);if(!l){if(T.pathname.startsWith(Ye)){q(m,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(m);return}d.add(m);let y=!1;(async()=>{if(v.has(l.laneId)){q(m,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let b=T.searchParams.get("token")??"",_=null;try{_=b===""?null:await e.verifyToken(b,l.laneId,l.docName)}catch{_=null}if(_===null){q(m,401,"invalid or missing lane doc token");return}let R=_;if(R.tenant!==void 0&&e.laneTenantOf){let P=null;try{P=await e.laneTenantOf(l.laneId)}catch{P=null}if(P==null||P==="")e.onLaneTenantMissing?.();else if(R.tenant!==P){q(m,403,"lane doc token org does not match the lane record");return}}S||m.destroyed||(y=!0,n.handleUpgrade(p,m,C,P=>{d.delete(m),r.add(P),P.on("close",()=>r.delete(P));let O=k.get(l.laneId);O||(O=new Set,k.set(l.laneId,O)),O.add(P),P.on("close",()=>{O.delete(P),O.size===0&&k.delete(l.laneId)});let D=R.scope===Lt||R.scope===void 0&&typeof R.app=="string"&&typeof R.fn=="string"&&R.aud==="sfu";if(D){let G=`${l.laneId}/${l.docName}`,te=(o.get(G)??0)+1;g(l.laneId,l.docName,te),te>1&&l.docName===on&&e.hostRegistry?.setHost(l.laneId,e.selfAddress).catch(()=>{})}P.on("close",()=>{if(!D)return;let G=`${l.laneId}/${l.docName}`;g(l.laneId,l.docName,Math.max(0,(o.get(G)??1)-1))}),rn(P,p,{docName:`${l.laneId}/${l.docName}`,gc:!0})}))})().catch(()=>{!y&&!m.destroyed&&q(m,500,"lane doc upgrade failed")}).finally(()=>d.delete(m))};return t.on("upgrade",E),{async close(){S=!0,t.off("upgrade",E);for(let m of[...u.keys()])A(m);await new Promise(m=>{if(r.size===0&&d.size===0){m();return}let C=r.size+d.size,T=()=>{C-=1,C<=0&&m()};for(let l of r)l.once("close",T);for(let l of d)l.once("close",T);for(let l of r)l.close(1001,"lane doc host shutting down");for(let l of d)l.destroy()}),o.clear(),s.clear(),c.clear()},roomDoc(p,m){return ze(`${p}/${m}`,!0)},isHosted(p){return i(p)>0},onHostedChange(p,m){let C=c.get(p);return C||(C=new Set,c.set(p,C)),C.add(m),m(i(p)>0),()=>{C.delete(m)}},closeLane(p){if(v.set(p,!0),v.size>f){let m=v.keys().next().value;m!==void 0&&v.delete(m)}A(p);for(let m of k.get(p)??[])m.close(1001,`lane ${p} retired \u2014 the app's release moved`)}}}import zr from"ws";L();var jr="urun:catalog:v1";function ln(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let c=await t.redis.hgetall(jr),u=[];for(let d of Object.values(c))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
19
|
+
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}import Yr from"ioredis";L();var Ae="/inference-usage",cn=25e3;var Jr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function dn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Jr.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 Ce=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ae}`,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(cn)})}catch(i){throw new ie(`the uRun usage surface (POST ${Ae}) could not be reached within ${cn}ms: ${dn(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new I("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new ie(`the uRun usage surface (POST ${Ae}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new ie(`the uRun usage surface (POST ${Ae}) answered HTTP ${o.status} with a body that is not JSON: ${dn(i)}`)}return ht(s,this.opts.onRejectedRow)}};var qr=5e3,Xr=1e3,Qr=1500,Zr=3e3,eo="/api/client-tokens";function Pe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function un(t,e,n,r){Pe(t,e,{error:{message:n,type:r}})}async function to(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${eo}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Zr)});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 ni(t){let e=t.resolver??new fe({gatewayUrl:t.baseUrl}),n=t.machine?new pe({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ue(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let l=new Yr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=ln({redis:l});return{registry:Qt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Kt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(_,R)=>o?.onHostedChange(_,R)??(()=>()=>{}),roomDoc:(_,R)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(_,R)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(_,R)=>y.rows().then(P=>{let O=Ze(P,R);return O?.warm_wait_s!==void 0?O.warm_wait_s*1e3:void 0}),currentReleaseOf:Zt(l),closeLane:_=>o?.closeLane(_)}),catalog:y,redis:l}})(),a=t.registry??new me({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),c=t.probeControlPlane??(()=>to(t.baseUrl)),u=async()=>{let l=null;for(let _ of a.decisionPools()){l=_;break}if(!l)return null;let y=l.stats();if(y.some(_=>_.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(_=>_.attached===0&&_.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await l.pingReady(Qr);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new Ce({apiUrl:t.apiUrl}),h=t.ledgerClient??new ve({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),k=process.env.URUN_SHARED_ORG_ID?.trim(),v=process.env.URUN_SHARED_ORG_API_KEY?.trim();k&&v&&(async()=>{try{await a.decisionWarmerFor({orgId:k,apiKey:v})?.warmFor(_t)}catch(l){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(l instanceof Error?l.message:l)}
|
|
20
|
+
`)}})();let f=async l=>$e(he(l.headers.authorization),e,n),S=async l=>{let y=await f(l);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let b=y.creditsRefusalReason;throw new Q(b==="spend_cap_reached"||b==="insufficient_credits"?b:void 0)}return y},g=l=>l instanceof I?{status:l.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:l instanceof Q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...l.code!==void 0?{code:l.code}:{}}:l instanceof H?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:l.detail}:null,w=St({clients:async l=>a.clientsFor(await S(l)),usage:{authorize:l=>he(l.headers.authorization),lookup:(l,y)=>d.lookup(l,y)},statusOf:g,...t.requestLog?{requestLog:t.requestLog}:{},observe:l=>r.observe(l),ledger:{write:(l,y)=>h.write(he(l.headers.authorization),y),observe:l=>r.observeLedger(l),...t.ledgerLog?{report:t.ledgerLog}:{}}}),A=null,E=null,p=Vr((l,y)=>{let b=new URL(l.url??"/","http://localhost");(async()=>{if(l.method==="GET"&&b.pathname==="/healthz"){Pe(y,200,{ok:!0});return}if(l.method==="GET"&&b.pathname==="/readyz"){let P=Date.now();if((!A||P-A.at>=qr)&&(A={at:P,...await c()}),!E||P-E.at>=Xr){let F=await u();E=F===null?{at:P,ok:!0,detail:null}:{at:P,ok:F.ok,detail:F.detail}}let O=(A?.ready??!1)&&E.ok,D=E.detail===null?A?.detail??"control plane not yet probed":`${A?.detail??"control plane not yet probed"}; ${E.detail}`;Pe(y,O?200:503,{ok:O,control_plane:D});return}if(l.method==="GET"&&b.pathname==="/lanez"){Pe(y,200,{pools:i?await i.registry.status():null});return}let _=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),R=b.pathname.startsWith("/partners/");if(!_&&!R){un(y,404,`no route for ${l.method} ${b.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}w(l,y)})().catch(_=>{if(!y.headersSent){un(y,500,String(_ instanceof Error?_.message:_),"proxy_error");return}y.end()})}),m=t.conversations??new we({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),C=[tt(p,{authenticate:async l=>{let y=await $e(l,e,n),b=m.connectionFor(y);return{clients:b.clients,scope:ge(y.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),ot(p,{clients:async l=>a.clientsFor(await S(l)),statusOf:g}).close,at(p,{resolver:{resolve:async(l,y)=>{let b=await S(l),_=m.connectionFor(b,ut(l)),R;try{R=await ft(lt(_.clients,t.realtimeCompanions),ct(l),y,dt(l))}catch(O){throw _.release().catch(()=>{}),O}let P=R.release;return{...R,release:async()=>{await P?.(),await _.release()}}}}})];if(t.lane&&i){let l=t.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=an(p,{verifyToken:(_,R)=>xe(_,R,l.tokenSecret,void 0,y),selfAddress:l.selfAddress,laneTenantOf:_=>i.redis.get(`lane_tenant:${_}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(_,R)=>i.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${_}`,R,String(sn)),delHost:_=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${_}`,l.selfAddress)}}),s=Xt(p,{verifyToken:(_,R)=>xe(_,R,l.tokenSecret,void 0,y),selfAddress:l.selfAddress,hostOf:async _=>{let R=await i.redis.get(`lane_hosts:${_}`);return R&&R.trim()!==""?R.trim():null},podToPodDial:(_,R,P)=>new Promise((O,D)=>{(async()=>{let F=await i.redis.get(`lane_tenant:${_}`),G=X(_,l.tokenSecret,void 0,void 0,F||void 0),te=`ws://${P}/stream/${encodeURIComponent(_)}/${encodeURIComponent(R)}?token=${encodeURIComponent(G)}`,Te=new zr(te,Ee(R));Te.once("open",()=>O(Te)),Te.once("error",D)})().catch(D)})});let b=i;C.push(async()=>{await o.close(),await s.close(),await b.registry.close(),b.redis.quit().catch(()=>{})})}p.on("upgrade",(l,y)=>{let b=new URL(l.url??"/","http://localhost");b.pathname===et||b.pathname===rt||b.pathname===it||o!==null&&b.pathname.startsWith("/doc/")||s!==null&&b.pathname.startsWith("/stream/")||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
|
|
21
|
+
Connection: close\r
|
|
22
|
+
\r
|
|
23
|
+
no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let T=async()=>{for(let l of C)await l();await m.detachAll()};return{server:p,metricsServer:Pt(r),metrics:r,edgeIdentityServer:It(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:T}}async function ri(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await bt()||vt(),await e()}export{lo as a,Ct as b,ce as c,gn as d,mn as e,yn as f,vn as g,_n as h,de as i,ue as j,Pt as k,ho as l,kn as m,En as n,Rn as o,Ln as p,Tt as q,Cn as r,Pn as s,Tn as t,It as u,I as v,H as w,he as x,Mn as y,Fn as z,fe as A,Gn as B,De as C,So as D,ko as E,Zn as F,ge as G,me as H,Mt as I,er as J,ye as K,we as L,rr as M,or as N,be as O,$ as P,fr as Q,ve as R,qr as S,Zr as T,ni as U,ri as V};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as m}from"./chunk-YSFSRI3D.js";m();var W=24e3,g="audio",w=class{constructor(t,r){this.backend=t;this.opts=r}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(t){this.dataEmit=t}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(t,"base64"),n=Math.floor(r.byteLength/2),i=new Int16Array(n);for(let a=0;a<n;a++)i[a]=r.readInt16LE(a*2);this.source.onData(i),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(a=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(a instanceof Error?a.message:String(a)))}))}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=r=>{let n=Buffer.from(r.samples.buffer,r.samples.byteOffset,r.samples.byteLength).toString("base64");for(let i of this.outHandlers)i(n)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function F(e,t,r=1e4){let n=new w(t,{sampleRate:24e3}),i=await n.startOutbound(),a=e.stream(g);await a.attach(i),typeof a.emit=="function"&&n.setDataEmit(u=>a.emit(u));let d=await T(e,r);return await n.startInbound(d),n}function T(e,t){let r=e.stream(g);return r.track!=null?Promise.resolve(r.track):new Promise((n,i)=>{let a,d=setTimeout(()=>{a?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),u=o=>{o!=null&&(clearTimeout(d),a?.(),n(o))};a=r.on?.("track",u),r.track!=null&&u(r.track)})}var h="rt-video-in",y=256e3;function H(e){let t=e.stream(h),r=t.emit;if(typeof r!="function")throw new Error(`enableSessionVideo: session.stream('${h}') 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 n=>{if(n.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(n.byteLength>y)throw new Error(`enableSessionVideo: frame is ${n.byteLength} bytes \u2014 over the ${y}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await r.call(t,n)}}}var V=24e3,l=480,I=111;async function L(){let e=await import("opusscript"),t=e.default??e;return new t(V,1,2048)}async function $(){let e=await import("werift"),t=await L();return{createSource:()=>{let r=new e.MediaStreamTrack({kind:"audio"}),n=Math.random()*4294967295>>>0,i=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,d=new Int16Array(0);return{track:r,onData:u=>{let o=new Int16Array(d.length+u.length);o.set(d,0),o.set(u,d.length);let s=0;for(;o.length-s>=l;){let c=o.subarray(s,s+l);s+=l;let f=Buffer.from(c.buffer,c.byteOffset,c.byteLength),v=t.encode(f,l);i=i+1&65535,a=a+l>>>0;let O=new e.RtpHeader({version:2,payloadType:I,sequenceNumber:i,timestamp:a,ssrc:n,marker:!1}),S=new e.RtpPacket(O,v);r.writeRtp(S)}d=o.slice(s)}}},createSink:r=>{let n={onframe:null};return r.onReceiveRtp.subscribe(a=>{let d;try{d=t.decode(a.payload)}catch{return}let u=new Int16Array(d.length/2);for(let o=0;o<u.length;o++)u[o]=d.readInt16LE(o*2);n.onframe?.({samples:u})}),n}}}async function N(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:n=>t.onData({samples:n,sampleRate:24e3})}},createSink:t=>{let r={onframe:null},n=new e.nonstandard.RTCAudioSink(t);return n.ondata=i=>{r.onframe?.(i)},r}}}m();import{WtControlDecoder as U,consumeWtDataStreams as _,encodeWtControlFrame as D,STREAM_END as P}from"@urun-sh/core";var p="rt-video-out",x="urun.videoOut.v1",b="h264";function k(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 J(e,t){if(k(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let r=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(r.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${r.byteLength} bytes \u2014 over the u16 length prefix`);let n=new Uint8Array(2+r.byteLength+t.byteLength);return n[0]=r.byteLength&255,n[1]=r.byteLength>>8,n.set(r,2),n.set(t,2+r.byteLength),n}function E(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 r;try{r=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(d){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(d)})`)}let n=r;if(n===null||typeof n!="object"||n.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(n?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let i=n;k(i,"decodeVideoOutRecord");let a=e.subarray(2+t);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:a.slice()}}async function Y(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 r=await t.call(e),n=r.sessionId??e.sessionId;if(typeof n!="string"||n.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:r.url,certHashes:r.certHashes,token:r.token,sessionId:n,stream:p,codec:b,framing:x}}var G="urun.videoOut.v2-ws";function Q(e){let t=e.stream(p);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') 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 r=new Set,n=new Set,i=new Set,a=o=>{for(let s of n)s(o)},d=!1,u=async()=>{for await(let o of t.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let s;try{s=E(o)}catch(c){a(c instanceof Error?c:new Error(String(c)));continue}for(let c of r)c(s)}for(let o of i)o()};return{codec:b,onOutputFrame:o=>(r.add(o),d||(d=!0,u().catch(s=>a(s instanceof Error?s:new Error(String(s))))),()=>r.delete(o)),onLaneError:o=>(n.add(o),()=>n.delete(o)),onEnd:o=>(i.add(o),()=>i.delete(o))}}function B(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 r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}async function j(e,t,r){let n=r??(typeof globalThis.WebTransport=="function"?(s,c)=>new globalThis.WebTransport(s,c):void 0);if(!n)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let i=n(e.url,{serverCertificateHashes:e.certHashes.map(s=>({algorithm:"sha-256",value:B(s)}))});await i.ready;let a=await i.createBidirectionalStream();await a.writable.getWriter().write(D({t:"hello",token:e.token,sessionId:e.sessionId}));let d=a.readable.getReader(),u=new U,o=!1;for(;!o;){let{value:s,done:c}=await d.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(s)for(let f of u.push(s)){if(f.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await _(i.incomingUnidirectionalStreams,{onData:(s,c)=>{if(s===e.stream){if(c===P){t.onEnd?.();return}if(!(c instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(E(c))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:s=>t.onLaneError(s)})}export{W as a,w as b,F as c,h as d,y as e,H as f,$ as g,N as h,p as i,x as j,b as k,J as l,E as m,Y as n,G as o,Q as p,j as q};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CatalogRow } from './models-D7F0bLJ3.js';
|
|
2
2
|
import { IncomingMessage } from 'node:http';
|
|
3
|
-
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-
|
|
3
|
+
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-REmiQMBJ.js';
|
|
4
4
|
|
|
5
5
|
type TurnCatalogIdentity = {
|
|
6
6
|
kind: 'catalog';
|
|
@@ -249,6 +249,8 @@ declare class ModelRouter<S> {
|
|
|
249
249
|
private readonly opts;
|
|
250
250
|
private readonly pool;
|
|
251
251
|
|
|
252
|
+
private readonly mintedIds;
|
|
253
|
+
|
|
252
254
|
private apps;
|
|
253
255
|
private rows;
|
|
254
256
|
private shared;
|
|
@@ -257,6 +259,8 @@ declare class ModelRouter<S> {
|
|
|
257
259
|
private swr;
|
|
258
260
|
|
|
259
261
|
seed(appSlug: string, entry: S): void;
|
|
262
|
+
|
|
263
|
+
private snapshotMintId;
|
|
260
264
|
private deployedApps;
|
|
261
265
|
|
|
262
266
|
private sharedBlock;
|
|
@@ -598,6 +602,8 @@ interface ProxyClients {
|
|
|
598
602
|
|
|
599
603
|
openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string): Promise<PinnedAudioLane>;
|
|
600
604
|
|
|
605
|
+
openVideoOn?(handle: string, signal?: AbortSignal): Promise<ProxyVideoLane>;
|
|
606
|
+
|
|
601
607
|
openTurnsOn?(handle: string, signal?: AbortSignal): AsyncIterable<SessionTurnLaneEvent>;
|
|
602
608
|
|
|
603
609
|
transcriptStreamFor?(model: string | undefined): Promise<string>;
|
|
@@ -673,4 +679,4 @@ interface RealtimeCompanions {
|
|
|
673
679
|
|
|
674
680
|
type RealtimeCompanionsFor = (model: string | undefined) => Promise<RealtimeCompanions | null>;
|
|
675
681
|
|
|
676
|
-
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type
|
|
682
|
+
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type ProxyVideoLane as h, type ProxyVideoOutLane as i, type RouteTarget as j, type UsageRowReporter as k, billingIdentityOf as l };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CatalogRow } from './models-D7F0bLJ3.cjs';
|
|
2
2
|
import { IncomingMessage } from 'node:http';
|
|
3
|
-
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-
|
|
3
|
+
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-DnCKUUO2.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* THE BILLING CORRELATION SEAM — one uuid per `/v1` request, returned as the
|
|
@@ -756,6 +756,23 @@ type ImageCapabilityMode = 'generation' | 'edit';
|
|
|
756
756
|
declare class ModelRouter<S> {
|
|
757
757
|
private readonly opts;
|
|
758
758
|
private readonly pool;
|
|
759
|
+
/**
|
|
760
|
+
* Each pooled entry's identity AT MINT TIME (`sessionKeyOf(entry)` as of
|
|
761
|
+
* the moment the entry was opened/seeded). The identity seam's RENAME PROOF:
|
|
762
|
+
* the SDK's Session id is not stable across a session's first dial — it is
|
|
763
|
+
* the client-minted placeholder (the idempotency key) at construction and is
|
|
764
|
+
* rewritten to the server-allocated id when the background dial lands
|
|
765
|
+
* (core `Session.setSessionId`). A handle minted pre-dial (every dedicated
|
|
766
|
+
* realtime session, and any handle minted while a slot's first dial is
|
|
767
|
+
* still in flight) therefore encodes the PRE-rename id, and comparing it
|
|
768
|
+
* against the post-rename current id alone answered the loud "was
|
|
769
|
+
* replaced" verdict for a session that never changed — prod-usw2
|
|
770
|
+
* 2026-10-28: every realtime upgrade closed `session_gone` ~20 ms after
|
|
771
|
+
* admit. A handle names the SESSION OBJECT it minted; its mint-time id and
|
|
772
|
+
* its current id both resolve it, and only a DIFFERENT session's ids are
|
|
773
|
+
* the genuine replacement.
|
|
774
|
+
*/
|
|
775
|
+
private readonly mintedIds;
|
|
759
776
|
/** One STALE-WHILE-REVALIDATE catalog cache slot: `refreshing` dedupes the
|
|
760
777
|
* in-flight background refresh across concurrent expired reads. */
|
|
761
778
|
private apps;
|
|
@@ -775,6 +792,14 @@ declare class ModelRouter<S> {
|
|
|
775
792
|
private swr;
|
|
776
793
|
/** Seed an already-open session (the CLI's eagerly-opened startup app). */
|
|
777
794
|
seed(appSlug: string, entry: S): void;
|
|
795
|
+
/**
|
|
796
|
+
* Record the entry's identity NOW (mint time). Every session-key read for
|
|
797
|
+
* the handle seam consults this snapshot alongside the CURRENT id — the
|
|
798
|
+
* SDK's first-dial rename must never read as a replacement (see the
|
|
799
|
+
* `mintedIds` note). A genuine replacement is a DIFFERENT entry object; a
|
|
800
|
+
* later id rewrite on the same object is the same session maturing.
|
|
801
|
+
*/
|
|
802
|
+
private snapshotMintId;
|
|
778
803
|
private deployedApps;
|
|
779
804
|
/**
|
|
780
805
|
* The shared block with the same stale-while-revalidate discipline as
|
|
@@ -2413,6 +2438,19 @@ interface ProxyClients {
|
|
|
2413
2438
|
* queued admission going back only at the LAST waiter's abort.
|
|
2414
2439
|
*/
|
|
2415
2440
|
openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string): Promise<PinnedAudioLane>;
|
|
2441
|
+
/**
|
|
2442
|
+
* The HANDLE-ADDRESSED video frame lane open (the realtime binding's
|
|
2443
|
+
* `input_image` camera frames): the SAME native rt-video-in frame path
|
|
2444
|
+
* {@link openVideo} hands out for a model-addressed session, resolved
|
|
2445
|
+
* through the EXACT pooled session (or proxy-hosted lane) the handle names
|
|
2446
|
+
* — never a second session behind the voice bridge's back. On a LANE
|
|
2447
|
+
* handle the frames ride the lane's §5 `rt-video-in` stream (lane-video.ts,
|
|
2448
|
+
* the lane-stream relay fans them to the runtime's `ctx.stream('rt-video-in',
|
|
2449
|
+
* kind='data')` consumer). Optional at the seam exactly like
|
|
2450
|
+
* {@link openVideo}: a surface that receives image frames while the
|
|
2451
|
+
* embedder wired no seam fails LOUD, never drops frames.
|
|
2452
|
+
*/
|
|
2453
|
+
openVideoOn?(handle: string, signal?: AbortSignal): Promise<ProxyVideoLane>;
|
|
2416
2454
|
/**
|
|
2417
2455
|
* THE TURN/TRANSCRIPT LANE OPEN (the realtime transcription intent,
|
|
2418
2456
|
* ENG-461): the STT engine's OWN transcript events — the §5 `stt` named
|
|
@@ -2768,4 +2806,4 @@ interface RealtimeCompanions {
|
|
|
2768
2806
|
*/
|
|
2769
2807
|
type RealtimeCompanionsFor = (model: string | undefined) => Promise<RealtimeCompanions | null>;
|
|
2770
2808
|
|
|
2771
|
-
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type
|
|
2809
|
+
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type ProxyVideoLane as h, type ProxyVideoOutLane as i, type RouteTarget as j, type UsageRowReporter as k, billingIdentityOf as l };
|
package/dist/gemini-live.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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,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});
|
|
1
|
+
"use strict";var be=Object.create;var A=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Se=(e,t)=>{for(var n in t)A(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ee(t))!Ae.call(e,i)&&i!==n&&A(e,i,{get:()=>t[i],enumerable:!(o=ve(t,i))||o.enumerable});return e};var $=(e,t,n)=>(n=e!=null?be(Oe(e)):{},W(t||!e||!e.__esModule?A(n,"default",{value:e,enumerable:!0}):n,e)),Te=e=>W(A({},"__esModule",{value:!0}),e);var je={};Se(je,{AudioBridge:()=>E,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:()=>O,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",E=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(t){this.dataEmit=t}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),i=new Int16Array(o);for(let r=0;r<o;r++)i[r]=n.readInt16LE(r*2);this.source.onData(i),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(r=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(r instanceof Error?r.message:String(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 i of this.outHandlers)i(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function J(e,t,n=1e4){let o=new E(t,{sampleRate:24e3}),i=await o.startOutbound(),r=e.stream(G);await r.attach(i),typeof r.emit=="function"&&o.setDataEmit(d=>r.emit(d));let a=await Re(e,n);return await o.startInbound(a),o}function Re(e,t){let n=e.stream(G);return n.track!=null?Promise.resolve(n.track):new Promise((o,i)=>{let r,a=setTimeout(()=>{r?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),d=u=>{u!=null&&(clearTimeout(a),r?.(),o(u))};r=n.on?.("track",d),n.track!=null&&d(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,i=Math.random()*65535&65535,r=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:d=>{let u=new Int16Array(a.length+d.length);u.set(a,0),u.set(d,a.length);let c=0;for(;u.length-c>=v;){let l=u.subarray(c,c+v);c+=v;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,v);i=i+1&65535,r=r+v>>>0;let g=new e.RtpHeader({version:2,payloadType:xe,sequenceNumber:i,timestamp:r,ssrc:o,marker:!1}),h=new e.RtpPacket(g,p);n.writeRtp(h)}a=u.slice(c)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(r=>{let a;try{a=t.decode(r.payload)}catch{return}let d=new Int16Array(a.length/2);for(let u=0;u<d.length;u++)d[u]=a.readInt16LE(u*2);o.onframe?.({samples:d})}),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=i=>{n.onframe?.(i)},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 i=o;Q(i,"decodeVideoOutRecord");let r=e.subarray(2+t);if(r.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:r.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,i=new Set,r=u=>{for(let c of o)c(u)},a=!1,d=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){r(new Error(`openSessionVideoOutLane: "${_}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let c;try{c=x(u)}catch(l){r(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(c)}for(let u of i)u()};return{codec:I,onOutputFrame:u=>(n.add(u),a||(a=!0,d().catch(c=>r(c instanceof Error?c:new Error(String(c))))),()=>n.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(i.add(u),()=>i.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"?(c,l)=>new globalThis.WebTransport(c,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 i=o(e.url,{serverCertificateHashes:e.certHashes.map(c=>({algorithm:"sha-256",value:Le(c)}))});await i.ready;let r=await i.createBidirectionalStream();await r.writable.getWriter().write((0,w.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=r.readable.getReader(),d=new w.WtControlDecoder,u=!1;for(;!u;){let{value:c,done:l}=await a.read();if(l)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(c)for(let f of d.push(c)){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)(i.incomingUnidirectionalStreams,{onData:(c,l)=>{if(c===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:c=>t.onLaneError(c)})}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(d=>n[d]!==void 0),i=Object.keys(n).filter(d=>!L.includes(d));if(i.length>0)throw new s(`unknown client message field(s) ${JSON.stringify(i)} \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 r=o[0],a=m(n[r]);if(!a)throw new s(`"${r}" must be a JSON object`);return{kind:r,[r]: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 i=[];for(let r of o){let a=m(r);if(a&&typeof a.text=="string"){i.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(r)}`)}return i.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:i}=e.header;return{[k]:{v:1,seq:t,ptsUs:n,codec:o,key:i,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 i of Object.keys(t))if(!(i==="automaticActivityDetection"||i==="activityHandling"))throw new s(i==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${i}"`);let n=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new s("realtimeInputConfig.automaticActivityDetection must be an object");for(let i of Object.keys(n??{}))if(i!=="disabled")throw new s(`automaticActivityDetection.${i} 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,i=!1,r=m(e.generationConfig);if(e.generationConfig!==void 0&&!r)throw new s("setup.generationConfig must be an object");if(r){for(let f of Object.keys(r))if(!Ne.includes(f))throw new s(`unsupported generationConfig field "${f}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new s("generationConfig.temperature must be a number");n=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new s("generationConfig.maxOutputTokens must be a number");o=r.maxOutputTokens}if(r.responseModalities!==void 0){let f=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let p of f){let g=String(p).toUpperCase();if(g==="AUDIO"){i=!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 d;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new s("setup.tools must be an array");d=[];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");d.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}d.length===0&&(d=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 c=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:d,temperature:n,maxOutputTokens:o,audioModality:i,activity:c,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 i=m(o);if(!i)throw new s("clientContent.turns entries must be Content objects");let r=i.role===void 0?"user":String(i.role).toLowerCase();if(r!=="user"&&r!=="model")throw new s(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(i.role)})`);n.push({role:r==="model"?"assistant":"user",content:se(i,"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),i=new Int16Array(o),r=t/n,a=e.length-1;for(let d=0;d<o;d++){let u=d*r,c=Math.floor(u);if(c>=a){i[d]=e[a];continue}let l=u-c;i[d]=Math.round(e[c]+(e[c+1]-e[c])*l)}return i}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 i=new Int16Array(o.length/2);for(let a=0;a<i.length;a++)i[a]=o.readInt16LE(a*2);let r=j(i,b,D);return Buffer.from(r.buffer,r.byteOffset,r.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 i=e.activityStart!==void 0?"activityStart":"activityEnd",r=m(e[i]);if(!r||Object.keys(r).length!==0)throw new s(`realtimeInput.${i} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:i}}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=[],i=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let c of n){let l=m(c);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"&&(r+=p.text)}}r&&i.push({role:"assistant",content:r});for(let c of n){let l=m(c);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(c)}`,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}),i.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 d=m(t.usage),u={serverContent:{turnComplete:!0}};if(d){let c={};typeof d.input_tokens=="number"&&(c.promptTokenCount=d.input_tokens),typeof d.output_tokens=="number"&&(c.responseTokenCount=d.output_tokens),typeof d.total_tokens=="number"&&(c.totalTokenCount=d.total_tokens),Object.keys(c).length>0&&(u.usageMetadata=c)}return a.push(u),{messages:a,assistantItems:i}}async function ke(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let o;await new Promise((i,r)=>{let a=e.onSynced(()=>{clearTimeout(o),i()});o=setTimeout(()=>{a(),r(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 i=e.response??{},r={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof i.instructions=="string"&&(r.instructions=i.instructions),Array.isArray(i.modalities)&&(r.modalities=i.modalities),typeof i.temperature=="number"&&(r.temperature=i.temperature),typeof i.max_output_tokens=="number"&&(r.max_output_tokens=i.max_output_tokens),i.tools!==void 0&&(r.tools=i.tools),r}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,i=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:i}}}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 i of t){let r=i;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let d=typeof a.index=="number"?a.index:0,u=o.get(d)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(d,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${d}`,tool_index:d,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...r.body}};return}else if(r.t==="error"){yield _e(r);return}}}async function*O(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),O(this.session,n)})}sendResponseCreate(t,n,o){return this.writeGated(o,()=>{let i=V(t,n,o,this.consumerId);return this.write(i),O(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
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { A as ActivityConfig, a as ActivityHandling, C as CLOSE_PROTOCOL, b as CLOSE_SESSION_GONE, c as CLOSE_UNKNOWN_MODEL, d as CLOSE_UPSTREAM, e as ClientMessage, G as GEMINI_AUDIO_IN_RATE, f as GEMINI_AUDIO_OUT_MIME, g as GEMINI_AUDIO_OUT_RATE, h as GEMINI_LIVE_PATH, i as GeminiLiveError, L as LiveSessionConfig, O as OUTBOUND_AUDIO_FLUSH_B64, R as RealtimeInputAction, T as TurnEnd, V as VIDEO_OUT_SETUP_KEY, j as goAwayMsg, p as parseClientMessage, r as resamplePcm16, s as serverContentOfAudio, k as serverContentOfDelta, l as sessionResumptionUpdateMsg, t as translateClientContent, m as translateRealtimeInput, n as translateSetup, o as translateToolResponse, q as turnEndOfCompleted, v as videoOutAck, u as videoOutChunkMsg } from './translator-
|
|
1
|
+
export { A as ActivityConfig, a as ActivityHandling, C as CLOSE_PROTOCOL, b as CLOSE_SESSION_GONE, c as CLOSE_UNKNOWN_MODEL, d as CLOSE_UPSTREAM, e as ClientMessage, G as GEMINI_AUDIO_IN_RATE, f as GEMINI_AUDIO_OUT_MIME, g as GEMINI_AUDIO_OUT_RATE, h as GEMINI_LIVE_PATH, i as GeminiLiveError, L as LiveSessionConfig, O as OUTBOUND_AUDIO_FLUSH_B64, R as RealtimeInputAction, T as TurnEnd, V as VIDEO_OUT_SETUP_KEY, j as goAwayMsg, p as parseClientMessage, r as resamplePcm16, s as serverContentOfAudio, k as serverContentOfDelta, l as sessionResumptionUpdateMsg, t as translateClientContent, m as translateRealtimeInput, n as translateSetup, o as translateToolResponse, q as turnEndOfCompleted, v as videoOutAck, u as videoOutChunkMsg } from './translator-Dox25ky9.cjs';
|
|
2
2
|
import { b as UrunSessionLike } from './types-CHPtJx6d.cjs';
|
|
3
3
|
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-CHPtJx6d.cjs';
|
|
4
|
-
export { A as AudioBackend, a as AudioBridge, b as AudioSink, c as AudioSource, N as NATIVE_AUDIO_SAMPLE_RATE, R as RT_VIDEO_IN_STREAM, d as RT_VIDEO_OUT_STREAM, V as VIDEO_FRAME_MESSAGE_BUDGET, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, h as VideoFrameLane, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutTransportSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, r as enableSessionAudio, s as enableSessionVideo, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-
|
|
4
|
+
export { A as AudioBackend, a as AudioBridge, b as AudioSink, c as AudioSource, N as NATIVE_AUDIO_SAMPLE_RATE, R as RT_VIDEO_IN_STREAM, d as RT_VIDEO_OUT_STREAM, V as VIDEO_FRAME_MESSAGE_BUDGET, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, h as VideoFrameLane, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutTransportSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, r as enableSessionAudio, s as enableSessionVideo, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-DnCKUUO2.cjs';
|
|
5
5
|
|
|
6
6
|
interface ServeEnvelope {
|
|
7
7
|
request_id: string;
|
package/dist/gemini-live.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { A as ActivityConfig, a as ActivityHandling, C as CLOSE_PROTOCOL, b as CLOSE_SESSION_GONE, c as CLOSE_UNKNOWN_MODEL, d as CLOSE_UPSTREAM, e as ClientMessage, G as GEMINI_AUDIO_IN_RATE, f as GEMINI_AUDIO_OUT_MIME, g as GEMINI_AUDIO_OUT_RATE, h as GEMINI_LIVE_PATH, i as GeminiLiveError, L as LiveSessionConfig, O as OUTBOUND_AUDIO_FLUSH_B64, R as RealtimeInputAction, T as TurnEnd, V as VIDEO_OUT_SETUP_KEY, j as goAwayMsg, p as parseClientMessage, r as resamplePcm16, s as serverContentOfAudio, k as serverContentOfDelta, l as sessionResumptionUpdateMsg, t as translateClientContent, m as translateRealtimeInput, n as translateSetup, o as translateToolResponse, q as turnEndOfCompleted, v as videoOutAck, u as videoOutChunkMsg } from './translator-
|
|
1
|
+
export { A as ActivityConfig, a as ActivityHandling, C as CLOSE_PROTOCOL, b as CLOSE_SESSION_GONE, c as CLOSE_UNKNOWN_MODEL, d as CLOSE_UPSTREAM, e as ClientMessage, G as GEMINI_AUDIO_IN_RATE, f as GEMINI_AUDIO_OUT_MIME, g as GEMINI_AUDIO_OUT_RATE, h as GEMINI_LIVE_PATH, i as GeminiLiveError, L as LiveSessionConfig, O as OUTBOUND_AUDIO_FLUSH_B64, R as RealtimeInputAction, T as TurnEnd, V as VIDEO_OUT_SETUP_KEY, j as goAwayMsg, p as parseClientMessage, r as resamplePcm16, s as serverContentOfAudio, k as serverContentOfDelta, l as sessionResumptionUpdateMsg, t as translateClientContent, m as translateRealtimeInput, n as translateSetup, o as translateToolResponse, q as turnEndOfCompleted, v as videoOutAck, u as videoOutChunkMsg } from './translator-BqpmZ-vh.js';
|
|
2
2
|
import { b as UrunSessionLike } from './types-CHPtJx6d.js';
|
|
3
3
|
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-CHPtJx6d.js';
|
|
4
|
-
export { A as AudioBackend, a as AudioBridge, b as AudioSink, c as AudioSource, N as NATIVE_AUDIO_SAMPLE_RATE, R as RT_VIDEO_IN_STREAM, d as RT_VIDEO_OUT_STREAM, V as VIDEO_FRAME_MESSAGE_BUDGET, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, h as VideoFrameLane, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutTransportSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, r as enableSessionAudio, s as enableSessionVideo, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-
|
|
4
|
+
export { A as AudioBackend, a as AudioBridge, b as AudioSink, c as AudioSource, N as NATIVE_AUDIO_SAMPLE_RATE, R as RT_VIDEO_IN_STREAM, d as RT_VIDEO_OUT_STREAM, V as VIDEO_FRAME_MESSAGE_BUDGET, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, h as VideoFrameLane, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutTransportSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, r as enableSessionAudio, s as enableSessionVideo, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-REmiQMBJ.js';
|
|
5
5
|
|
|
6
6
|
interface ServeEnvelope {
|
|
7
7
|
request_id: string;
|
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-
|
|
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-QTHFMDZY.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-Z3QCHKJB.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};
|