@urun-sh/openai 0.6.43 → 0.6.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-2EsjJUz1.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
- package/dist/{ResponsesClient-BIcQ6p6Z.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
- package/dist/chunk-64VO62LW.js +1 -0
- package/dist/chunk-7KRHHEKZ.js +1 -0
- package/dist/chunk-BA3NCMS5.js +6 -0
- package/dist/chunk-DMRZZTYI.js +4 -0
- package/dist/chunk-FNAZ2XBE.js +20 -0
- package/dist/chunk-G6AFKOVS.js +1 -0
- package/dist/{chunk-FF3RWDFM.js → chunk-HB5KNEY5.js} +1 -1
- package/dist/{chunk-ZCF6EV4Y.js → chunk-VQSCBUKT.js} +20 -19
- package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
- package/dist/chunk-XNRPTMSL.js +1 -0
- package/dist/chunk-Y774TOE7.js +2 -0
- package/dist/{composite-BoS9-74g.d.cts → composite-DM2sT1Sp.d.cts} +1 -1
- package/dist/{composite-D4_XPSas.d.ts → composite-DNNAm0PY.d.ts} +1 -1
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +4 -4
- package/dist/gemini-live.d.ts +4 -4
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +43 -42
- package/dist/hosted/index.d.cts +4 -4
- package/dist/hosted/index.d.ts +4 -4
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +2 -2
- package/dist/pi-extension/index.d.ts +2 -2
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +41 -41
- package/dist/pooler/bin.cjs +25 -25
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +48 -47
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +19 -18
- package/dist/proxy/index.d.cts +5 -5
- package/dist/proxy/index.d.ts +5 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-PsmsZT62.d.cts → translator-C6MpaZS-.d.cts} +1 -1
- package/dist/{translator-BemK1Of5.d.ts → translator-CaOqL-V8.d.ts} +1 -1
- package/dist/{types-CxWQ84Ew.d.cts → types-DiYzfHYN.d.cts} +2 -5
- package/dist/{types-CxWQ84Ew.d.ts → types-DiYzfHYN.d.ts} +1 -1
- package/dist/{video-out-DPLqpGbQ.d.cts → video-out-A8qMuI36.d.cts} +1 -1
- package/dist/{video-out-DkMqKSOi.d.ts → video-out-IoTqIbAw.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-27HP3RMZ.js +0 -6
- package/dist/chunk-2NKCALKY.js +0 -22
- package/dist/chunk-2RO722HS.js +0 -2
- package/dist/chunk-7DUSLXPG.js +0 -1
- package/dist/chunk-BFIKVTQB.js +0 -1
- package/dist/chunk-GDH2D3S6.js +0 -1
- package/dist/chunk-MOX5FG2R.js +0 -1
- package/dist/chunk-YRBUHHI3.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as I,o as A}from"./chunk-
|
|
1
|
+
import{a as I,o as A}from"./chunk-64VO62LW.js";import{c as v}from"./chunk-YSFSRI3D.js";v();var J="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",k=1007,F=1008,R=1011,V=1008,n=class extends Error{constructor(o,i=k){super(o);this.closeCode=i}closeCode},d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,w=["setup","clientContent","realtimeInput","toolResponse"];function B(e){let t;try{t=JSON.parse(e)}catch{throw new n("client message is not valid JSON")}let o=d(t);if(!o)throw new n("client message must be a JSON object");let i=w.filter(c=>o[c]!==void 0),s=Object.keys(o).filter(c=>!w.includes(c));if(s.length>0)throw new n(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${w.join(", ")}`);if(i.length!==1)throw new n(`client message must contain exactly one of ${w.join(", ")} (got ${i.length})`);let r=i[0],a=d(o[r]);if(!a)throw new n(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function C(e,t){if(typeof e=="string")return e;let o=d(e),i=o?o.parts:void 0;if(!Array.isArray(i))throw new n(`${t}: expected a Content with a parts array`);let s=[];for(let r of i){let a=d(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new n(`${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 n(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new n(`${t}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
|
|
2
2
|
`)}var _={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},h="urun.videoOut";function G(e){return{framing:A,codec:e}}function Y(e){let{seq:t,ptsUs:o,codec:i,key:s}=e.header;return{[h]:{v:1,seq:t,ptsUs:o,codec:i,key:s,data:Buffer.from(e.au).toString("base64")}}}var x={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},S=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",h],T=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function E(e){let t=d(e);if(!t)throw new n("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new n(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let o=d(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!o)throw new n("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(o??{}))if(s!=="disabled")throw new n(`automaticActivityDetection.${s} 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(o?.disabled!==!0)throw new n("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let i="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!T.includes(t.activityHandling))throw new n(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${T.join(", ")}`);i=t.activityHandling}return{manualActivity:!0,activityHandling:i}}var N=["temperature","maxOutputTokens","responseModalities"];function K(e){for(let[u,f]of Object.entries(x))if(e[u]!==void 0)throw new n(f);for(let u of Object.keys(e))if(!S.includes(u))throw new n(`unsupported setup field "${u}"`);if(typeof e.model!="string"||e.model.length===0)throw new n('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),o,i,s=!1,r=d(e.generationConfig);if(e.generationConfig!==void 0&&!r)throw new n("setup.generationConfig must be an object");if(r){for(let u of Object.keys(r))if(!N.includes(u))throw new n(`unsupported generationConfig field "${u}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new n("generationConfig.temperature must be a number");o=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new n("generationConfig.maxOutputTokens must be a number");i=r.maxOutputTokens}if(r.responseModalities!==void 0){let u=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let f of u){let y=String(f).toUpperCase();if(y==="AUDIO"){s=!0;continue}if(y!=="TEXT")throw new n(`responseModalities ${JSON.stringify(f)} 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:C(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new n("setup.tools must be an array");c=[];for(let u of e.tools){let f=d(u);if(!f)throw new n("setup.tools entries must be objects");for(let y of Object.keys(f))if(y!=="functionDeclarations")throw new n(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new n("tool.functionDeclarations must be an array");for(let y of f.functionDeclarations){let g=d(y);if(!g||typeof g.name!="string")throw new n("functionDeclarations entries require a string name");c.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}c.length===0&&(c=void 0)}let m={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let u=d(e.sessionResumption);if(!u)throw new n("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(u))if(f!=="handle")throw new n(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(u.handle!==void 0&&(typeof u.handle!="string"||u.handle.length===0))throw new n("sessionResumption.handle must be a non-empty string when present");m={enabled:!0,handle:typeof u.handle=="string"?u.handle:null}}let p=e.realtimeInputConfig===void 0?_:E(e.realtimeInputConfig),l=!1;if(e[h]!==void 0){if(!d(e[h]))throw new n(`setup["${h}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:o,maxOutputTokens:i,audioModality:s,activity:p,sessionResumption:m,videoOut:l}}function q(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function W(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function X(e){for(let i of Object.keys(e))if(i!=="turns"&&i!=="turnComplete")throw new n(`unsupported clientContent field "${i}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new n("clientContent.turns must be an array");let o=[];for(let i of t){let s=d(i);if(!s)throw new n("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new n(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);o.push({role:r==="model"?"assistant":"user",content:C(s,"clientContent.turns")})}return{items:o,turnComplete:e.turnComplete===!0}}var b=16e3,O=24e3,$=`audio/pcm;rate=${O}`,z=Buffer.alloc(960).toString("base64");function j(e,t,o){if(t===o)return e;let i=Math.floor(e.length*o/t),s=new Int16Array(i),r=t/o,a=e.length-1;for(let c=0;c<i;c++){let m=c*r,p=Math.floor(m);if(p>=a){s[c]=e[a];continue}let l=m-p;s[c]=Math.round(e[p]+(e[p+1]-e[p])*l)}return s}function U(e){let t=d(e);if(!t)throw new n("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new n(`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 n("realtimeInput.video.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length<3||o[0]!==255||o[1]!==216)throw new n("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(o)}function D(e){let t=d(e);if(!t)throw new n("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new n(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let o=/;\s*rate=(\d+)/.exec(t.mimeType);if(o&&Number(o[1])!==b)throw new n(`realtimeInput.audio.mimeType declares rate=${o[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 n("realtimeInput.audio.data must be non-empty base64");let i=Buffer.from(t.data,"base64");if(i.length===0||i.length%2!==0)throw new n(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${i.length} bytes \u2014 not even)`);let s=new Int16Array(i.length/2);for(let a=0;a<s.length;a++)s[a]=i.readInt16LE(a*2);let r=j(s,b,O);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Q(e){if(e.mediaChunks!==void 0)throw new n('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new n("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=e.activityStart!==void 0?"activityStart":"activityEnd",r=d(e[s]);if(!r||Object.keys(r).length!==0)throw new n(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let t=["text","audio","audioStreamEnd","video"];for(let i of Object.keys(e))if(!t.includes(i))throw new n(`unsupported realtimeInput field "${i}"`);let o=t.filter(i=>e[i]!==void 0);if(o.length!==1)throw new n(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${o.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:D(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:U(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new n("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new n("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Z(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new n(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new n("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let o=d(t);if(!o||typeof o.id!="string"||o.id.length===0)throw new n("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:o.id,output:JSON.stringify(o.response??null)}})}function ee(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function te(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:$,data:e}}]}}}}function ne(e){let t=d(e)??{},o=Array.isArray(t.output)?t.output:[],i=[],s=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let p of o){let l=d(p);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let u of l.content){let f=d(u);f?.type==="output_text"&&typeof f.text=="string"&&(r+=f.text)}}r&&s.push({role:"assistant",content:r});for(let p of o){let l=d(p);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new n(`upstream function_call item is missing call_id/name: ${JSON.stringify(p)}`,R);let u=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",f;try{f=JSON.parse(u)}catch{throw new n(`upstream function_call arguments are not valid JSON: ${u}`,R)}i.push({id:l.call_id,name:l.name,args:f}),s.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:u})}let a=[];i.length>0&&a.push({toolCall:{functionCalls:i}}),a.push({serverContent:{generationComplete:!0}});let c=d(t.usage),m={serverContent:{turnComplete:!0}};if(c){let p={};typeof c.input_tokens=="number"&&(p.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(p.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(p.totalTokenCount=c.total_tokens),Object.keys(p).length>0&&(m.usageMetadata=p)}return a.push(m),{messages:a,assistantItems:s}}export{J as a,k as b,F as c,R as d,V as e,n as f,B as g,h,G as i,Y as j,K as k,q as l,W as m,X as n,b as o,O as p,$ as q,z as r,j as s,Q as t,Z as u,ee as v,te as w,ne as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as x}from"./chunk-YSFSRI3D.js";x();import{createHmac as y,randomUUID as A,timingSafeEqual as S}from"crypto";var k=["sfu","urun-doc"],I="runtime:lease",O="lane:join",D="urun-runtime-key-v1";function p(r,t){if(!r)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!t)throw new Error("deriveOrgRuntimeKey requires an orgId");return y("sha256",r).update(`${D}|${t}`).digest("base64url")}var T=120;function N(r){return Buffer.from(r).toString("base64url")}function $(r,t,i){let s=N(JSON.stringify(r)),e=N(JSON.stringify(t)),o=y("sha256",i).update(`${s}.${e}`).digest("base64url");return`${s}.${e}.${o}`}function J(r,t,i=T,s=O,e){let o=e?p(t,e):t;return _(r,o,i,s,e)}function U(r,t,i,s=T,e=O){return _(r,i,s,e,t)}function _(r,t,i,s,e){let o=Math.floor(Date.now()/1e3);return $({alg:"HS256",typ:"JWT"},{session_id:r,aud:"sfu",sub:r,scope:s,...e?{tenant:e}:{},iat:o,exp:o+i,jti:A()},t)}function j(r,t,i,s=Math.floor(Date.now()/1e3),e){let o=r.split(".");if(o.length!==3)return null;let[m,h,L]=o,E,n;try{E=JSON.parse(Buffer.from(m,"base64url").toString()),n=JSON.parse(Buffer.from(h,"base64url").toString())}catch{return null}if(E.alg!=="HS256")return null;let d;try{d=Buffer.from(L,"base64url")}catch{return null}let f=typeof n.tenant=="string"&&n.tenant!==""?n.tenant:void 0,u=[];if(f!==void 0?(u.push(p(i,f)),e&&u.push(p(e,f))):(u.push(i),e&&u.push(e)),!u.some(g=>{let b=y("sha256",g).update(`${m}.${h}`).digest();return d.length===b.length&&S(d,b)}))return null;let l=n.exp;if(typeof l!="number"||l<=s)return null;let a=typeof n.aud=="string"||Array.isArray(n.aud)?n.aud:void 0;if(!(a!==void 0&&k.some(g=>g===a||Array.isArray(a)&&a.includes(g))))return null;let c=n.session_id??n.sub;return typeof c!="string"||c!==t?null:{sessionId:c,aud:a,scope:typeof n.scope=="string"?n.scope:void 0,tenant:f,app:typeof n.app=="string"?n.app:void 0,fn:typeof n.fn=="string"?n.fn:void 0,exp:l}}export{I as a,T as b,J as c,U as d,j as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as D}from"./chunk-BA3NCMS5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
2
|
+
`)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CatalogRow } from './models-D7F0bLJ3.cjs';
|
|
2
2
|
import { IncomingMessage, Server } 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-A8qMuI36.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* THE BILLING CORRELATION SEAM — one uuid per `/v1` request, returned as the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CatalogRow } from './models-D7F0bLJ3.js';
|
|
2
2
|
import { IncomingMessage, Server } 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-IoTqIbAw.js';
|
|
4
4
|
|
|
5
5
|
type TurnCatalogIdentity = {
|
|
6
6
|
kind: 'catalog';
|
package/dist/gemini-live.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ae=Object.create;var A=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var xe=(e,t)=>{for(var o in t)A(e,o,{get:t[o],enumerable:!0})},J=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Te(t))!Ie.call(e,r)&&r!==o&&A(e,r,{get:()=>t[r],enumerable:!(n=Se(t,r))||n.enumerable});return e};var B=(e,t,o)=>(o=e!=null?Ae(Re(e)):{},J(t||!e||!e.__esModule?A(o,"default",{value:e,enumerable:!0}):o,e)),Ce=e=>J(A({},"__esModule",{value:!0}),e);var Qe={};xe(Qe,{AudioBridge:()=>E,CLOSE_PROTOCOL:()=>j,CLOSE_SESSION_GONE:()=>se,CLOSE_UNKNOWN_MODEL:()=>ie,CLOSE_UPSTREAM:()=>D,GEMINI_AUDIO_IN_RATE:()=>b,GEMINI_AUDIO_OUT_MIME:()=>W,GEMINI_AUDIO_OUT_RATE:()=>V,GEMINI_LIVE_PATH:()=>re,GeminiLiveError:()=>a,NATIVE_AUDIO_SAMPLE_RATE:()=>I,OUTBOUND_AUDIO_FLUSH_B64:()=>ge,RT_VIDEO_IN_STREAM:()=>S,RT_VIDEO_OUT_STREAM:()=>v,SdkTransport:()=>$,VIDEO_FRAME_MESSAGE_BUDGET:()=>T,VIDEO_OUT_DEFAULT_CODEC:()=>x,VIDEO_OUT_FRAMING:()=>H,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>L,consumeVideoOut:()=>ne,decodeResponsesLane:()=>O,decodeVideoOutRecord:()=>C,enableSessionAudio:()=>Y,enableSessionVideo:()=>K,encodeVideoOutRecord:()=>Z,goAwayMsg:()=>pe,negotiateSessionVideoOutQuic:()=>ee,nodeAudioBackend:()=>z,openSessionVideoOutLane:()=>te,parseClientMessage:()=>ae,resamplePcm16:()=>G,responseCreateToEnvelope:()=>M,responsesCreateToEnvelope:()=>N,serverContentOfAudio:()=>ke,serverContentOfDelta:()=>we,sessionResumptionUpdateMsg:()=>fe,translateClientContent:()=>me,translateRealtimeInput:()=>ye,translateSetup:()=>le,translateToolResponse:()=>he,turnEndOfCompleted:()=>ve,videoOutAck:()=>de,videoOutChunkMsg:()=>ce,weriftAudioBackend:()=>Q});module.exports=Ce(Qe);var I=24e3,q="audio",E=class{constructor(t,o){this.backend=t;this.opts=o}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,o){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),i=new Int16Array(r);for(let s=0;s<r;s++)i[s]=n.readInt16LE(s*2);this.source.onData(i),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(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=o=>{let n=Buffer.from(o.samples.buffer,o.samples.byteOffset,o.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(n)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function Y(e,t,o=1e4){try{return await Le(e,t,o)}catch(n){try{t.dispose?.()}catch{}throw n}}async function Le(e,t,o){let n=new E(t,{sampleRate:24e3}),r=await n.startOutbound(),i=e.stream(q);await i.attach(r),typeof i.emit=="function"&&n.setDataEmit(c=>i.emit(c));let s=await Ue(e,o);return await n.startInbound(s),n}function Ue(e,t){let o=e.stream(q);return o.track!=null?Promise.resolve(o.track):new Promise((n,r)=>{let i,s=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(s),i?.(),n(u))};i=o.on?.("track",c),o.track!=null&&c(o.track)})}var S="rt-video-in",T=256e3;function K(e){let t=e.stream(S),o=t.emit;if(typeof o!="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 n=>{if(n.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(n.byteLength>T)throw new Error(`enableSessionVideo: frame is ${n.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 o.call(t,n)}}}var De=24e3,_=480,Ve=111,Me=50,R=null;async function Ne(){if(R)return;let e=await import("opusscript");R=e.default??e}function Pe(){if(!R)throw new Error("[opus-guard] opusscript module not loaded");return new R(De,1,2048)}var F=class{constructor(t=Pe){this.build=t;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let t=this.build();return this.inner=t,t}get wedged(){return this._wedged||this.consecutiveFailures>=Me}encode(t,o){this.inner||this.rebuild();let n=this.inner;try{let r=n.encode(t,o);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`);return null}}decode(t){this.inner||this.rebuild();let o=this.inner;try{let n=o.decode(t);return this.consecutiveFailures=0,this._wedged=!1,n}catch(n){this.consecutiveFailures+=1,this.inner=null;try{o.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${n instanceof Error?n.message:String(n)}`)):n}}dispose(){let t=this.inner;this.inner=null;try{t?.delete?.()}catch{}}};async function Q(){let e=await import("werift");await Ne();let t=new F;return{createSource:()=>{let o=new e.MediaStreamTrack({kind:"audio"}),n=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:o,onData:c=>{let u=new Int16Array(s.length+c.length);u.set(s,0),u.set(c,s.length);let d=0;for(;u.length-d>=_;){let l=u.subarray(d,d+_);d+=_;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,_);if(p===null){s=u.slice(d);break}r=r+1&65535,i=i+_>>>0;let y=new e.RtpHeader({version:2,payloadType:Ve,sequenceNumber:r,timestamp:i,ssrc:n,marker:!1}),w=new e.RtpPacket(y,p);o.writeRtp(w)}s=u.slice(d)}}},createSink:o=>{let n={onframe:null};return o.onReceiveRtp.subscribe(i=>{let s;try{s=t.decode(i.payload)}catch(u){if(t.wedged)throw u;return}let c=new Int16Array(s.length/2);for(let u=0;u<c.length;u++)c[u]=s.readInt16LE(u*2);n.onframe?.({samples:c})}),n},dispose:()=>t.dispose()}}async function z(){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 o={onframe:null},n=new e.nonstandard.RTCAudioSink(t);return n.ondata=r=>{o.onframe?.(r)},o}}}var h=require("@urun-sh/core"),v="rt-video-out",H="urun.videoOut.v1",x="h264";function X(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(X(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let o=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(o.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${o.byteLength} bytes \u2014 over the u16 length prefix`);let n=new Uint8Array(2+o.byteLength+t.byteLength);return n[0]=o.byteLength&255,n[1]=o.byteLength>>8,n.set(o,2),n.set(t,2+o.byteLength),n}function C(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 o;try{o=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let n=o;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 r=n;X(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 ee(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 o=await t.call(e),n=o.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:o.url,certHashes:o.certHashes,token:o.token,sessionId:n,stream:v,codec:x,framing:H}}var L="urun.videoOut.v2-ws";function te(e){let t=e.stream(v);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${v}') 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 o=new Set,n=new Set,r=new Set,i=u=>{for(let d of n)d(u)},s=!1,c=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${v}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=C(u)}catch(l){i(l instanceof Error?l:new Error(String(l)));continue}for(let l of o)l(d)}for(let u of r)u()};return{codec:x,onOutputFrame:u=>(o.add(u),s||(s=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>o.delete(u)),onLaneError:u=>(n.add(u),()=>n.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function $e(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 o=0;o<t.length;o++)t[o]=parseInt(e.slice(o*2,o*2+2),16);return t}async function ne(e,t,o){let n=o??(typeof globalThis.WebTransport=="function"?(d,l)=>new globalThis.WebTransport(d,l):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 r=n(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:$e(d)}))});await r.ready;let i=await r.createBidirectionalStream();await i.writable.getWriter().write((0,h.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let s=i.readable.getReader(),c=new h.WtControlDecoder,u=!1;for(;!u;){let{value:d,done:l}=await s.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,h.consumeWtDataStreams)(r.incomingUnidirectionalStreams,{onData:(d,l)=>{if(d===e.stream){if(l===h.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(C(l))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:d=>t.onLaneError(d)})}var re="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",j=1007,ie=1008,D=1011,se=1008,a=class extends Error{constructor(o,n=j){super(o);this.closeCode=n}closeCode},m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,U=["setup","clientContent","realtimeInput","toolResponse"];function ae(e){let t;try{t=JSON.parse(e)}catch{throw new a("client message is not valid JSON")}let o=m(t);if(!o)throw new a("client message must be a JSON object");let n=U.filter(c=>o[c]!==void 0),r=Object.keys(o).filter(c=>!U.includes(c));if(r.length>0)throw new a(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${U.join(", ")}`);if(n.length!==1)throw new a(`client message must contain exactly one of ${U.join(", ")} (got ${n.length})`);let i=n[0],s=m(o[i]);if(!s)throw new a(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function ue(e,t){if(typeof e=="string")return e;let o=m(e),n=o?o.parts:void 0;if(!Array.isArray(n))throw new a(`${t}: expected a Content with a parts array`);let r=[];for(let i of n){let s=m(i);if(s&&typeof s.text=="string"){r.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new a(`${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`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new a(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new a(`${t}: unsupported part ${JSON.stringify(i)}`)}return r.join(`
|
|
2
|
-
`)}var Be={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function de(e){return{framing:L,codec:e}}function ce(e){let{seq:t,ptsUs:o,codec:n,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:o,codec:n,key:r,data:Buffer.from(e.au).toString("base64")}}}var Fe={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},He=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],oe=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function je(e){let t=m(e);if(!t)throw new a("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new a(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let o=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!o)throw new a("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(o??{}))if(r!=="disabled")throw new a(`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(o?.disabled!==!0)throw new a("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 n="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!oe.includes(t.activityHandling))throw new a(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${oe.join(", ")}`);n=t.activityHandling}return{manualActivity:!0,activityHandling:n}}var We=["temperature","maxOutputTokens","responseModalities"];function le(e){for(let[f,p]of Object.entries(Fe))if(e[f]!==void 0)throw new a(p);for(let f of Object.keys(e))if(!He.includes(f))throw new a(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new a('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),o,n,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new a("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!We.includes(f))throw new a(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new a("generationConfig.temperature must be a number");o=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new a("generationConfig.maxOutputTokens must be a number");n=i.maxOutputTokens}if(i.responseModalities!==void 0){let f=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of f){let y=String(p).toUpperCase();if(y==="AUDIO"){r=!0;continue}if(y!=="TEXT")throw new a(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];e.systemInstruction!==void 0&&s.push({role:"system",content:ue(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new a("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new a("setup.tools entries must be objects");for(let y of Object.keys(p))if(y!=="functionDeclarations")throw new a(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new a("tool.functionDeclarations must be an array");for(let y of p.functionDeclarations){let w=m(y);if(!w||typeof w.name!="string")throw new a("functionDeclarations entries require a string name");c.push({type:"function",name:w.name,description:w.description,parameters:w.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 a("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new a(`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 a("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?Be:je(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new a(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:s,tools:c,temperature:o,maxOutputTokens:n,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function fe(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function pe(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function me(e){for(let n of Object.keys(e))if(n!=="turns"&&n!=="turnComplete")throw new a(`unsupported clientContent field "${n}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new a("clientContent.turns must be an array");let o=[];for(let n of t){let r=m(n);if(!r)throw new a("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 a(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);o.push({role:i==="model"?"assistant":"user",content:ue(r,"clientContent.turns")})}return{items:o,turnComplete:e.turnComplete===!0}}var b=16e3,V=24e3,W=`audio/pcm;rate=${V}`,ge=Buffer.alloc(960).toString("base64");function G(e,t,o){if(t===o)return e;let n=Math.floor(e.length*o/t),r=new Int16Array(n),i=t/o,s=e.length-1;for(let c=0;c<n;c++){let u=c*i,d=Math.floor(u);if(d>=s){r[c]=e[s];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function Ge(e){let t=m(e);if(!t)throw new a("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new a(`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 a("realtimeInput.video.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length<3||o[0]!==255||o[1]!==216)throw new a("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(o)}function Je(e){let t=m(e);if(!t)throw new a("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new a(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let o=/;\s*rate=(\d+)/.exec(t.mimeType);if(o&&Number(o[1])!==b)throw new a(`realtimeInput.audio.mimeType declares rate=${o[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 a("realtimeInput.audio.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length===0||n.length%2!==0)throw new a(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${n.length} bytes \u2014 not even)`);let r=new Int16Array(n.length/2);for(let s=0;s<r.length;s++)r[s]=n.readInt16LE(s*2);let i=G(r,b,V);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function ye(e){if(e.mediaChunks!==void 0)throw new a('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 a("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 a(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let n of Object.keys(e))if(!t.includes(n))throw new a(`unsupported realtimeInput field "${n}"`);let o=t.filter(n=>e[n]!==void 0);if(o.length!==1)throw new a(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${o.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:Je(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Ge(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new a("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new a("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function he(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new a(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new a("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let o=m(t);if(!o||typeof o.id!="string"||o.id.length===0)throw new a("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:o.id,output:JSON.stringify(o.response??null)}})}function we(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function ke(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:W,data:e}}]}}}}function ve(e){let t=m(e)??{},o=Array.isArray(t.output)?t.output:[],n=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of o){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 o){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new a(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,D);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new a(`upstream function_call arguments are not valid JSON: ${f}`,D)}n.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 s=[];n.length>0&&s.push({toolCall:{functionCalls:n}}),s.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 s.push(u),{messages:s,assistantItems:r}}async function be(e,t,o){if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((r,i)=>{let s=e.onSynced(()=>{clearTimeout(n),r()});n=setTimeout(()=>{s(),i(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${o} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}function M(e,t,o,n){let r=e.response??{},i={request_id:o,consumer_id:n,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 N(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}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,o=t.body??{},n=o.error,r=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Ee=require("@urun-sh/core/internal");function Oe(e,t){let o=e.delete;if(typeof o=="function"){(0,Ee.gcRequest)({get:n=>e.get(n),delete:n=>o.call(e,n),on:(n,r)=>e.on(n,r)},t);return}e.set({requests:{[t]:null}})}var qe="llm-resp";async function*Ye(e,t){let o=`resp_${e}`,n=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:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let s of i.tool_calls){let c=typeof s.index=="number"?s.index:0,u=n.get(c)??{};s.id&&(u.id=s.id),s.function?.name&&(u.name=s.function.name),n.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:s.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield _e(i);return}}}async function*O(e,t){let o=`${qe}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*Ye(t,e.stream(o).messages())}finally{try{Oe(e.doc("llm"),t)}catch{}}}var $=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}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,o){return this.writeGated(o,()=>{let n=N(t,o,this.consumerId);return this.write(n),O(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let r=M(t,o,n,this.consumerId);return this.write(r),O(this.session,n)})}async writeGated(t,o){try{await be(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};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 Oe=Object.create;var A=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(e,t)=>{for(var o in t)A(e,o,{get:t[o],enumerable:!0})},J=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Se(t))!Re.call(e,r)&&r!==o&&A(e,r,{get:()=>t[r],enumerable:!(n=Ae(t,r))||n.enumerable});return e};var B=(e,t,o)=>(o=e!=null?Oe(Te(e)):{},J(t||!e||!e.__esModule?A(o,"default",{value:e,enumerable:!0}):o,e)),xe=e=>J(A({},"__esModule",{value:!0}),e);var Ke={};Ie(Ke,{AudioBridge:()=>E,CLOSE_PROTOCOL:()=>j,CLOSE_SESSION_GONE:()=>se,CLOSE_UNKNOWN_MODEL:()=>ie,CLOSE_UPSTREAM:()=>D,GEMINI_AUDIO_IN_RATE:()=>v,GEMINI_AUDIO_OUT_MIME:()=>W,GEMINI_AUDIO_OUT_RATE:()=>V,GEMINI_LIVE_PATH:()=>re,GeminiLiveError:()=>a,NATIVE_AUDIO_SAMPLE_RATE:()=>I,OUTBOUND_AUDIO_FLUSH_B64:()=>ge,RT_VIDEO_IN_STREAM:()=>S,RT_VIDEO_OUT_STREAM:()=>b,SdkTransport:()=>$,VIDEO_FRAME_MESSAGE_BUDGET:()=>T,VIDEO_OUT_DEFAULT_CODEC:()=>x,VIDEO_OUT_FRAMING:()=>H,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>L,consumeVideoOut:()=>ne,decodeResponsesLane:()=>O,decodeVideoOutRecord:()=>C,enableSessionAudio:()=>q,enableSessionVideo:()=>K,encodeVideoOutRecord:()=>Z,goAwayMsg:()=>pe,negotiateSessionVideoOutQuic:()=>ee,nodeAudioBackend:()=>z,openSessionVideoOutLane:()=>te,parseClientMessage:()=>ae,resamplePcm16:()=>G,responseCreateToEnvelope:()=>M,responsesCreateToEnvelope:()=>N,serverContentOfAudio:()=>ke,serverContentOfDelta:()=>we,sessionResumptionUpdateMsg:()=>fe,translateClientContent:()=>me,translateRealtimeInput:()=>ye,translateSetup:()=>le,translateToolResponse:()=>he,turnEndOfCompleted:()=>be,videoOutAck:()=>de,videoOutChunkMsg:()=>ce,weriftAudioBackend:()=>Q});module.exports=xe(Ke);var I=24e3,Y="audio",E=class{constructor(t,o){this.backend=t;this.opts=o}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,o){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),i=new Int16Array(r);for(let s=0;s<r;s++)i[s]=n.readInt16LE(s*2);this.source.onData(i),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(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=o=>{let n=Buffer.from(o.samples.buffer,o.samples.byteOffset,o.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(n)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function q(e,t,o=1e4){try{return await Ce(e,t,o)}catch(n){try{t.dispose?.()}catch{}throw n}}async function Ce(e,t,o){let n=new E(t,{sampleRate:24e3}),r=await n.startOutbound(),i=e.stream(Y);await i.attach(r),typeof i.emit=="function"&&n.setDataEmit(c=>i.emit(c));let s=await Le(e,o);return await n.startInbound(s),n}function Le(e,t){let o=e.stream(Y);return o.track!=null?Promise.resolve(o.track):new Promise((n,r)=>{let i,s=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(s),i?.(),n(u))};i=o.on?.("track",c),o.track!=null&&c(o.track)})}var S="rt-video-in",T=256e3;function K(e){let t=e.stream(S),o=t.emit;if(typeof o!="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 n=>{if(n.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(n.byteLength>T)throw new Error(`enableSessionVideo: frame is ${n.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 o.call(t,n)}}}var Ue=24e3,_=480,De=111,Ve=50,R=null;async function Me(){if(R)return;let e=await import("opusscript");R=e.default??e}function Ne(){if(!R)throw new Error("[opus-guard] opusscript module not loaded");return new R(Ue,1,2048)}var F=class{constructor(t=Ne){this.build=t;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let t=this.build();return this.inner=t,t}get wedged(){return this._wedged||this.consecutiveFailures>=Ve}encode(t,o){this.inner||this.rebuild();let n=this.inner;try{let r=n.encode(t,o);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`);return null}}decode(t){this.inner||this.rebuild();let o=this.inner;try{let n=o.decode(t);return this.consecutiveFailures=0,this._wedged=!1,n}catch(n){this.consecutiveFailures+=1,this.inner=null;try{o.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${n instanceof Error?n.message:String(n)}`)):n}}dispose(){let t=this.inner;this.inner=null;try{t?.delete?.()}catch{}}};async function Q(){let e=await import("werift");await Me();let t=new F;return{createSource:()=>{let o=new e.MediaStreamTrack({kind:"audio"}),n=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:o,onData:c=>{let u=new Int16Array(s.length+c.length);u.set(s,0),u.set(c,s.length);let d=0;for(;u.length-d>=_;){let l=u.subarray(d,d+_);d+=_;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,_);if(p===null){s=u.slice(d);break}r=r+1&65535,i=i+_>>>0;let g=new e.RtpHeader({version:2,payloadType:De,sequenceNumber:r,timestamp:i,ssrc:n,marker:!1}),w=new e.RtpPacket(g,p);o.writeRtp(w)}s=u.slice(d)}}},createSink:o=>{let n={onframe:null};return o.onReceiveRtp.subscribe(i=>{if(i.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${i.payload.length} B > 3828 B max`);return}let s;try{s=t.decode(i.payload)}catch(u){if(t.wedged)throw u;return}let c=new Int16Array(s.length/2);for(let u=0;u<c.length;u++)c[u]=s.readInt16LE(u*2);n.onframe?.({samples:c})}),n},dispose:()=>t.dispose()}}async function z(){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 o={onframe:null},n=new e.nonstandard.RTCAudioSink(t);return n.ondata=r=>{o.onframe?.(r)},o}}}var h=require("@urun-sh/core"),b="rt-video-out",H="urun.videoOut.v1",x="h264";function X(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(X(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let o=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(o.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${o.byteLength} bytes \u2014 over the u16 length prefix`);let n=new Uint8Array(2+o.byteLength+t.byteLength);return n[0]=o.byteLength&255,n[1]=o.byteLength>>8,n.set(o,2),n.set(t,2+o.byteLength),n}function C(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 o;try{o=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let n=o;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 r=n;X(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 ee(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 o=await t.call(e),n=o.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:o.url,certHashes:o.certHashes,token:o.token,sessionId:n,stream:b,codec:x,framing:H}}var L="urun.videoOut.v2-ws";function te(e){let t=e.stream(b);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${b}') 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 o=new Set,n=new Set,r=new Set,i=u=>{for(let d of n)d(u)},s=!1,c=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${b}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=C(u)}catch(l){i(l instanceof Error?l:new Error(String(l)));continue}for(let l of o)l(d)}for(let u of r)u()};return{codec:x,onOutputFrame:u=>(o.add(u),s||(s=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>o.delete(u)),onLaneError:u=>(n.add(u),()=>n.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function Pe(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 o=0;o<t.length;o++)t[o]=parseInt(e.slice(o*2,o*2+2),16);return t}async function ne(e,t,o){let n=o??(typeof globalThis.WebTransport=="function"?(d,l)=>new globalThis.WebTransport(d,l):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 r=n(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:Pe(d)}))});await r.ready;let i=await r.createBidirectionalStream();await i.writable.getWriter().write((0,h.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let s=i.readable.getReader(),c=new h.WtControlDecoder,u=!1;for(;!u;){let{value:d,done:l}=await s.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,h.consumeWtDataStreams)(r.incomingUnidirectionalStreams,{onData:(d,l)=>{if(d===e.stream){if(l===h.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(C(l))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:d=>t.onLaneError(d)})}var re="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",j=1007,ie=1008,D=1011,se=1008,a=class extends Error{constructor(o,n=j){super(o);this.closeCode=n}closeCode},m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,U=["setup","clientContent","realtimeInput","toolResponse"];function ae(e){let t;try{t=JSON.parse(e)}catch{throw new a("client message is not valid JSON")}let o=m(t);if(!o)throw new a("client message must be a JSON object");let n=U.filter(c=>o[c]!==void 0),r=Object.keys(o).filter(c=>!U.includes(c));if(r.length>0)throw new a(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${U.join(", ")}`);if(n.length!==1)throw new a(`client message must contain exactly one of ${U.join(", ")} (got ${n.length})`);let i=n[0],s=m(o[i]);if(!s)throw new a(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function ue(e,t){if(typeof e=="string")return e;let o=m(e),n=o?o.parts:void 0;if(!Array.isArray(n))throw new a(`${t}: expected a Content with a parts array`);let r=[];for(let i of n){let s=m(i);if(s&&typeof s.text=="string"){r.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new a(`${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`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new a(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new a(`${t}: unsupported part ${JSON.stringify(i)}`)}return r.join(`
|
|
2
|
+
`)}var $e={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function de(e){return{framing:L,codec:e}}function ce(e){let{seq:t,ptsUs:o,codec:n,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:o,codec:n,key:r,data:Buffer.from(e.au).toString("base64")}}}var Be={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Fe=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],oe=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function He(e){let t=m(e);if(!t)throw new a("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new a(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let o=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!o)throw new a("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(o??{}))if(r!=="disabled")throw new a(`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(o?.disabled!==!0)throw new a("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 n="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!oe.includes(t.activityHandling))throw new a(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${oe.join(", ")}`);n=t.activityHandling}return{manualActivity:!0,activityHandling:n}}var je=["temperature","maxOutputTokens","responseModalities"];function le(e){for(let[f,p]of Object.entries(Be))if(e[f]!==void 0)throw new a(p);for(let f of Object.keys(e))if(!Fe.includes(f))throw new a(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new a('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),o,n,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new a("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!je.includes(f))throw new a(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new a("generationConfig.temperature must be a number");o=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new a("generationConfig.maxOutputTokens must be a number");n=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 a(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];e.systemInstruction!==void 0&&s.push({role:"system",content:ue(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new a("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new a("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new a(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new a("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let w=m(g);if(!w||typeof w.name!="string")throw new a("functionDeclarations entries require a string name");c.push({type:"function",name:w.name,description:w.description,parameters:w.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 a("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new a(`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 a("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?$e:He(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new a(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:s,tools:c,temperature:o,maxOutputTokens:n,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function fe(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function pe(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function me(e){for(let n of Object.keys(e))if(n!=="turns"&&n!=="turnComplete")throw new a(`unsupported clientContent field "${n}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new a("clientContent.turns must be an array");let o=[];for(let n of t){let r=m(n);if(!r)throw new a("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 a(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);o.push({role:i==="model"?"assistant":"user",content:ue(r,"clientContent.turns")})}return{items:o,turnComplete:e.turnComplete===!0}}var v=16e3,V=24e3,W=`audio/pcm;rate=${V}`,ge=Buffer.alloc(960).toString("base64");function G(e,t,o){if(t===o)return e;let n=Math.floor(e.length*o/t),r=new Int16Array(n),i=t/o,s=e.length-1;for(let c=0;c<n;c++){let u=c*i,d=Math.floor(u);if(d>=s){r[c]=e[s];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function We(e){let t=m(e);if(!t)throw new a("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new a(`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 a("realtimeInput.video.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length<3||o[0]!==255||o[1]!==216)throw new a("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(o)}function Ge(e){let t=m(e);if(!t)throw new a("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new a(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let o=/;\s*rate=(\d+)/.exec(t.mimeType);if(o&&Number(o[1])!==v)throw new a(`realtimeInput.audio.mimeType declares rate=${o[1]} \u2014 the Live spec input format is ${v} Hz (audio/pcm;rate=${v})`);if(typeof t.data!="string"||t.data.length===0)throw new a("realtimeInput.audio.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length===0||n.length%2!==0)throw new a(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${n.length} bytes \u2014 not even)`);let r=new Int16Array(n.length/2);for(let s=0;s<r.length;s++)r[s]=n.readInt16LE(s*2);let i=G(r,v,V);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function ye(e){if(e.mediaChunks!==void 0)throw new a('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 a("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 a(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let n of Object.keys(e))if(!t.includes(n))throw new a(`unsupported realtimeInput field "${n}"`);let o=t.filter(n=>e[n]!==void 0);if(o.length!==1)throw new a(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${o.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:Ge(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:We(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new a("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new a("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function he(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new a(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new a("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let o=m(t);if(!o||typeof o.id!="string"||o.id.length===0)throw new a("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:o.id,output:JSON.stringify(o.response??null)}})}function we(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function ke(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:W,data:e}}]}}}}function be(e){let t=m(e)??{},o=Array.isArray(t.output)?t.output:[],n=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of o){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 o){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new a(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,D);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new a(`upstream function_call arguments are not valid JSON: ${f}`,D)}n.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 s=[];n.length>0&&s.push({toolCall:{functionCalls:n}}),s.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 s.push(u),{messages:s,assistantItems:r}}async function ve(e,t,o){if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((r,i)=>{let s=e.onSynced(()=>{clearTimeout(n),r()});n=setTimeout(()=>{s(),i(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${o} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}function M(e,t,o,n){let r=e.response??{},i={request_id:o,consumer_id:n,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 N(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}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,o=t.body??{},n=o.error,r=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Ee=require("@urun-sh/core/internal");var Je="llm-resp";async function*Ye(e,t){let o=`resp_${e}`,n=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:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let s of i.tool_calls){let c=typeof s.index=="number"?s.index:0,u=n.get(c)??{};s.id&&(u.id=s.id),s.function?.name&&(u.name=s.function.name),n.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:s.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield _e(i);return}}}async function*O(e,t){let o=`${Je}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*Ye(t,e.stream(o).messages())}finally{try{(0,Ee.gcRequest)(e.doc("llm"),t)}catch{}}}var $=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}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,o){return this.writeGated(o,()=>{let n=N(t,o,this.consumerId);return this.write(n),O(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let r=M(t,o,n,this.consumerId);return this.write(r),O(this.session,n)})}async writeGated(t,o){try{await ve(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};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-
|
|
2
|
-
import { b as UrunSessionLike } from './types-
|
|
3
|
-
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-
|
|
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-
|
|
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-C6MpaZS-.cjs';
|
|
2
|
+
import { b as UrunSessionLike } from './types-DiYzfHYN.cjs';
|
|
3
|
+
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-DiYzfHYN.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-A8qMuI36.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-
|
|
2
|
-
import { b as UrunSessionLike } from './types-
|
|
3
|
-
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-
|
|
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-
|
|
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-CaOqL-V8.js';
|
|
2
|
+
import { b as UrunSessionLike } from './types-DiYzfHYN.js';
|
|
3
|
+
export { L as LaneMessage, a as LaneToolCallDelta, U as UrunDocLike, c as UrunStreamLike } from './types-DiYzfHYN.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-IoTqIbAw.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-X5BLQXHK.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-64VO62LW.js";import{a as o,b as t,e as n,f as r}from"./chunk-G6AFKOVS.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};
|