@urun-sh/openai 0.6.53 → 0.6.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/chunk-4UE7XH7T.js +21 -0
  2. package/dist/chunk-BVM4ZQ2Y.js +2 -0
  3. package/dist/{chunk-K5TQMHAY.js → chunk-HLSJAQHY.js} +2 -2
  4. package/dist/{chunk-XGAF2NDT.js → chunk-KNWFUWXY.js} +1 -1
  5. package/dist/{chunk-X5BLQXHK.js → chunk-KV3UXLNF.js} +1 -1
  6. package/dist/chunk-MYNG74AX.js +1 -0
  7. package/dist/{chunk-C452ZIU5.js → chunk-N3Y2GDQK.js} +5 -5
  8. package/dist/{chunk-7IT4XK2K.js → chunk-PPEND4SP.js} +18 -18
  9. package/dist/{chunk-ZWDQPTSH.js → chunk-Z74YK7AL.js} +1 -1
  10. package/dist/{composite-4ppY0Kv6.d.cts → composite-C1oeSkNz.d.cts} +19 -0
  11. package/dist/{composite-BKEde6hP.d.ts → composite-CmDZAzTq.d.ts} +6 -0
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.js +1 -1
  14. package/dist/hosted/bin.cjs +44 -43
  15. package/dist/hosted/bin.js +1 -1
  16. package/dist/hosted/index.cjs +44 -43
  17. package/dist/hosted/index.d.cts +106 -2
  18. package/dist/hosted/index.d.ts +45 -2
  19. package/dist/hosted/index.js +1 -1
  20. package/dist/index.cjs +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/pi-extension/index.cjs +5 -5
  23. package/dist/pi-extension/index.js +1 -1
  24. package/dist/pi-extension/standalone.cjs +22 -22
  25. package/dist/pooler/bin.cjs +12 -12
  26. package/dist/pooler/bin.js +8 -8
  27. package/dist/proxy/cli.cjs +35 -35
  28. package/dist/proxy/cli.js +1 -1
  29. package/dist/proxy/index.cjs +18 -18
  30. package/dist/proxy/index.d.cts +2 -2
  31. package/dist/proxy/index.d.ts +2 -2
  32. package/dist/proxy/index.js +1 -1
  33. package/package.json +2 -2
  34. package/dist/chunk-5PA6542H.js +0 -20
  35. package/dist/chunk-64VO62LW.js +0 -1
  36. package/dist/chunk-D7PBMXB6.js +0 -2
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-C452ZIU5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.53";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
1
+ import{h as m}from"./chunk-N3Y2GDQK.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.55";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
@@ -938,6 +938,16 @@ interface RouteTarget {
938
938
  * session and its usage stay attributed to the CALLER org.
939
939
  */
940
940
  sharedApp?: boolean;
941
+ /**
942
+ * THE REQUESTOR ORG (ENG-636 1.5): the CALLER org that dialed this proxy —
943
+ * sourced from the proxy's authenticated request context at the builder
944
+ * ({@link ModelRouterOptions.callerOrgId}, wired from BackhaulConfig.orgId).
945
+ * A user-triggered cold pick on a SHARED app carries it to the lane demand's
946
+ * create (DIAL SHAPE: requestor = the caller org, provider = the shared
947
+ * org). Absent when the auth context names no org — never a guessed or
948
+ * defaulted id (an absent requestor is the designed standard path).
949
+ */
950
+ callerOrgId?: string;
941
951
  /** Shared lanes only: the catalog id the request pinned (capability joins). */
942
952
  modelId?: string;
943
953
  /** Shared lanes only: the catalog variant the request pinned. */
@@ -1002,6 +1012,13 @@ interface ModelRouterOptions<S> {
1002
1012
  * declared `serves` protocol (see {@link ModelRouter.servable}).
1003
1013
  */
1004
1014
  fnName: string;
1015
+ /**
1016
+ * THE REQUESTOR ORG (ENG-636 1.5): the authenticated CALLER's org id — the
1017
+ * proxy's request context (BackhaulConfig.orgId, resolved from the caller's
1018
+ * API key on the hosted lane). Stamped on every resolved {@link RouteTarget};
1019
+ * absent/empty ⇒ no target ever carries one. No default, no guess.
1020
+ */
1021
+ callerOrgId?: string;
1005
1022
  /**
1006
1023
  * Open a backhaul session for a resolved dial target (called at most once
1007
1024
  * per pool key). The SECOND argument is the POOL KEY the entry will
@@ -1261,6 +1278,8 @@ declare class ModelRouter<S> {
1261
1278
  * SHARED org's app with `sharedApp: true` — the cross-org session dial.
1262
1279
  */
1263
1280
  private resolveTarget;
1281
+ /** The dial resolution itself — {@link resolveTarget} stamps the requestor. */
1282
+ private dialTargetFor;
1264
1283
  /**
1265
1284
  * THE BILLING IDENTITY of a request's model: the CATALOG `(model_id,
1266
1285
  * variant)` the request actually resolved to, or `null` when the route
@@ -305,6 +305,8 @@ interface RouteTarget {
305
305
 
306
306
  sharedApp?: boolean;
307
307
 
308
+ callerOrgId?: string;
309
+
308
310
  modelId?: string;
309
311
 
310
312
  variant?: string;
@@ -323,6 +325,8 @@ interface ModelRouterOptions<S> {
323
325
 
324
326
  fnName: string;
325
327
 
328
+ callerOrgId?: string;
329
+
326
330
  openSession: (target: RouteTarget, poolKey: string) => S | Promise<S>;
327
331
 
328
332
  closeSession: (entry: S) => Promise<void>;
@@ -385,6 +389,8 @@ declare class ModelRouter<S> {
385
389
 
386
390
  private resolveTarget;
387
391
 
392
+ private dialTargetFor;
393
+
388
394
  catalogIdentityFor(model: string | undefined): Promise<{
389
395
  model_id: string;
390
396
  variant: string;
@@ -1,2 +1,2 @@
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),typeof r.model=="string"&&r.model&&(i.model=r.model),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});
1
+ "use strict";var Ae=Object.create;var S=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ie=Object.getPrototypeOf,Re=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))!Re.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(Ie(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:()=>v,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:()=>b,SdkTransport:()=>$,VIDEO_FRAME_MESSAGE_BUDGET:()=>I,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:()=>be,videoOutAck:()=>de,videoOutChunkMsg:()=>ce,weriftAudioBackend:()=>Q});module.exports=Ce(Qe);var x=24e3;var 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",I=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>I)throw new Error(`enableSessionVideo: frame is ${n.byteLength} bytes \u2014 over the ${I}-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 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"),b="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:b,codec:C,framing:H}}var U="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=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 v=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])!==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,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 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)}`,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 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)})}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),typeof r.model=="string"&&r.model&&(i.model=r.model),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 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});
@@ -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-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-AWCC5WRB.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};
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-KV3UXLNF.js";import{a as i,c as s,d as O,e as d,f as a,g as E,h as _,i as p,j as u,k as A,l as S,m as I,n as T,o as l,p as m,q as U,r as V}from"./chunk-MYNG74AX.js";import{a as o,b as t,e as n,f as r}from"./chunk-AWCC5WRB.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};