@urun-sh/openai 0.6.32 → 0.6.34

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 (39) hide show
  1. package/dist/chunk-2L7UL6BM.js +17 -0
  2. package/dist/chunk-6K7NOPD5.js +6 -0
  3. package/dist/chunk-7KRHHEKZ.js +1 -0
  4. package/dist/{chunk-7OH7UJ2H.js → chunk-AVMTHHBR.js} +4 -4
  5. package/dist/{chunk-M3YMNU5P.js → chunk-CY4RJOTS.js} +2 -2
  6. package/dist/chunk-ETX6IX25.js +1 -0
  7. package/dist/{chunk-GL7EWL3V.js → chunk-EV4DZCHN.js} +1 -1
  8. package/dist/{chunk-L6HTHDVV.js → chunk-GQTWIDJ6.js} +1 -1
  9. package/dist/chunk-LDBKLCCU.js +2 -0
  10. package/dist/{composite-DMawda97.d.ts → composite-D4oZXeX4.d.ts} +2 -0
  11. package/dist/{composite-DtBebn0Y.d.cts → composite-DGytPb8F.d.cts} +13 -8
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +0 -26
  14. package/dist/gemini-live.d.ts +0 -5
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +46 -46
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +40 -40
  19. package/dist/hosted/index.d.cts +57 -13
  20. package/dist/hosted/index.d.ts +15 -2
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/pi-extension/index.cjs +7 -7
  25. package/dist/pi-extension/index.js +1 -1
  26. package/dist/pi-extension/standalone.cjs +40 -40
  27. package/dist/pooler/bin.cjs +24 -24
  28. package/dist/pooler/bin.js +23 -23
  29. package/dist/proxy/cli.cjs +37 -37
  30. package/dist/proxy/cli.js +1 -1
  31. package/dist/proxy/index.cjs +20 -20
  32. package/dist/proxy/index.d.cts +2 -2
  33. package/dist/proxy/index.d.ts +2 -2
  34. package/dist/proxy/index.js +1 -1
  35. package/package.json +2 -2
  36. package/dist/chunk-5473ZAQ4.js +0 -17
  37. package/dist/chunk-KTMDSM7F.js +0 -2
  38. package/dist/chunk-NN6TQQUG.js +0 -1
  39. package/dist/chunk-OOCRI7ZM.js +0 -6
