@urun-sh/openai 0.6.43 → 0.6.45
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-J3KCHTSA.js → chunk-3QZYIRAL.js} +3 -3
- package/dist/chunk-5JTIJPFV.js +6 -0
- package/dist/chunk-64VO62LW.js +1 -0
- package/dist/chunk-7KRHHEKZ.js +1 -0
- package/dist/{chunk-MJSK6W3W.js → chunk-BMSZZYSZ.js} +1 -1
- package/dist/chunk-GCQR62TJ.js +2 -0
- package/dist/chunk-LNQW3VFC.js +66 -0
- package/dist/chunk-NUPHEB3L.js +20 -0
- package/dist/chunk-PXV7QBSD.js +1 -0
- package/dist/{chunk-FF3RWDFM.js → chunk-Q3AIBMET.js} +1 -1
- package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
- package/dist/chunk-XNRPTMSL.js +1 -0
- package/dist/chunk-ZXQXOEVN.js +4 -0
- package/dist/{composite-D4_XPSas.d.ts → composite-BXbbnmL2.d.ts} +10 -1
- package/dist/{composite-BoS9-74g.d.cts → composite-n3axzdCh.d.cts} +35 -1
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +15 -4
- package/dist/gemini-live.d.ts +6 -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 +45 -44
- 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 +2 -2
- 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 +54 -54
- package/dist/pooler/bin.cjs +25 -25
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +52 -51
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +32 -31
- package/dist/proxy/index.d.cts +19 -6
- package/dist/proxy/index.d.ts +11 -6
- 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
- package/dist/chunk-ZCF6EV4Y.js +0 -65
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 Ae=Object.create;var S=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)S(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&&S(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?S(o,"default",{value:e,enumerable:!0}):o,e)),Ce=e=>J(S({},"__esModule",{value:!0}),e);var Qe={};xe(Qe,{AudioBridge:()=>E,CLOSE_PROTOCOL:()=>j,CLOSE_SESSION_GONE:()=>se,CLOSE_UNKNOWN_MODEL:()=>ie,CLOSE_UPSTREAM:()=>V,GEMINI_AUDIO_IN_RATE:()=>b,GEMINI_AUDIO_OUT_MIME:()=>W,GEMINI_AUDIO_OUT_RATE:()=>M,GEMINI_LIVE_PATH:()=>re,GeminiLiveError:()=>a,NATIVE_AUDIO_SAMPLE_RATE:()=>x,OUTBOUND_AUDIO_FLUSH_B64:()=>ge,RT_VIDEO_IN_STREAM:()=>T,RT_VIDEO_OUT_STREAM:()=>v,SdkTransport:()=>$,VIDEO_FRAME_MESSAGE_BUDGET:()=>R,VIDEO_OUT_DEFAULT_CODEC:()=>C,VIDEO_OUT_FRAMING:()=>H,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>U,consumeVideoOut:()=>ne,decodeResponsesLane:()=>A,decodeVideoOutRecord:()=>L,enableSessionAudio:()=>Y,enableSessionVideo:()=>K,encodeVideoOutRecord:()=>Z,goAwayMsg:()=>pe,negotiateSessionVideoOutQuic:()=>ee,nodeAudioBackend:()=>z,openSessionVideoOutLane:()=>te,parseClientMessage:()=>ae,resamplePcm16:()=>G,responseCreateToEnvelope:()=>N,responsesCreateToEnvelope:()=>P,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 x=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 T="rt-video-in",R=256e3;function K(e){let t=e.stream(T),o=t.emit;if(typeof o!="function")throw new Error(`enableSessionVideo: session.stream('${T}') 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>R)throw new Error(`enableSessionVideo: frame is ${n.byteLength} bytes \u2014 over the ${R}-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,I=null;async function Ne(){if(I)return;let e=await import("opusscript");I=e.default??e}function Pe(){if(!I)throw new Error("[opus-guard] opusscript module not loaded");return new I(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 g=new e.RtpHeader({version:2,payloadType:Ve,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"),v="rt-video-out",H="urun.videoOut.v1",C="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 L(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:C,framing:H}}var U="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=L(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:C,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(L(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,V=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,D=["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=D.filter(c=>o[c]!==void 0),r=Object.keys(o).filter(c=>!D.includes(c));if(r.length>0)throw new a(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${D.join(", ")}`);if(n.length!==1)throw new a(`client message must contain exactly one of ${D.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:U,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 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?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,M=24e3,W=`audio/pcm;rate=${M}`,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,M);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)}`,V);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}`,V)}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)})}var Oe=require("@urun-sh/core/internal");function N(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 P(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 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*A(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{(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=P(t,o,this.consumerId);return this.write(n),A(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let r=N(t,o,n,this.consumerId);return this.write(r),A(this.session,n)})}cancelTurn(t){try{(0,Oe.gcRequest)(this.session.doc("llm"),t)}catch{}}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});
|
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;
|
|
@@ -158,6 +158,17 @@ declare class SdkTransport {
|
|
|
158
158
|
role: string;
|
|
159
159
|
content: unknown;
|
|
160
160
|
}>, requestId: string): Promise<AsyncIterable<unknown>>;
|
|
161
|
+
/**
|
|
162
|
+
* THE PROMPT CANCEL TOMBSTONE: null the request marker NOW so the engine
|
|
163
|
+
* releases the in-flight request even when the lane's decode iterator never
|
|
164
|
+
* unwinds — a lane parked on a pull that never settles hangs the
|
|
165
|
+
* fire-and-forget `return()` that would otherwise run this in
|
|
166
|
+
* {@link decodeResponsesLane}'s finally, and the cancelled turn would hold
|
|
167
|
+
* the seat (prod scratch 2026-11-15: every post-cancel turn hit no-capacity).
|
|
168
|
+
* Best-effort by contract (decode.ts parity): a gone doc room must never
|
|
169
|
+
* turn a cancel into a fault.
|
|
170
|
+
*/
|
|
171
|
+
cancelTurn(requestId: string): void;
|
|
161
172
|
/**
|
|
162
173
|
* Run the turn's write + lane subscribe behind {@link ensureDocSynced}. The
|
|
163
174
|
* gate is per-turn: the doc plane may have re-dialed since the last turn
|
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;
|
|
@@ -102,6 +102,8 @@ declare class SdkTransport {
|
|
|
102
102
|
content: unknown;
|
|
103
103
|
}>, requestId: string): Promise<AsyncIterable<unknown>>;
|
|
104
104
|
|
|
105
|
+
cancelTurn(requestId: string): void;
|
|
106
|
+
|
|
105
107
|
private writeGated;
|
|
106
108
|
}
|
|
107
109
|
|
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-PXV7QBSD.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};
|