@@ -1,6 +1,6 @@
1
- import{g as m}from"./chunk-OOCRI7ZM.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var f="0.6.32";var y=4141,R=f,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(p=>p==="-m"||p==="--model"||p.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),u=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...u]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?g(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let u=(e.URUN_GATEWAY_URL??"").trim(),p=u?g(u):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:p}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function g(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
1
+ import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.34";var y=4141,R=g,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ie(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
5
5
  `)}catch(o){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
6
- `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function se(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}export{J as a,P as b,B as c,K as d,M as e,F as f,H as g,V as h,X as i,z as j,Q as k,N as l,g as m,Z as n,A as o,ee as p,te as q,ne as r,re as s,oe as t,ie as u,se as v};
6
+ `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function se(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}export{J as a,P as b,B as c,K as d,M as e,F as f,H as g,V as h,X as i,z as j,Q as k,N as l,f as m,Z as n,A as o,ee as p,te as q,ne as r,re as s,oe as t,ie as u,se as v};
@@ -0,0 +1 @@
1
+ import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(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}i();function y(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,s=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:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var w="llm-resp";async function*v(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.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:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*l(e,t){let o=`${w}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*v(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var k=class{constructor(t,o=15e3){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),l(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),l(this.session,n)})}async writeGated(t,o){try{await m(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()}};export{_ as a,f as b,y as c,v as d,l as e,k as f};
@@ -1 +1 @@
1
- import{f as r}from"./chunk-NN6TQQUG.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(n){this.transport=new r(n)}responses={create:async n=>{let t=a(),i=await this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*i})(),{requestId:t})}}};export{o as a};
1
+ import{f as r}from"./chunk-ETX6IX25.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(n){this.transport=new r(n)}responses={create:async n=>{let t=a(),i=await this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*i})(),{requestId:t})}}};export{o as a};
@@ -1 +1 @@
1
- import{i as d}from"./chunk-OOCRI7ZM.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
1
+ import{j as d}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
@@ -0,0 +1,2 @@
1
+ import{a as W}from"./chunk-CAR4AEQJ.js";import{f as Z,g as R,h as ee,i as ne}from"./chunk-AVMTHHBR.js";import{c as B,f as H,g as j,p as G}from"./chunk-6M5JK4YC.js";import{a as oe,b as U}from"./chunk-GQTWIDJ6.js";import{a as F}from"./chunk-EV4DZCHN.js";import{b as V,c as q,d as K,g as J,j as D,k as X,l as N,m as Y,p as b,q as Q,r as z}from"./chunk-6K7NOPD5.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as C,createClientToken as ce,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Se,DEFAULT_WHEN_LIVE_TIMEOUT_MS as le,isWakingPhase as Pe,SessionFailedError as Ee}from"@urun-sh/core";A();import{SessionFailedError as me}from"@urun-sh/core";var M=2;function ge(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function we(e){let i=e?.type;return i==="response.completed"||i==="error"}function ie(e){return async function(a,d){let p=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=M;l++){let{app:w,entry:u,identity:h}=l===1?p:await e.sessionFor(a.model);d?.({sessionId:e.sessionIdOf?.(u)??null,identity:h});let s=!1,c=!1;try{let f=await e.createStream(u,a);for await(let g of f){if(we(g)&&(s=!0),ge(g)){if(l>1)continue}else c=!0;yield g}}catch(f){if(f instanceof me&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,u,f)}catch{}throw f}if(l<M&&!c){await e.evict(w,u);continue}throw f}if(s)return;if(l<M&&!c){await e.evict(w,u);continue}return}})()}}import{randomUUID as de}from"crypto";A();var ye="audio";var re=new WeakMap;function ae(e,i,a){let d=e.doc(ye),p=[],r=0,l=0;return{sessionId:i,appendInputAudio(w){let u=Buffer.from(w,"base64");if(u.byteLength===0||(p.push(u),r+=u.byteLength,r<4800))return;let h=Buffer.concat(p,r).toString("base64");if(p=[],r=0,a===void 0){let s=(re.get(e)??0)+1;re.set(e,s),d.set({frames:{[String(s%32)]:{s,pcm16:h}}})}else{let s=++l;d.set({frames:{[`${a}:${s%32}`]:{s,pcm16:h,c:a}}})}},onOutputAudio(){return()=>{}}}}var Oe=0,Ae=4,ve=4;function Je(e,i){let a=(l,w)=>{let u=(e[l]??"").trim();if(!u)return w;let h=Number.parseInt(u,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},d=(e.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let p=d?Number.parseInt(d,10):Oe;if(!Number.isInteger(p)||p<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=a("URUN_DECISION_POOL_MAX",Math.max(p,Ae));return{min:p,max:r,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",ve),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function Xe(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return R;let a=Number.parseInt(i,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function x(e,i,a,d){let p=e[a];if(typeof p!="function")throw new Error(`app "${i}" has no function "${a}" (set URUN_FUNCTION)`);let r=d?p(void 0,d):p();if(typeof r.end!="function")throw new Error(`app "${i}" function "${a}" returned a session without end()`);return r}function ue(e,i,a,d){let{baseUrl:p,orgId:r,auth:l}=e,w=i.fnName??e.fnName,u=e.sessionStartOptions?.(a),h=d||u||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...u,...d}:void 0,s=y=>({session:y,responses:new F(y),gone:oe(y,a)});if(l.lane==="jwt"){let y=C(i.appSlug,{baseUrl:p,orgId:r,jwt:l.jwt});return s(x(y,i.appSlug,w,h))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:k}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??de(),n=C(i.appSlug,{baseUrl:p,orgId:r,getAccessToken:async()=>(await ce(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(n,i.appSlug,w,h))}let{apiKey:c,gatewayUrl:f}=l,g=(typeof e.subject=="function"?e.subject():e.subject)??de(),S=C(i.appSlug,{baseUrl:p,orgId:r,getAccessToken:async()=>(await ce(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:g,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(S,i.appSlug,w,h))}function be(e){let i=e.session.id;if(typeof i!="string"||i.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return i}function fe(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,a=e.status.error?.code;return i===410||i===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Ie=new Set(["error","paused"]);function Ye(e){let{auth:i,catalog:a}=e,d=null,p=(l,w)=>{let u=ue(e,l,w);return e.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&e.onSessionOpen(w,u.session.id),u.gone.onGone(()=>{d?.evict(w,u)}),u},r=new z({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:p,closeSession:async l=>{if(l.gone.dispose(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:i.lane==="api-key"?()=>Y({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(a?()=>W(a):null),listPrices:a?()=>K(a):null,shared:i.lane==="api-key"?()=>q({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return V(l)}:null,sessionKey:be});return d=r,e.defaultApp!==null&&r.seed(e.defaultApp,p({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Qe(e,i){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",p=new Map,r=new Map,l=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
2
+ `)},u=(s,c)=>{let f=p.get(c);if(f)return f;let g=new Z({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:d,openSlot:async S=>{let y=ue(e,s,c,{concurrencyKey:S.concurrencyKey});return y.gone.onGone(()=>g.markSessionDead(y)),await L(y.session),w(`slot attached pool=${c} slot=${S.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async S=>{S.gone.dispose(),await S.session.end()},onDetach:(S,y)=>w(`slot detached pool=${c} slot=${S.concurrencyKey} reason=${y}`),terminalOpenFailure:S=>S instanceof Ee&&fe(S)});return r.set(c,{target:s,env:a}),p.set(c,g),g},h=async(s,c)=>{let f=r.get(c);if(f)try{let g=await i.poolTuningFor(s);u(s,c).retune({min:g?.min??f.env.min,max:g?.max??f.env.max,inFlightCap:g?.in_flight_cap??f.env.inFlightCap,idleGraceMs:g?.idle_grace_s!==void 0?g.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:g?.warm_wait_s!==void 0?g.warm_wait_s*1e3:void 0})}catch(g){w(`pool tuning refresh failed pool=${c} reason=${g instanceof Error?g.message:String(g)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await u(s,b(s)).boot()},async sessionFor(s){let c=await i.resolveTargetFor(s),f=b(c),g=u(c,f);await h(c,f);let S=await g.acquire({timeoutMs:g.requestWaitMs}),y=l.get(S.entry)??[];return y.push(S),l.set(S.entry,y),{app:f,entry:S.entry,identity:Q(c)}},async warmFor(s){let c=await i.resolveTargetFor(s);await u(c,b(c)).boot()},end(s){let c=l.get(s)?.shift();c&&(l.get(s)?.length===0&&l.delete(s),c.release())},evict(s){for(let c of p.values())c.evict(s)},markSessionDead(s){for(let c of p.values())c.markSessionDead(s)},reap(){for(let[s,{target:c}]of r)h(c,s).then(()=>{let f=p.get(s);f&&f.reap()})},async pingReady(s){for(let c of p.values())if(await c.pingReady(s))return!0;return!1},stats(){return[...p.entries()].map(([s,c])=>({poolKey:s,...c.stats()}))},async drain(s){await Promise.all([...p.values()].map(c=>c.drain({timeoutMs:s})))},async close(){await Promise.all([...p.values()].map(s=>s.close()))}}}function _e(e){return Pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le:Se:le}async function L(e,i){let a=e.whenLive;if(typeof a!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await a.call(e,{timeout:_e(e.phase),signal:i})}async function pe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function ze(e,i=j,a,d,p=R,r){let l=new WeakMap,w=new WeakMap,u=new WeakMap,h=new WeakMap,s=new WeakMap,c=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},f="lane",g=n=>{let o=N(n);if(!r||!o||o.app!==f)return null;let t=r.entryFor(o.key);if(!t)throw new D(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},S=async n=>g(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=l.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let m=await B(n.session,await i());return Object.assign(m,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=h.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:m=>t.appendInputAudio(m),onOutputAudio:m=>t.onOutputAudio(m),sessionId:c(n)}})(),h.set(n,o),o.catch(()=>{h.get(n)===o&&h.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(l.get(n)===void 0||E!==void 0&&E.waiting===0)&&await pe(n.session),_(t)}let m=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?m:new Promise((E,O)=>{let v=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),l.delete(n),h.delete(n),pe(n.session).catch(()=>{})),O(_(t))};t.addEventListener("abort",v,{once:!0});let $=()=>t.removeEventListener("abort",v);m.then(T=>{$(),E(T)},T=>{$(),O(T)})})};return{createResponse:ie({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return d?d.sessionFor(n):e.sessionFor(n)}:d?n=>d.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>c(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):d?d.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{fe(t)&&(r&&r.owns(o)?r.evict(o):d?d.markSessionDead(o):e.evict(n,o),a?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=ee(U(await n.responses.responses.create(o),n.gone),p);if(!d&&!r)return t;let m=n;return(async function*(){try{yield*t}catch(E){throw ne(E)&&(r&&r.owns(m)?r.evict(m):d&&(E instanceof D?d.markSessionDead(m):d.evict(m))),E}finally{r&&r.owns(m)?r.release(m):d?.end(m)}})()}catch(t){throw r&&r.owns(n)?r.release(n):d&&d.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let m=g(n);if(m)return ae(m.entry.session,m.laneId,t);let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await S(n);yield*J(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=H(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=u.get(o);return t||(t=G(o.session),u.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),m=c(t.entry);if(m===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return X(f,m)}}return(await e.handleFor(n)).handle},releaseSessionHandle:n=>{let o=N(n);if(!r||o?.app!==f)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let m=await S(n);await L(m.session);let P=t!==void 0&&g(n)?new F({...m.session,consumerId:t}):m.responses;return U(await P.responses.create(o),m.gone)},onSessionEnd:async(n,o)=>{let t=g(n);if(t)return t.entry.gone.onGone(O=>o({timeLeftMs:null,reason:O.message}));let{entry:m}=await e.sessionForHandle(n),P=m.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(O=>{if(E||!Ie.has(O.name))return;E=!0;let v=P.endsAt??null;o({timeLeftMs:v?Math.max(0,v.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}export{Je as a,Xe as b,Ye as c,Qe as d,ze as e};
@@ -640,6 +640,8 @@ interface ProxyHandlerOptions {
640
640
  openaiType: string;
641
641
  anthropicType: string;
642
642
  operatorDetail?: string;
643
+
644
+ code?: string;
643
645
  } | null;
644
646
 
645
647
  requestLog?: (line: string) => void;
@@ -1884,7 +1884,8 @@ interface LedgerRecorded {
1884
1884
  * Why the row carries no price, or null when it is priced. One of
1885
1885
  * `not_a_catalog_model` | `outcome_not_billable` | `http_status_not_success`
1886
1886
  * | `task_unit_undeclared` | `task_not_token_billed` | `token_counts_absent`
1887
- * | `output_minutes_absent` | `no_active_price` | `no_active_input_price` |
1887
+ * | `output_minutes_absent` | `output_units_absent` |
1888
+ * `session_seconds_absent` | `no_active_price` | `no_active_input_price` |
1888
1889
  * `no_active_output_price`.
1889
1890
  * It is a NORMAL answer, not an error: no PER-TOKEN rate has been seeded
1890
1891
  * yet, so this lane has nothing to price with. (Not "the price book is
@@ -1901,13 +1902,14 @@ interface LedgerRecorded {
1901
1902
  * TASK DECLARES (`public.task_billing_units`), never in the unit the data
1902
1903
  * happens to look like:
1903
1904
  *
1904
- * * `task_not_token_billed` — this lane's billable quantity is not tokens
1905
- * (an image lane's is {@link LedgerWrite.output_units}), so its token counts are not
1906
- * a price for it. A genuine `{0, 0}` receipt on such a lane would
1907
- * otherwise settle at `cost_nano_usd = 0` PERMANENTLY — the control
1908
- * plane's append-only rule allows a deliberate re-price and never a
1909
- * return to NULL — which is an invoice asserting the work was free when
1910
- * its billable quantity was never measured.
1905
+ * * `task_not_token_billed` — the task's declared billing unit has no
1906
+ * arithmetic rung in the writer (the CHECK vocabulary accepts units the
1907
+ * ladder does not price, e.g. `per_request`), so nothing is priced.
1908
+ * A genuine `{0, 0}` receipt on such a lane would otherwise settle at
1909
+ * `cost_nano_usd = 0` PERMANENTLY — the control plane's append-only
1910
+ * rule allows a deliberate re-price and never a return to NULL —
1911
+ * which is an invoice asserting the work was free when its billable
1912
+ * quantity was never measured.
1911
1913
  * * `task_unit_undeclared` — nobody has declared what this task bills in,
1912
1914
  * so nothing is priced. Adding a lane to {@link ledgerTaskOf} without a
1913
1915
  * matching declaration fails CLOSED and says which fix it wants.
@@ -2657,6 +2659,9 @@ interface ProxyHandlerOptions {
2657
2659
  openaiType: string;
2658
2660
  anthropicType: string;
2659
2661
  operatorDetail?: string;
2662
+ /** The machine-readable `error.code` for envelopes that carry one (the
2663
+ * Anthropic envelope never does). Absent = the body carries no code. */
2664
+ code?: string;
2660
2665
  } | null;
2661
2666
  /**
2662
2667
  * Where the per-request structured log line goes — ONE newline-terminated
@@ -1,2 +1,2 @@
1
- "use strict";var _e=Object.create;var E=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Ee=(e,t)=>{for(var n in t)E(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ve(t))!Ae.call(e,r)&&r!==n&&E(e,r,{get:()=>t[r],enumerable:!(o=be(t,r))||o.enumerable});return e};var $=(e,t,n)=>(n=e!=null?_e(Oe(e)):{},W(t||!e||!e.__esModule?E(n,"default",{value:e,enumerable:!0}):n,e)),Se=e=>W(E({},"__esModule",{value:!0}),e);var He={};Ee(He,{AudioBridge:()=>O,CLOSE_PROTOCOL:()=>H,CLOSE_SESSION_GONE:()=>re,CLOSE_UNKNOWN_MODEL:()=>oe,CLOSE_UPSTREAM:()=>U,GEMINI_AUDIO_IN_RATE:()=>b,GEMINI_AUDIO_OUT_MIME:()=>F,GEMINI_AUDIO_OUT_RATE:()=>D,GEMINI_LIVE_PATH:()=>ne,GeminiLiveError:()=>s,NATIVE_AUDIO_SAMPLE_RATE:()=>R,OUTBOUND_AUDIO_FLUSH_B64:()=>pe,RT_VIDEO_IN_STREAM:()=>S,RT_VIDEO_OUT_STREAM:()=>_,SdkTransport:()=>P,VIDEO_FRAME_MESSAGE_BUDGET:()=>T,VIDEO_OUT_DEFAULT_CODEC:()=>I,VIDEO_OUT_FRAMING:()=>B,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>C,consumeVideoOut:()=>ee,decodeResponsesLane:()=>A,decodeVideoOutRecord:()=>x,enableSessionAudio:()=>J,enableSessionVideo:()=>Y,encodeVideoOutRecord:()=>z,goAwayMsg:()=>le,negotiateSessionVideoOutQuic:()=>X,nodeAudioBackend:()=>K,openSessionVideoOutLane:()=>Z,parseClientMessage:()=>ie,resamplePcm16:()=>j,responseCreateToEnvelope:()=>V,responsesCreateToEnvelope:()=>M,serverContentOfAudio:()=>we,serverContentOfDelta:()=>ye,sessionResumptionUpdateMsg:()=>ce,translateClientContent:()=>fe,translateRealtimeInput:()=>me,translateSetup:()=>de,translateToolResponse:()=>ge,turnEndOfCompleted:()=>he,videoOutAck:()=>ae,videoOutChunkMsg:()=>ue,weriftAudioBackend:()=>q});module.exports=Se(He);var R=24e3,G="audio",O=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),o=Math.floor(n.byteLength/2),r=new Int16Array(o);for(let i=0;i<o;i++)r[i]=n.readInt16LE(i*2);this.source.onData(r)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let o=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function J(e,t,n=1e4){let o=new O(t,{sampleRate:24e3}),r=await o.startOutbound();await e.stream(G).attach(r);let i=await Te(e,n);return await o.startInbound(i),o}function Te(e,t){let n=e.stream(G);return n.track!=null?Promise.resolve(n.track):new Promise((o,r)=>{let i,a=setTimeout(()=>{i?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),c=u=>{u!=null&&(clearTimeout(a),i?.(),o(u))};i=n.on?.("track",c),n.track!=null&&c(n.track)})}var S="rt-video-in",T=256e3;function Y(e){let t=e.stream(S),n=t.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${S}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>T)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${T}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(t,o)}}}var Re=24e3,v=480,Ie=111;async function xe(){let e=await import("opusscript"),t=e.default??e;return new t(Re,1,2048)}async function q(){let e=await import("werift"),t=await xe();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:c=>{let u=new Int16Array(a.length+c.length);u.set(a,0),u.set(c,a.length);let d=0;for(;u.length-d>=v;){let l=u.subarray(d,d+v);d+=v;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,v);r=r+1&65535,i=i+v>>>0;let g=new e.RtpHeader({version:2,payloadType:Ie,sequenceNumber:r,timestamp:i,ssrc:o,marker:!1}),h=new e.RtpPacket(g,p);n.writeRtp(h)}a=u.slice(d)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(i=>{let a;try{a=t.decode(i.payload)}catch{return}let c=new Int16Array(a.length/2);for(let u=0;u<c.length;u++)c[u]=a.readInt16LE(u*2);o.onframe?.({samples:c})}),o}}}async function K(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:o=>t.onData({samples:o,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},o=new e.nonstandard.RTCAudioSink(t);return o.ondata=r=>{n.onframe?.(r)},n}}}var w=require("@urun-sh/core"),_="rt-video-out",B="urun.videoOut.v1",I="h264";function Q(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function z(e,t){if(Q(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let o=new Uint8Array(2+n.byteLength+t.byteLength);return o[0]=n.byteLength&255,o[1]=n.byteLength>>8,o.set(n,2),o.set(t,2+n.byteLength),o}function x(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let o=n;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Q(r,"decodeVideoOutRecord");let i=e.subarray(2+t);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:i.slice()}}async function X(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),o=n.sessionId??e.sessionId;if(typeof o!="string"||o.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:o,stream:_,codec:I,framing:B}}var C="urun.videoOut.v2-ws";function Z(e){let t=e.stream(_);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${_}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,o=new Set,r=new Set,i=u=>{for(let d of o)d(u)},a=!1,c=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${_}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=x(u)}catch(l){i(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of r)u()};return{codec:I,onOutputFrame:u=>(n.add(u),a||(a=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function Ce(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function ee(e,t,n){let o=n??(typeof globalThis.WebTransport=="function"?(d,l)=>new globalThis.WebTransport(d,l):void 0);if(!o)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let r=o(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:Ce(d)}))});await r.ready;let i=await r.createBidirectionalStream();await i.writable.getWriter().write((0,w.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=i.readable.getReader(),c=new w.WtControlDecoder,u=!1;for(;!u;){let{value:d,done:l}=await a.read();if(l)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let f of c.push(d)){if(f.t==="hello-ack"){u=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await(0,w.consumeWtDataStreams)(r.incomingUnidirectionalStreams,{onData:(d,l)=>{if(d===e.stream){if(l===w.STREAM_END){t.onEnd?.();return}if(!(l instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(x(l))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:d=>t.onLaneError(d)})}var ne="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",H=1007,oe=1008,U=1011,re=1008,s=class extends Error{constructor(n,o=H){super(n);this.closeCode=o}closeCode},m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,L=["setup","clientContent","realtimeInput","toolResponse"];function ie(e){let t;try{t=JSON.parse(e)}catch{throw new s("client message is not valid JSON")}let n=m(t);if(!n)throw new s("client message must be a JSON object");let o=L.filter(c=>n[c]!==void 0),r=Object.keys(n).filter(c=>!L.includes(c));if(r.length>0)throw new s(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${L.join(", ")}`);if(o.length!==1)throw new s(`client message must contain exactly one of ${L.join(", ")} (got ${o.length})`);let i=o[0],a=m(n[i]);if(!a)throw new s(`"${i}" must be a JSON object`);return{kind:i,[i]:a}}function se(e,t){if(typeof e=="string")return e;let n=m(e),o=n?n.parts:void 0;if(!Array.isArray(o))throw new s(`${t}: expected a Content with a parts array`);let r=[];for(let i of o){let a=m(i);if(a&&typeof a.text=="string"){r.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new s(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new s(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new s(`${t}: unsupported part ${JSON.stringify(i)}`)}return r.join(`
2
- `)}var Le={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function ae(e){return{framing:C,codec:e}}function ue(e){let{seq:t,ptsUs:n,codec:o,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:n,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var Ue={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},De=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],te=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Ve(e){let t=m(e);if(!t)throw new s("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new s(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new s("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new s(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new s("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!te.includes(t.activityHandling))throw new s(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${te.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var Me=["temperature","maxOutputTokens","responseModalities"];function de(e){for(let[f,p]of Object.entries(Ue))if(e[f]!==void 0)throw new s(p);for(let f of Object.keys(e))if(!De.includes(f))throw new s(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new s('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),n,o,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new s("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!Me.includes(f))throw new s(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new s("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new s("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let f=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of f){let g=String(p).toUpperCase();if(g==="AUDIO"){r=!0;continue}if(g!=="TEXT")throw new s(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:se(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new s("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new s("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new s(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new s("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let h=m(g);if(!h||typeof h.name!="string")throw new s("functionDeclarations entries require a string name");c.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}c.length===0&&(c=void 0)}let u={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=m(e.sessionResumption);if(!f)throw new s("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new s(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new s("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?Le:Ve(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new s(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:n,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function ce(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function le(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function fe(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new s(`unsupported clientContent field "${o}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new s("clientContent.turns must be an array");let n=[];for(let o of t){let r=m(o);if(!r)throw new s("clientContent.turns entries must be Content objects");let i=r.role===void 0?"user":String(r.role).toLowerCase();if(i!=="user"&&i!=="model")throw new s(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:i==="model"?"assistant":"user",content:se(r,"clientContent.turns")})}return{items:n,turnComplete:e.turnComplete===!0}}var b=16e3,D=24e3,F=`audio/pcm;rate=${D}`,pe=Buffer.alloc(960).toString("base64");function j(e,t,n){if(t===n)return e;let o=Math.floor(e.length*n/t),r=new Int16Array(o),i=t/n,a=e.length-1;for(let c=0;c<o;c++){let u=c*i,d=Math.floor(u);if(d>=a){r[c]=e[a];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function Ne(e){let t=m(e);if(!t)throw new s("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new s("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Pe(e){let t=m(e);if(!t)throw new s("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(t.mimeType);if(n&&Number(n[1])!==b)throw new s(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length===0||o.length%2!==0)throw new s(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let a=0;a<r.length;a++)r[a]=o.readInt16LE(a*2);let i=j(r,b,D);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function me(e){if(e.mediaChunks!==void 0)throw new s('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new s("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",i=m(e[r]);if(!i||Object.keys(i).length!==0)throw new s(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!t.includes(o))throw new s(`unsupported realtimeInput field "${o}"`);let n=t.filter(o=>e[o]!==void 0);if(n.length!==1)throw new s(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${n.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:Pe(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Ne(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new s("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new s("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function ge(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new s(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new s("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let n=m(t);if(!n||typeof n.id!="string"||n.id.length===0)throw new s("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function ye(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function we(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:F,data:e}}]}}}}function he(e){let t=m(e)??{},n=Array.isArray(t.output)?t.output:[],o=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of n){let l=m(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let f of l.content){let p=m(f);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&r.push({role:"assistant",content:i});for(let d of n){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new s(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,U);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new s(`upstream function_call arguments are not valid JSON: ${f}`,U)}o.push({id:l.call_id,name:l.name,args:p}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:f})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let c=m(t.usage),u={serverContent:{turnComplete:!0}};if(c){let d={};typeof c.input_tokens=="number"&&(d.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(d.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(d.totalTokenCount=c.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return a.push(u),{messages:a,assistantItems:r}}function V(e,t,n,o){let r=e.response??{},i={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(i.instructions=r.instructions),Array.isArray(r.modalities)&&(i.modalities=r.modalities),typeof r.temperature=="number"&&(i.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(i.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(i.tools=r.tools),i}function M(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(o.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(o.response_format=e.response_format),typeof e.voice=="string"&&(o.voice=e.voice),typeof e.language=="string"&&(o.language=e.language),o}function ke(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},o=n.error,r=o?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:o?.type??"urun_error",code:t.code??o?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var $e="llm-resp";async function*Be(e,t){let n=`resp_${e}`,o=new Map;for await(let r of t){let i=r;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=o.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield ke(i);return}}}async function*A(e,t){let n=`${$e}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*Be(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var P=class e{constructor(t,n=e.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let t=this.session.doc("llm");if(t.synced===!0||typeof t.onSynced!="function")return;let n;await new Promise((r,i)=>{let a=t.onSynced(()=>{clearTimeout(n),r()});n=setTimeout(()=>{a(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let o=M(t,n,this.consumerId);return this.write(o),A(this.session,n)})}sendResponseCreate(t,n,o){return this.writeGated(o,()=>{let r=V(t,n,o,this.consumerId);return this.write(r),A(this.session,o)})}async writeGated(t,n){try{await this.ensureDocSynced()}catch(o){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${o instanceof Error?o.message:String(o)}`)}return n()}};0&&(module.exports={AudioBridge,CLOSE_PROTOCOL,CLOSE_SESSION_GONE,CLOSE_UNKNOWN_MODEL,CLOSE_UPSTREAM,GEMINI_AUDIO_IN_RATE,GEMINI_AUDIO_OUT_MIME,GEMINI_AUDIO_OUT_RATE,GEMINI_LIVE_PATH,GeminiLiveError,NATIVE_AUDIO_SAMPLE_RATE,OUTBOUND_AUDIO_FLUSH_B64,RT_VIDEO_IN_STREAM,RT_VIDEO_OUT_STREAM,SdkTransport,VIDEO_FRAME_MESSAGE_BUDGET,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_SETUP_KEY,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeResponsesLane,decodeVideoOutRecord,enableSessionAudio,enableSessionVideo,encodeVideoOutRecord,goAwayMsg,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,parseClientMessage,resamplePcm16,responseCreateToEnvelope,responsesCreateToEnvelope,serverContentOfAudio,serverContentOfDelta,sessionResumptionUpdateMsg,translateClientContent,translateRealtimeInput,translateSetup,translateToolResponse,turnEndOfCompleted,videoOutAck,videoOutChunkMsg,weriftAudioBackend});
1
+ "use strict";var be=Object.create;var E=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Se=(e,t)=>{for(var n in t)E(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Oe(t))!Ee.call(e,r)&&r!==n&&E(e,r,{get:()=>t[r],enumerable:!(o=ve(t,r))||o.enumerable});return e};var $=(e,t,n)=>(n=e!=null?be(Ae(e)):{},W(t||!e||!e.__esModule?E(n,"default",{value:e,enumerable:!0}):n,e)),Te=e=>W(E({},"__esModule",{value:!0}),e);var je={};Se(je,{AudioBridge:()=>O,CLOSE_PROTOCOL:()=>H,CLOSE_SESSION_GONE:()=>re,CLOSE_UNKNOWN_MODEL:()=>oe,CLOSE_UPSTREAM:()=>U,GEMINI_AUDIO_IN_RATE:()=>b,GEMINI_AUDIO_OUT_MIME:()=>F,GEMINI_AUDIO_OUT_RATE:()=>D,GEMINI_LIVE_PATH:()=>ne,GeminiLiveError:()=>s,NATIVE_AUDIO_SAMPLE_RATE:()=>R,OUTBOUND_AUDIO_FLUSH_B64:()=>pe,RT_VIDEO_IN_STREAM:()=>S,RT_VIDEO_OUT_STREAM:()=>_,SdkTransport:()=>P,VIDEO_FRAME_MESSAGE_BUDGET:()=>T,VIDEO_OUT_DEFAULT_CODEC:()=>I,VIDEO_OUT_FRAMING:()=>B,VIDEO_OUT_SETUP_KEY:()=>k,VIDEO_OUT_WS_FRAMING:()=>C,consumeVideoOut:()=>ee,decodeResponsesLane:()=>A,decodeVideoOutRecord:()=>x,enableSessionAudio:()=>J,enableSessionVideo:()=>Y,encodeVideoOutRecord:()=>z,goAwayMsg:()=>le,negotiateSessionVideoOutQuic:()=>X,nodeAudioBackend:()=>K,openSessionVideoOutLane:()=>Z,parseClientMessage:()=>ie,resamplePcm16:()=>j,responseCreateToEnvelope:()=>V,responsesCreateToEnvelope:()=>M,serverContentOfAudio:()=>we,serverContentOfDelta:()=>ye,sessionResumptionUpdateMsg:()=>ce,translateClientContent:()=>fe,translateRealtimeInput:()=>me,translateSetup:()=>de,translateToolResponse:()=>ge,turnEndOfCompleted:()=>he,videoOutAck:()=>ae,videoOutChunkMsg:()=>ue,weriftAudioBackend:()=>q});module.exports=Te(je);var R=24e3,G="audio",O=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),o=Math.floor(n.byteLength/2),r=new Int16Array(o);for(let i=0;i<o;i++)r[i]=n.readInt16LE(i*2);this.source.onData(r)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let o=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function J(e,t,n=1e4){let o=new O(t,{sampleRate:24e3}),r=await o.startOutbound();await e.stream(G).attach(r);let i=await Re(e,n);return await o.startInbound(i),o}function Re(e,t){let n=e.stream(G);return n.track!=null?Promise.resolve(n.track):new Promise((o,r)=>{let i,a=setTimeout(()=>{i?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),c=u=>{u!=null&&(clearTimeout(a),i?.(),o(u))};i=n.on?.("track",c),n.track!=null&&c(n.track)})}var S="rt-video-in",T=256e3;function Y(e){let t=e.stream(S),n=t.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${S}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>T)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${T}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(t,o)}}}var Ie=24e3,v=480,xe=111;async function Ce(){let e=await import("opusscript"),t=e.default??e;return new t(Ie,1,2048)}async function q(){let e=await import("werift"),t=await Ce();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:c=>{let u=new Int16Array(a.length+c.length);u.set(a,0),u.set(c,a.length);let d=0;for(;u.length-d>=v;){let l=u.subarray(d,d+v);d+=v;let f=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=t.encode(f,v);r=r+1&65535,i=i+v>>>0;let g=new e.RtpHeader({version:2,payloadType:xe,sequenceNumber:r,timestamp:i,ssrc:o,marker:!1}),h=new e.RtpPacket(g,p);n.writeRtp(h)}a=u.slice(d)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(i=>{let a;try{a=t.decode(i.payload)}catch{return}let c=new Int16Array(a.length/2);for(let u=0;u<c.length;u++)c[u]=a.readInt16LE(u*2);o.onframe?.({samples:c})}),o}}}async function K(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:o=>t.onData({samples:o,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},o=new e.nonstandard.RTCAudioSink(t);return o.ondata=r=>{n.onframe?.(r)},n}}}var w=require("@urun-sh/core"),_="rt-video-out",B="urun.videoOut.v1",I="h264";function Q(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function z(e,t){if(Q(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let o=new Uint8Array(2+n.byteLength+t.byteLength);return o[0]=n.byteLength&255,o[1]=n.byteLength>>8,o.set(n,2),o.set(t,2+n.byteLength),o}function x(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let o=n;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Q(r,"decodeVideoOutRecord");let i=e.subarray(2+t);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:i.slice()}}async function X(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),o=n.sessionId??e.sessionId;if(typeof o!="string"||o.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:o,stream:_,codec:I,framing:B}}var C="urun.videoOut.v2-ws";function Z(e){let t=e.stream(_);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${_}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,o=new Set,r=new Set,i=u=>{for(let d of o)d(u)},a=!1,c=async()=>{for await(let u of t.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${_}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=x(u)}catch(l){i(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of r)u()};return{codec:I,onOutputFrame:u=>(n.add(u),a||(a=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function Le(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function ee(e,t,n){let o=n??(typeof globalThis.WebTransport=="function"?(d,l)=>new globalThis.WebTransport(d,l):void 0);if(!o)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let r=o(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:Le(d)}))});await r.ready;let i=await r.createBidirectionalStream();await i.writable.getWriter().write((0,w.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=i.readable.getReader(),c=new w.WtControlDecoder,u=!1;for(;!u;){let{value:d,done:l}=await a.read();if(l)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let f of c.push(d)){if(f.t==="hello-ack"){u=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await(0,w.consumeWtDataStreams)(r.incomingUnidirectionalStreams,{onData:(d,l)=>{if(d===e.stream){if(l===w.STREAM_END){t.onEnd?.();return}if(!(l instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(x(l))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:d=>t.onLaneError(d)})}var ne="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",H=1007,oe=1008,U=1011,re=1008,s=class extends Error{constructor(n,o=H){super(n);this.closeCode=o}closeCode},m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,L=["setup","clientContent","realtimeInput","toolResponse"];function ie(e){let t;try{t=JSON.parse(e)}catch{throw new s("client message is not valid JSON")}let n=m(t);if(!n)throw new s("client message must be a JSON object");let o=L.filter(c=>n[c]!==void 0),r=Object.keys(n).filter(c=>!L.includes(c));if(r.length>0)throw new s(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${L.join(", ")}`);if(o.length!==1)throw new s(`client message must contain exactly one of ${L.join(", ")} (got ${o.length})`);let i=o[0],a=m(n[i]);if(!a)throw new s(`"${i}" must be a JSON object`);return{kind:i,[i]:a}}function se(e,t){if(typeof e=="string")return e;let n=m(e),o=n?n.parts:void 0;if(!Array.isArray(o))throw new s(`${t}: expected a Content with a parts array`);let r=[];for(let i of o){let a=m(i);if(a&&typeof a.text=="string"){r.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new s(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new s(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new s(`${t}: unsupported part ${JSON.stringify(i)}`)}return r.join(`
2
+ `)}var Ue={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},k="urun.videoOut";function ae(e){return{framing:C,codec:e}}function ue(e){let{seq:t,ptsUs:n,codec:o,key:r}=e.header;return{[k]:{v:1,seq:t,ptsUs:n,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var De={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ve=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",k],te=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Me(e){let t=m(e);if(!t)throw new s("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new s(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=m(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new s("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new s(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new s("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!te.includes(t.activityHandling))throw new s(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${te.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var Ne=["temperature","maxOutputTokens","responseModalities"];function de(e){for(let[f,p]of Object.entries(De))if(e[f]!==void 0)throw new s(p);for(let f of Object.keys(e))if(!Ve.includes(f))throw new s(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new s('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),n,o,r=!1,i=m(e.generationConfig);if(e.generationConfig!==void 0&&!i)throw new s("setup.generationConfig must be an object");if(i){for(let f of Object.keys(i))if(!Ne.includes(f))throw new s(`unsupported generationConfig field "${f}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new s("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new s("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let f=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of f){let g=String(p).toUpperCase();if(g==="AUDIO"){r=!0;continue}if(g!=="TEXT")throw new s(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:se(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new s("setup.tools must be an array");c=[];for(let f of e.tools){let p=m(f);if(!p)throw new s("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new s(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new s("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let h=m(g);if(!h||typeof h.name!="string")throw new s("functionDeclarations entries require a string name");c.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}c.length===0&&(c=void 0)}let u={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=m(e.sessionResumption);if(!f)throw new s("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(f))if(p!=="handle")throw new s(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new s("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?Ue:Me(e.realtimeInputConfig),l=!1;if(e[k]!==void 0){if(!m(e[k]))throw new s(`setup["${k}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:n,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:u,videoOut:l}}function ce(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function le(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function fe(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new s(`unsupported clientContent field "${o}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new s("clientContent.turns must be an array");let n=[];for(let o of t){let r=m(o);if(!r)throw new s("clientContent.turns entries must be Content objects");let i=r.role===void 0?"user":String(r.role).toLowerCase();if(i!=="user"&&i!=="model")throw new s(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:i==="model"?"assistant":"user",content:se(r,"clientContent.turns")})}return{items:n,turnComplete:e.turnComplete===!0}}var b=16e3,D=24e3,F=`audio/pcm;rate=${D}`,pe=Buffer.alloc(960).toString("base64");function j(e,t,n){if(t===n)return e;let o=Math.floor(e.length*n/t),r=new Int16Array(o),i=t/n,a=e.length-1;for(let c=0;c<o;c++){let u=c*i,d=Math.floor(u);if(d>=a){r[c]=e[a];continue}let l=u-d;r[c]=Math.round(e[d]+(e[d+1]-e[d])*l)}return r}function Pe(e){let t=m(e);if(!t)throw new s("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new s("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function $e(e){let t=m(e);if(!t)throw new s("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new s(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(t.mimeType);if(n&&Number(n[1])!==b)throw new s(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new s("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length===0||o.length%2!==0)throw new s(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let a=0;a<r.length;a++)r[a]=o.readInt16LE(a*2);let i=j(r,b,D);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function me(e){if(e.mediaChunks!==void 0)throw new s('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new s("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",i=m(e[r]);if(!i||Object.keys(i).length!==0)throw new s(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!t.includes(o))throw new s(`unsupported realtimeInput field "${o}"`);let n=t.filter(o=>e[o]!==void 0);if(n.length!==1)throw new s(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${n.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:$e(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Pe(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new s("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new s("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function ge(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new s(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new s("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let n=m(t);if(!n||typeof n.id!="string"||n.id.length===0)throw new s("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function ye(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function we(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:F,data:e}}]}}}}function he(e){let t=m(e)??{},n=Array.isArray(t.output)?t.output:[],o=[],r=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let d of n){let l=m(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let f of l.content){let p=m(f);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&r.push({role:"assistant",content:i});for(let d of n){let l=m(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new s(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,U);let f=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(f)}catch{throw new s(`upstream function_call arguments are not valid JSON: ${f}`,U)}o.push({id:l.call_id,name:l.name,args:p}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:f})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let c=m(t.usage),u={serverContent:{turnComplete:!0}};if(c){let d={};typeof c.input_tokens=="number"&&(d.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(d.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(d.totalTokenCount=c.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return a.push(u),{messages:a,assistantItems:r}}async function ke(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let o;await new Promise((r,i)=>{let a=e.onSynced(()=>{clearTimeout(o),r()});o=setTimeout(()=>{a(),i(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}function V(e,t,n,o){let r=e.response??{},i={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(i.instructions=r.instructions),Array.isArray(r.modalities)&&(i.modalities=r.modalities),typeof r.temperature=="number"&&(i.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(i.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(i.tools=r.tools),i}function M(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(o.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(o.response_format=e.response_format),typeof e.voice=="string"&&(o.voice=e.voice),typeof e.language=="string"&&(o.language=e.language),o}function _e(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},o=n.error,r=o?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:o?.type??"urun_error",code:t.code??o?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Be="llm-resp";async function*He(e,t){let n=`resp_${e}`,o=new Map;for await(let r of t){let i=r;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=o.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield _e(i);return}}}async function*A(e,t){let n=`${Be}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*He(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var P=class{constructor(t,n=15e3){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let o=M(t,n,this.consumerId);return this.write(o),A(this.session,n)})}sendResponseCreate(t,n,o){return this.writeGated(o,()=>{let r=V(t,n,o,this.consumerId);return this.write(r),A(this.session,o)})}async writeGated(t,n){try{await ke(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(o){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${o instanceof Error?o.message:String(o)}`)}return n()}};0&&(module.exports={AudioBridge,CLOSE_PROTOCOL,CLOSE_SESSION_GONE,CLOSE_UNKNOWN_MODEL,CLOSE_UPSTREAM,GEMINI_AUDIO_IN_RATE,GEMINI_AUDIO_OUT_MIME,GEMINI_AUDIO_OUT_RATE,GEMINI_LIVE_PATH,GeminiLiveError,NATIVE_AUDIO_SAMPLE_RATE,OUTBOUND_AUDIO_FLUSH_B64,RT_VIDEO_IN_STREAM,RT_VIDEO_OUT_STREAM,SdkTransport,VIDEO_FRAME_MESSAGE_BUDGET,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_SETUP_KEY,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeResponsesLane,decodeVideoOutRecord,enableSessionAudio,enableSessionVideo,encodeVideoOutRecord,goAwayMsg,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,parseClientMessage,resamplePcm16,responseCreateToEnvelope,responsesCreateToEnvelope,serverContentOfAudio,serverContentOfDelta,sessionResumptionUpdateMsg,translateClientContent,translateRealtimeInput,translateSetup,translateToolResponse,turnEndOfCompleted,videoOutAck,videoOutChunkMsg,weriftAudioBackend});
@@ -114,36 +114,10 @@ declare class SdkTransport {
114
114
  * persistent session, so a per-transport tag identifies the session too.
115
115
  */
116
116
  private readonly sessionTag;
117
- /** The shipped gate deadline — the only production value (test seam overrides it). */
118
- private static readonly DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS;
119
117
  constructor(session: UrunSessionLike,
120
118
  /** Test seam for the gate deadline; never an env knob or config surface. */
121
119
  docSyncTimeoutMs?: number);
122
120
  get consumerId(): string;
123
- /**
124
- * THE FIRST-WRITE-LOST GATE (resumed-attach, prod-usw2 2026-09-23): a turn's
125
- * request envelope is the llm doc's FIRST write after a cold (re-)attach, and
126
- * the dial's `whenLive` gate resolves off the SIGNALING status frame — which
127
- * routinely lands while the yjs doc provider is still dialing its room. A
128
- * local write applied while the provider has no socket is relayed ONLY through
129
- * the initial-sync diff exchange, and on a resumed session that exchange races
130
- * the session-server's S3 hydration barrier. Observed live (local proxy against
131
- * prod, dial resumed the long-parked shared-org session): the 396-byte envelope
132
- * applied at `wsconnected=false synced=false` NEVER reached the room — the
133
- * serve runtime drained the doc for the caller's whole timeout budget and
134
- * never saw the request (`drain: 2 in doc, 0 pending`, no change events), while
135
- * the client's provider reported `synced`. The write is silently stranded.
136
- *
137
- * So every request-envelope write first holds for the doc plane's OWN
138
- * readiness — `synced`, the provider's level-triggered initial-sync bar.
139
- * Post-sync writes ride the connected socket directly and are delivered.
140
- * Bounded and loud on deadline: the caller (rehome's one re-dial, then the
141
- * lane's loud 502) owns the verdict — never a silent loss. A session double
142
- * that exposes no `onSynced` surface cannot be gated and is skipped honestly
143
- * (same structural-seam contract as `onConnectionState`).
144
- */
145
- /** Hold until the llm doc plane has completed its first sync (bounded, loud). */
146
- private ensureDocSynced;
147
121
  private write;
148
122
  sendResponses(params: {
149
123
  model?: string;
@@ -68,15 +68,10 @@ declare class SdkTransport {
68
68
  private readonly docSyncTimeoutMs;
69
69
 
70
70
  private readonly sessionTag;
71
-
72
- private static readonly DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS;
73
71
  constructor(session: UrunSessionLike,
74
72
 
75
73
  docSyncTimeoutMs?: number);
76
74
  get consumerId(): string;
77
-
78
-
79
- private ensureDocSynced;
80
75
  private write;
81
76
  sendResponses(params: {
82
77
  model?: string;
@@ -1 +1 @@
1
- import{a as c,b as C,c as L,d as M,e as R,f as D,g as f,h as N,i as v,j as g,k as x,l as k,m as y,n as G,o as B,p as F,q as P,r as H,s as W,t as b,u as w,v as K,w as h,x as Q}from"./chunk-3JWYIKHM.js";import{a as i,b as s,c as O,d,e as a,f as E,g as _,h as p,i as u,j as A,k as S,l as I,m as T,n as l,o as m,p as U,q as V}from"./chunk-6M5JK4YC.js";import{a as o,b as t,e as n,f as r}from"./chunk-NN6TQQUG.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-3JWYIKHM.js";import{a as i,b as s,c as O,d,e as a,f as E,g as _,h as p,i as u,j as A,k as S,l as I,m as T,n as l,o as m,p as U,q as V}from"./chunk-6M5JK4YC.js";import{a as o,b as t,e as n,f as r}from"./chunk-ETX6IX25.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};