@urun-sh/openai 0.2.57 → 0.2.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-BJUGGTQT.js → chunk-TEZ4WLY6.js} +20 -15
- package/dist/pi-extension/index.cjs +6 -6
- package/dist/pi-extension/index.d.cts +12 -2
- package/dist/pi-extension/index.d.ts +4 -2
- package/dist/pi-extension/index.js +6 -6
- package/dist/pi-extension/standalone.cjs +52 -52
- package/dist/proxy/cli.cjs +34 -27
- package/dist/proxy/cli.js +17 -15
- package/dist/proxy/index.cjs +13 -8
- package/dist/proxy/index.js +1 -1
- package/package.json +4 -4
package/dist/proxy/cli.js
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`)};return()=>{n.stdout.write=
|
|
4
|
-
`)}catch{}};r.on("error",
|
|
2
|
+
import{a as j}from"../chunk-OLE2YJO3.js";import{b as W}from"../chunk-TEZ4WLY6.js";import{a as C,b as G,c as g}from"../chunk-VFHQZ4OM.js";import{c as L}from"../chunk-62IL5R2N.js";import{a as D,c as U,d as M,e as F}from"../chunk-VXTNG2TP.js";import{spawn as fe}from"child_process";import{appendFileSync as ue,createWriteStream as Ce,existsSync as Ge,mkdirSync as Le}from"fs";import je from"path";import l from"process";import{App as de,createClientToken as De}from"@urun-sh/core";import ge from"os";import we from"path";import{fileURLToPath as xe}from"url";import{format as ve}from"util";var B="0.2.59";var K=4141,Se=B,S={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function A(e,n="openai"){if(n==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function H(e,n,t){let s={...e,...A(n,t)};return delete s.URUN_API_KEY,delete s.URUN_JWT,s}function Y(e,n,t){let s=["-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"'],r=t.indexOf("--"),o=r===-1?t:t.slice(0,r),i=o.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),a=t[0]==="exec",u=o.includes("--skip-git-repo-check"),c=a&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...s,...i?[]:["-m",n],...c]}function J(e,n){return n.some(s=>s==="--model"||s==="--provider"||s.startsWith("--model=")||s.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function q(e,n,t){let s=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(s){if(!t(s))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${s}, 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 s}let r=xe(new URL("../pi-extension/standalone.cjs",n));if(!t(r))throw new Error(`pi extension entry not found at ${r} \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 r}function V(e){let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return n}function X(e){if(e[0]!=="--port")return null;let n=V(e[1]);return e.splice(0,2),n}function I(e){let n=e.indexOf("--port");if(n===-1)return K;let t=V(e[n+1]);return e.splice(n,2),t}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 _(e,n){let t=(e[n]??"").trim();if(!t)throw new Error(`${n} 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 t}function h(e){let n=Ee(_(e,"URUN_BASE_URL")),t=_(e,"URUN_ORG_ID"),s=_(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",o=(e.URUN_API_URL??"").trim(),i=o?w(o,"URUN_API_URL"):D,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:n,orgId:t,appId:s,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(e.URUN_API_KEY??"").trim();if(u){let c=(e.URUN_GATEWAY_URL??"").trim(),d=c?w(c):void 0;return{baseUrl:n,orgId:t,appId:s,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function Ee(e,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${n} 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 w(e,n="URUN_GATEWAY_URL"){let t=new URL(e),s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!s)throw new Error(`${n} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function O(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Se}}function be(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var Re=250;async function T(e,n=Re){try{let t=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(n)});if(!t.ok)return null;let s=(await t.json()).identity;if(s==null||typeof s!="object")return null;let{app:r,org:o,fn:i,base_url:a,proxy_version:u}=s;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:r,org:o,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Q=2e3;async function Pe(e,n=Q){try{let t=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(n)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function Z(e,n,t=K,s=Q){if(e!=null)return{mode:"spawn",port:e};let r=await T(t);if(r!==null&&be(r,n)){let o=await Pe(t,s);return o===null?{mode:"reuse",port:t,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${o}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ee(e,n=ge.homedir()){return we.join(n,".urun","logs",`compat-proxy-${e}.log`)}var k=["log","info","warn","error","debug","trace"];function ne(e,n=process,t=console){let s=n.stdout.write,r=n.stderr.write,o=(a,...u)=>e.write(a,...u);n.stdout.write=o,n.stderr.write=o;let i=Object.fromEntries(k.map(a=>[a,t[a]]));for(let a of k)t[a]=(...u)=>{e.write(`${ve(...u)}
|
|
3
|
+
`)};return()=>{n.stdout.write=s,n.stderr.write=r;for(let a of k)t[a]=i[a]}}var Ue=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function te(e){let n=e?.code;return typeof n=="string"&&Ue.has(n)}function E(e,n){try{return e.write(n),!0}catch(t){if(te(t))return!1;throw t}}function re(e){let n={stdout:!1,stderr:!1},t=[];for(let s of["stdout","stderr"]){let r=e.streams[s],o=i=>{te(i)&&(n[s]=!0);let a=i?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${s} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
4
|
+
`)}catch{}};r.on("error",o),t.push([r,o])}return{isDead:s=>n[s],uninstall:()=>{for(let[s,r]of t)s.off("error",r)}}}function oe(e){let n=t=>{let s=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${s}
|
|
5
5
|
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
6
6
|
`)}catch(r){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(r?.code??r)}) \u2014 the terminal is gone
|
|
7
|
-
`)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function
|
|
8
|
-
`);let r=e.auth,
|
|
9
|
-
`),r(127)})})}function
|
|
10
|
-
`)}async function
|
|
11
|
-
`),
|
|
12
|
-
`):
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
15
|
-
`),
|
|
16
|
-
`),l
|
|
17
|
-
`),
|
|
18
|
-
`),u.
|
|
7
|
+
`)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function se(e,n){let t="pass --port 0 for an OS-assigned ephemeral port";return n?`port ${e} is held by another urun-openai proxy serving app ${n.app} (org ${n.org}, fn ${n.fn}, version ${n.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${t}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}function _e(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function ke(e){let n=e?.type;return n==="response.completed"||n==="error"}function ie(e){return async function(t){return(async function*(){for(let r=1;r<=2;r++){let{app:o,entry:i}=await e.sessionFor(t.model),a=!1,u=!1;try{let c=await e.createStream(i,t);for await(let d of c){if(ke(d)&&(a=!0),_e(d)){if(r>1)continue}else u=!0;yield d}}catch(c){if(r<2&&!u){await e.evict(o,i);continue}throw c}if(a)return;if(r<2&&!u){await e.evict(o,i);continue}return}})()}}var Ae=3,Ie="llm",Oe=new Set(["ended","expired","error"]);function ae(e,n){let t=e.doc(Ie),s=typeof t.onConnectionState=="function",r=typeof e.onPhase=="function";if(!s&&!r)throw new Error(`session for app "${n}" 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 o=null,i=new Set,a=[],u=c=>{if(!o){o=c;for(let d of[...i])d(c);i.clear()}};return s&&a.push(t.onConnectionState(c=>{c.consecutiveFailures<Ae||u(new U(`the pooled session for app "${n}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),r&&a.push(e.onPhase(c=>{Oe.has(c.name)&&u(new U(`the pooled session for app "${n}" is gone: it reached terminal phase "${c.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>o,onGone(c){return o?(c(o),()=>{}):(i.add(c),()=>i.delete(c))},dispose(){i.clear();for(let c of a.splice(0))c()}}}async function*N(e,n){let t=n.gone();if(t)throw t;let s=e[Symbol.asyncIterator](),r,o=new Promise((i,a)=>{r=n.onGone(u=>a(u))});o.catch(()=>{});try{for(;;){let i=await Promise.race([s.next(),o]);if(i.done)return;yield i.value}}finally{r?.(),s.return?.(void 0)}}import{ensureNodeWebRTC as Te,nodeWebRTCUnavailableReason as Ne}from"@urun-sh/core/internal";var $e={ensureWebRTC:Te,webrtcUnavailableReason:Ne,audioBackend:g};async function ce(e=$e){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let n=e.webrtcUnavailableReason();if(n)return{ok:!1,reason:`${n} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function le(e,n,t){let s=e[t];if(typeof s!="function")throw new Error(`app "${n}" has no function "${t}" (set URUN_FUNCTION)`);let r=s();if(typeof r.end!="function")throw new Error(`app "${n}" function "${t}" returned a session without end()`);return r}function Me(e,n){let{baseUrl:t,orgId:s,fnName:r,auth:o}=e,i=d=>({session:d,responses:new L(d),gone:ae(d,n)});if(o.lane==="jwt"){let d=de(n,{baseUrl:t,orgId:s,jwt:o.jwt});return i(le(d,n,r))}let{apiKey:a,gatewayUrl:u}=o,c=de(n,{baseUrl:t,orgId:s,getAccessToken:async()=>(await De(a,{baseUrl:u,expiresIn:300,allowedFunctions:[`${n}/${r}`]})).token});return i(le(c,n,r))}function Fe(e){let n=e.session.id;if(typeof n!="string"||n.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 n}var We=new Set(["error","ended","expired"]);function Be(e){let n=(l.env.URUN_CATALOG_URL??"").trim(),t=n?w(n,"URUN_CATALOG_URL"):"",s=(l.env.URUN_CATALOG_ANON_KEY??"").trim();(!t||!s)&&l.stderr.write(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
|
|
8
|
+
`);let r=e.auth,o=null,i=u=>{let c=Me(e,u);return c.gone.onGone(()=>{o?.evict(u,c)}),c},a=new F({defaultApp:e.appId,fnName:e.fnName,openSession:i,closeSession:async u=>{u.gone.dispose(),await u.session.end()},listApps:r.lane==="api-key"?()=>M({apiUrl:e.apiUrl,apiKey:r.apiKey}):null,listCatalog:t&&s?()=>j({catalogUrl:t,anonKey:s}):null,sessionKey:Fe});return o=a,a.seed(e.appId,i(e.appId)),a}function Ke(e,n=g){let t=new WeakMap,s=new WeakMap;return{createResponse:ie({sessionFor:r=>e.sessionFor(r),evict:(r,o)=>e.evict(r,o),createStream:async(r,o)=>N(await r.responses.responses.create(o),r.gone)}),listModels:()=>e.modelList(),openAudio:async r=>{let{entry:o}=await e.sessionFor(r),i=t.get(o);return i||(i=(async()=>C(o.session,await n()))(),t.set(o,i),i.catch(()=>t.delete(o))),i},openVideo:async r=>{let{entry:o}=await e.sessionFor(r),i=s.get(o);return i||(i=G(o.session),s.set(o,i)),i},sessionHandle:async r=>(await e.handleFor(r)).handle,createResponseOn:async(r,o)=>{let{entry:i}=await e.sessionForHandle(r);return N(await i.responses.responses.create(o),i.gone)},onSessionEnd:async(r,o)=>{let{entry:i}=await e.sessionForHandle(r),a=i.session;if(typeof a.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let u=!1;return a.onPhase(c=>{if(u||!We.has(c.name))return;u=!0;let d=a.endsAt??null;o({timeLeftMs:d?Math.max(0,d.getTime()-Date.now()):null,reason:c.name==="expired"?"session reached its maximum length":`session ${c.name}`})})}}}async function He(e,n,t){let s=fe(e,n,{stdio:"inherit",env:t});return new Promise(r=>{s.once("exit",o=>r(o??1)),s.once("error",o=>{l.stderr.write(`failed to launch ${e}: ${String(o)}
|
|
9
|
+
`),r(127)})})}function Ye(){return q(l.env,import.meta.url,Ge)}function me(e){for(let[n,t]of Object.entries(A(e)))l.stdout.write(`export ${n}=${t}
|
|
10
|
+
`)}async function pe(e,n){let t=h(l.env),s=n?O(t):void 0,r=Be(t),o=W({clients:Ke(r),identity:s});try{await new Promise((a,u)=>{o.once("error",u),o.listen(e,"127.0.0.1",a)})}catch(a){throw await r.closeAll().catch(()=>{}),a.code==="EADDRINUSE"?new Error(se(e,await T(e))):a}let i=o.address().port;return n&&(l.stdout.write(`urun openai proxy listening on http://127.0.0.1:${i}/v1
|
|
11
|
+
`),me(i)),{port:i,close:async()=>{let a=new Promise(u=>o.close(()=>u()));o.closeAllConnections(),await a,await r.closeAll()}}}async function Je(){let e=l.argv.slice(2),n=X(e),t=e.shift()??"proxy";if(t==="env")return me(z(n??I(e))),0;if(t==="selftest"){let{ok:r,reason:o}=await ce();return r?(l.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
12
|
+
`),0):(l.stderr.write(`urun-openai selftest: FAIL \u2014 ${o}
|
|
13
|
+
`),1)}if(t==="proxy"){let r=n??I(e),o=await pe(r,!0);return await new Promise(i=>{l.once("SIGINT",i),l.once("SIGTERM",i)}),await o.close(),0}let s=t==="run"?e.shift():t;{if(!s)throw new Error(`launch needs an agent (${Object.keys(S).join("|")}) or \`-- <cmd>\``);if(s==="pi"){let p=h(l.env);return He("pi",["-e",Ye(),...J(p.appId,e)],l.env)}let r,o,i="openai";if(s==="--"){if(r=e.shift()??"",o=e,!r)throw new Error("`-- <cmd>` needs a command to launch")}else{let p=S[s];if(!p)throw new Error(`unknown command/agent ${s}; commands: proxy | env; agents: ${Object.keys(S).join(" | ")} \u2014 or \`-- <cmd>\``);r=p.bin,o=[...p.args??[],...e],i=p.env}let a=await Z(n,O(h(l.env))),u=null,c=a.port;a.mode==="reuse"?l.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${c} (app ${a.identity.app}, fn ${a.identity.fn}, v${a.identity.proxy_version})
|
|
14
|
+
`):a.reason&&l.stderr.write(`urun compat: ${a.reason}
|
|
15
|
+
`);let d=null,b=null,y=null,f=null;a.mode!=="reuse"&&(u=await pe(a.port,!1),c=u.port,f=ee(c),Le(je.dirname(f),{recursive:!0}),y=Ce(f,{flags:"a"}),b=re({streams:l,note:p=>ue(f,p)}).uninstall,y.on("error",p=>{d?.(),d=null,E(l.stderr,`urun compat: proxy log ${f} failed: ${String(p)} \u2014 proxy output continues on the terminal
|
|
16
|
+
`)}),l.stdout.write(`urun openai proxy on http://127.0.0.1:${c}/v1 \u2014 proxy logs: ${f}
|
|
17
|
+
`),d=ne(y)),s==="codex"&&(o=Y(c,h(l.env).appId,o));let R=fe(r,o,{stdio:"inherit",env:H(l.env,c,i)}),he=f!==null?oe({logPath:f,appendSync:ue,restore:()=>{d?.(),d=null},writeStderr:p=>l.stderr.write(p),killChild:()=>R.kill("SIGTERM"),exit:p=>l.exit(p),proc:l}):null,$=await new Promise(p=>{R.once("exit",P=>p(P??1)),R.once("error",P=>{d?.(),d=null,E(l.stderr,`failed to launch ${r}: ${String(P)}
|
|
18
|
+
`),p(127)})});he?.();let m=null;try{u&&await u.close()}catch(p){m=p}finally{d?.(),d=null,b?.(),b=null,y?.end()}return m!==null&&E(l.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${$} preserved): ${String(m instanceof Error?m.message:m)}
|
|
19
|
+
`),$}}Je().then(e=>l.exit(e),e=>{l.stderr.write(`${String(e instanceof Error?e.message:e)}
|
|
20
|
+
`),l.exit(1)});export{Ke as buildClients,Be as buildRouter};
|
package/dist/proxy/index.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
"use strict";var ye=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(n,t)=>{for(var e in t)ye(n,e,{get:t[e],enumerable:!0})},ot=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of et(t))!tt.call(n,s)&&s!==e&&ye(n,s,{get:()=>t[s],enumerable:!(o=Ze(t,s))||o.enumerable});return n};var st=n=>ot(ye({},"__esModule",{value:!0}),n);var Mt={};nt(Mt,{GEMINI_LIVE_PATH:()=>de,createOpenAIProxy:()=>Qe});module.exports=st(Mt);var Ye=require("http");var Je=require("crypto"),Ve=require("ws");var F=class extends Error{},ne=class extends Error{};var de="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",it=1007,Te=1008,J=1011,we=1008,i=class extends Error{constructor(e,o=it){super(e);this.closeCode=o}closeCode},x=n=>typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null,le=["setup","clientContent","realtimeInput","toolResponse"];function Ce(n){let t;try{t=JSON.parse(n)}catch{throw new i("client message is not valid JSON")}let e=x(t);if(!e)throw new i("client message must be a JSON object");let o=le.filter(u=>e[u]!==void 0),s=Object.keys(e).filter(u=>!le.includes(u));if(s.length>0)throw new i(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${le.join(", ")}`);if(o.length!==1)throw new i(`client message must contain exactly one of ${le.join(", ")} (got ${o.length})`);let r=o[0],a=x(e[r]);if(!a)throw new i(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function Pe(n,t){if(typeof n=="string")return n;let e=x(n),o=e?e.parts:void 0;if(!Array.isArray(o))throw new i(`${t}: expected a Content with a parts array`);let s=[];for(let r of o){let a=x(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new i(`${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 i(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new i(`${t}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
|
|
2
|
-
`)}var at={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},ut={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},lt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Ee=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ct(n){let t=x(n);if(!t)throw new i("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new i(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let e=x(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!e)throw new i("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(e??{}))if(s!=="disabled")throw new i(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(e?.disabled!==!0)throw new i("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(!Ee.includes(t.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${Ee.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var dt=["temperature","maxOutputTokens","responseModalities"];function $e(n){for(let[d,h]of Object.entries(ut))if(n[d]!==void 0)throw new i(h);for(let d of Object.keys(n))if(!lt.includes(d))throw new i(`unsupported setup field "${d}"`);if(typeof n.model!="string"||n.model.length===0)throw new i('setup.model is required (format "models/{model}")');let t=n.model.replace(/^models\//,""),e,o,s=!1,r=x(n.generationConfig);if(n.generationConfig!==void 0&&!r)throw new i("setup.generationConfig must be an object");if(r){for(let d of Object.keys(r))if(!dt.includes(d))throw new i(`unsupported generationConfig field "${d}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new i("generationConfig.temperature must be a number");e=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new i("generationConfig.maxOutputTokens must be a number");o=r.maxOutputTokens}if(r.responseModalities!==void 0){let d=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let h of d){let p=String(h).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new i(`responseModalities ${JSON.stringify(h)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let a=[];n.systemInstruction!==void 0&&a.push({role:"system",content:Pe(n.systemInstruction,"setup.systemInstruction")});let u;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new i("setup.tools must be an array");u=[];for(let d of n.tools){let h=x(d);if(!h)throw new i("setup.tools entries must be objects");for(let p of Object.keys(h))if(p!=="functionDeclarations")throw new i(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(h.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let p of h.functionDeclarations){let g=x(p);if(!g||typeof g.name!="string")throw new i("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let m={enabled:!1,handle:null};if(n.sessionResumption!==void 0){let d=x(n.sessionResumption);if(!d)throw new i("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let h of Object.keys(d))if(h!=="handle")throw new i(`unsupported sessionResumption field "${h}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(d.handle!==void 0&&(typeof d.handle!="string"||d.handle.length===0))throw new i("sessionResumption.handle must be a non-empty string when present");m={enabled:!0,handle:typeof d.handle=="string"?d.handle:null}}let c=n.realtimeInputConfig===void 0?at:ct(n.realtimeInputConfig);return{model:t,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:c,sessionResumption:m}}function Ne(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function Le(n){let t=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function Me(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new i(`unsupported clientContent field "${o}"`);let t=n.turns===void 0?[]:n.turns;if(!Array.isArray(t))throw new i("clientContent.turns must be an array");let e=[];for(let o of t){let s=x(o);if(!s)throw new i("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new i(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);e.push({role:r==="model"?"assistant":"user",content:Pe(s,"clientContent.turns")})}return{items:e,turnComplete:n.turnComplete===!0}}var ce=16e3,Ue=24e3,pt=`audio/pcm;rate=${Ue}`,De=Buffer.alloc(960).toString("base64");function ft(n,t,e){if(t===e)return n;let o=Math.floor(n.length*e/t),s=new Int16Array(o),r=t/e,a=n.length-1;for(let u=0;u<o;u++){let m=u*r,c=Math.floor(m);if(c>=a){s[u]=n[a];continue}let d=m-c;s[u]=Math.round(n[c]+(n[c+1]-n[c])*d)}return s}function mt(n){let t=x(n);if(!t)throw new i("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new i(`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 i("realtimeInput.video.data must be non-empty base64");let e=Buffer.from(t.data,"base64");if(e.length<3||e[0]!==255||e[1]!==216)throw new i("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(e)}function ht(n){let t=x(n);if(!t)throw new i("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new i(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let e=/;\s*rate=(\d+)/.exec(t.mimeType);if(e&&Number(e[1])!==ce)throw new i(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ce} Hz (audio/pcm;rate=${ce})`);if(typeof t.data!="string"||t.data.length===0)throw new i("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 i(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let a=0;a<s.length;a++)s[a]=o.readInt16LE(a*2);let r=ft(s,ce,Ue);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Be(n){if(n.mediaChunks!==void 0)throw new i('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(n.activityStart!==void 0||n.activityEnd!==void 0){if(Object.keys(n).length!==1||n.activityStart!==void 0&&n.activityEnd!==void 0)throw new i("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=n.activityStart!==void 0?"activityStart":"activityEnd",r=x(n[s]);if(!r||Object.keys(r).length!==0)throw new i(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(n))if(!t.includes(o))throw new i(`unsupported realtimeInput field "${o}"`);let e=t.filter(o=>n[o]!==void 0);if(e.length!==1)throw new i(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${e.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:ht(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:mt(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new i("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new i("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function He(n){for(let t of Object.keys(n))if(t!=="functionResponses")throw new i(`unsupported toolResponse field "${t}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new i("toolResponse.functionResponses must be a non-empty array");return n.functionResponses.map(t=>{let e=x(t);if(!e||typeof e.id!="string"||e.id.length===0)throw new i("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:e.id,output:JSON.stringify(e.response??null)}})}function je(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function qe(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:pt,data:n}}]}}}}function Fe(n){let t=x(n)??{},e=Array.isArray(t.output)?t.output:[],o=[],s=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let c of e){let d=x(c);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let h of d.content){let p=x(h);p?.type==="output_text"&&typeof p.text=="string"&&(r+=p.text)}}r&&s.push({role:"assistant",content:r});for(let c of e){let d=x(c);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new i(`upstream function_call item is missing call_id/name: ${JSON.stringify(c)}`,J);let h=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(h)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${h}`,J)}o.push({id:d.call_id,name:d.name,args:p}),s.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:h})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let u=x(t.usage),m={serverContent:{turnComplete:!0}};if(u){let c={};typeof u.input_tokens=="number"&&(c.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(c.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(c.totalTokenCount=u.total_tokens),Object.keys(c).length>0&&(m.usageMetadata=c)}return a.push(m),{messages:a,assistantItems:s}}var gt=256,_e=class{snapshots=new Map;store(t,e){for(this.snapshots.set(t,e);this.snapshots.size>gt;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},se=n=>n.slice(0,120),ke=class{constructor(t,e,o){this.ws=t;this.clients=e;this.registry=o;t.on("message",s=>this.onMessage(s)),t.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;video=null;activityOpen=!1;activeTurn=null;send(t){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(t))}fail(t){if(t instanceof F){this.ws.close(Te,se(t.message));return}if(t instanceof ne){this.ws.close(we,se(t.message));return}if(t instanceof i){this.ws.close(t.closeCode,se(t.message));return}this.ws.close(J,se(String(t instanceof Error?t.message:t)))}onMessage(t){try{let e=Ce(typeof t=="string"?t:Buffer.concat(Array.isArray(t)?t:[t]).toString("utf8"));if(e.kind==="setup"){this.handleSetup(e.setup).catch(s=>this.fail(s));return}if(!this.config)throw new i(`"${e.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(e.kind==="clientContent"){let{items:s,turnComplete:r}=Me(e.clientContent);this.transcript.push(...s),r&&this.enqueue(()=>this.runTurn());return}if(e.kind==="realtimeInput"){let s=Be(e.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:De);return}this.transcript.push(...He(e.toolResponse)),this.enqueue(()=>this.runTurn())}catch(e){this.fail(e)}}async handleSetup(t){if(this.config)throw new i("setup may only be sent once, as the first client message");let e=$e(t),o=e.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new i("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",we);if(s.model!==e.model)throw new i(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${e.model}", per the Live API session-resumption contract)`);if(e.systemItems.length>0)throw new i("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r)))}else this.proxyHandle=await this.clients.sessionHandle(e.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...e.systemItems);this.config=e,this.send({setupComplete:{}}),e.audioModality&&this.ensureAudioLane(),e.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let t=this.config;if(!t)throw new i("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openAudio;if(!e)throw new i("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",J);return this.audio=(async()=>{let o=await e.call(this.clients,t.model);return this.detachAudio=o.onOutputAudio(s=>this.send(qe(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(t){this.ensureAudioLane().then(e=>e.appendInputAudio(t)).catch(e=>this.fail(e))}ensureVideoLane(){if(this.video)return this.video;let t=this.config;if(!t)throw new i("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openVideo;if(!e)throw new i("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",J);return this.video=Promise.resolve(e.call(this.clients,t.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(t){this.ensureVideoLane().then(e=>e.sendInputFrame(t)).catch(e=>this.fail(e))}onActivity(t,e){if(!e.activity.manualActivity)throw new i(`realtimeInput.${t} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(t==="activityStart"){if(this.activityOpen)throw new i("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,e.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new i("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(t){this.queue=this.queue.then(t,()=>{}),this.queue=this.queue.catch(e=>this.fail(e))}async mintResumptionUpdate(){let t=this.config;if(!t?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let e=await this.clients.sessionHandle(t.model);this.proxyHandle=e;let o=(0,Je.randomUUID)();this.registry.store(o,{model:t.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Ne(o))}async handleUpstreamEnd(t){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let e=null;try{e=await this.clients.sessionHandle(this.config.model)}catch{}if(e!==null&&e!==this.proxyHandle){this.proxyHandle=e,this.unsubscribeEnd=await this.clients.onSessionEnd(e,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Le(t.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${t.reason}`))}async runTurn(){let t=this.config;if(!t||this.ws.readyState!==this.ws.OPEN)return;let e={interrupted:!1};this.activeTurn=e;try{let o=await this.clients.createResponse({model:t.model,input:[...this.transcript],stream:!0,tools:t.tools,temperature:t.temperature,max_output_tokens:t.maxOutputTokens}),s,r=!1;for await(let m of o){if(e.interrupted)break;let c=m;if(c.type==="error")throw new i(`upstream error: ${JSON.stringify(c)}`,J);if(c.type==="response.completed"){s=c.response,r=!0;continue}let d=je(c);d&&this.send(d)}if(e.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!r)throw new i("upstream produced no response.completed event",J);let{messages:a,assistantItems:u}=Fe(s);this.transcript.push(...u);for(let m of a)this.send(m);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},yt=(n,t)=>{let e=n.headers["x-goog-api-key"];if(typeof e=="string")return e;let o=n.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):t.searchParams.get("key")??void 0};function Ge(n,t){let e=new Ve.WebSocketServer({noServer:!0}),o=new _e;n.on("upgrade",(s,r,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==de){r.write(`HTTP/1.1 404 Not Found\r
|
|
2
|
+
`)}var at={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},ut={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},lt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Ee=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ct(n){let t=x(n);if(!t)throw new i("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new i(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let e=x(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!e)throw new i("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(e??{}))if(s!=="disabled")throw new i(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(e?.disabled!==!0)throw new i("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(!Ee.includes(t.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${Ee.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var dt=["temperature","maxOutputTokens","responseModalities"];function $e(n){for(let[c,h]of Object.entries(ut))if(n[c]!==void 0)throw new i(h);for(let c of Object.keys(n))if(!lt.includes(c))throw new i(`unsupported setup field "${c}"`);if(typeof n.model!="string"||n.model.length===0)throw new i('setup.model is required (format "models/{model}")');let t=n.model.replace(/^models\//,""),e,o,s=!1,r=x(n.generationConfig);if(n.generationConfig!==void 0&&!r)throw new i("setup.generationConfig must be an object");if(r){for(let c of Object.keys(r))if(!dt.includes(c))throw new i(`unsupported generationConfig field "${c}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new i("generationConfig.temperature must be a number");e=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new i("generationConfig.maxOutputTokens must be a number");o=r.maxOutputTokens}if(r.responseModalities!==void 0){let c=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let h of c){let p=String(h).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new i(`responseModalities ${JSON.stringify(h)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let a=[];n.systemInstruction!==void 0&&a.push({role:"system",content:Pe(n.systemInstruction,"setup.systemInstruction")});let u;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new i("setup.tools must be an array");u=[];for(let c of n.tools){let h=x(c);if(!h)throw new i("setup.tools entries must be objects");for(let p of Object.keys(h))if(p!=="functionDeclarations")throw new i(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(h.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let p of h.functionDeclarations){let g=x(p);if(!g||typeof g.name!="string")throw new i("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let f={enabled:!1,handle:null};if(n.sessionResumption!==void 0){let c=x(n.sessionResumption);if(!c)throw new i("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let h of Object.keys(c))if(h!=="handle")throw new i(`unsupported sessionResumption field "${h}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new i("sessionResumption.handle must be a non-empty string when present");f={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=n.realtimeInputConfig===void 0?at:ct(n.realtimeInputConfig);return{model:t,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:d,sessionResumption:f}}function Ne(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function Le(n){let t=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function Me(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new i(`unsupported clientContent field "${o}"`);let t=n.turns===void 0?[]:n.turns;if(!Array.isArray(t))throw new i("clientContent.turns must be an array");let e=[];for(let o of t){let s=x(o);if(!s)throw new i("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new i(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);e.push({role:r==="model"?"assistant":"user",content:Pe(s,"clientContent.turns")})}return{items:e,turnComplete:n.turnComplete===!0}}var ce=16e3,Ue=24e3,pt=`audio/pcm;rate=${Ue}`,De=Buffer.alloc(960).toString("base64");function ft(n,t,e){if(t===e)return n;let o=Math.floor(n.length*e/t),s=new Int16Array(o),r=t/e,a=n.length-1;for(let u=0;u<o;u++){let f=u*r,d=Math.floor(f);if(d>=a){s[u]=n[a];continue}let c=f-d;s[u]=Math.round(n[d]+(n[d+1]-n[d])*c)}return s}function mt(n){let t=x(n);if(!t)throw new i("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new i(`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 i("realtimeInput.video.data must be non-empty base64");let e=Buffer.from(t.data,"base64");if(e.length<3||e[0]!==255||e[1]!==216)throw new i("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(e)}function ht(n){let t=x(n);if(!t)throw new i("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new i(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let e=/;\s*rate=(\d+)/.exec(t.mimeType);if(e&&Number(e[1])!==ce)throw new i(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ce} Hz (audio/pcm;rate=${ce})`);if(typeof t.data!="string"||t.data.length===0)throw new i("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 i(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let a=0;a<s.length;a++)s[a]=o.readInt16LE(a*2);let r=ft(s,ce,Ue);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Be(n){if(n.mediaChunks!==void 0)throw new i('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(n.activityStart!==void 0||n.activityEnd!==void 0){if(Object.keys(n).length!==1||n.activityStart!==void 0&&n.activityEnd!==void 0)throw new i("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=n.activityStart!==void 0?"activityStart":"activityEnd",r=x(n[s]);if(!r||Object.keys(r).length!==0)throw new i(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(n))if(!t.includes(o))throw new i(`unsupported realtimeInput field "${o}"`);let e=t.filter(o=>n[o]!==void 0);if(e.length!==1)throw new i(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${e.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:ht(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:mt(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new i("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new i("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function He(n){for(let t of Object.keys(n))if(t!=="functionResponses")throw new i(`unsupported toolResponse field "${t}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new i("toolResponse.functionResponses must be a non-empty array");return n.functionResponses.map(t=>{let e=x(t);if(!e||typeof e.id!="string"||e.id.length===0)throw new i("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:e.id,output:JSON.stringify(e.response??null)}})}function je(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function qe(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:pt,data:n}}]}}}}function Fe(n){let t=x(n)??{},e=Array.isArray(t.output)?t.output:[],o=[],s=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let d of e){let c=x(d);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let h of c.content){let p=x(h);p?.type==="output_text"&&typeof p.text=="string"&&(r+=p.text)}}r&&s.push({role:"assistant",content:r});for(let d of e){let c=x(d);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new i(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,J);let h=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(h)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${h}`,J)}o.push({id:c.call_id,name:c.name,args:p}),s.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:h})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let u=x(t.usage),f={serverContent:{turnComplete:!0}};if(u){let d={};typeof u.input_tokens=="number"&&(d.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(d.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(d.totalTokenCount=u.total_tokens),Object.keys(d).length>0&&(f.usageMetadata=d)}return a.push(f),{messages:a,assistantItems:s}}var gt=256,_e=class{snapshots=new Map;store(t,e){for(this.snapshots.set(t,e);this.snapshots.size>gt;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},se=n=>n.slice(0,120),ke=class{constructor(t,e,o){this.ws=t;this.clients=e;this.registry=o;t.on("message",s=>this.onMessage(s)),t.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;video=null;activityOpen=!1;activeTurn=null;send(t){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(t))}fail(t){if(t instanceof F){this.ws.close(Te,se(t.message));return}if(t instanceof ne){this.ws.close(we,se(t.message));return}if(t instanceof i){this.ws.close(t.closeCode,se(t.message));return}this.ws.close(J,se(String(t instanceof Error?t.message:t)))}onMessage(t){try{let e=Ce(typeof t=="string"?t:Buffer.concat(Array.isArray(t)?t:[t]).toString("utf8"));if(e.kind==="setup"){this.handleSetup(e.setup).catch(s=>this.fail(s));return}if(!this.config)throw new i(`"${e.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(e.kind==="clientContent"){let{items:s,turnComplete:r}=Me(e.clientContent);this.transcript.push(...s),r&&this.enqueue(()=>this.runTurn());return}if(e.kind==="realtimeInput"){let s=Be(e.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:De);return}this.transcript.push(...He(e.toolResponse)),this.enqueue(()=>this.runTurn())}catch(e){this.fail(e)}}async handleSetup(t){if(this.config)throw new i("setup may only be sent once, as the first client message");let e=$e(t),o=e.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new i("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",we);if(s.model!==e.model)throw new i(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${e.model}", per the Live API session-resumption contract)`);if(e.systemItems.length>0)throw new i("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r)))}else this.proxyHandle=await this.clients.sessionHandle(e.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...e.systemItems);this.config=e,this.send({setupComplete:{}}),e.audioModality&&this.ensureAudioLane(),e.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let t=this.config;if(!t)throw new i("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openAudio;if(!e)throw new i("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",J);return this.audio=(async()=>{let o=await e.call(this.clients,t.model);return this.detachAudio=o.onOutputAudio(s=>this.send(qe(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(t){this.ensureAudioLane().then(e=>e.appendInputAudio(t)).catch(e=>this.fail(e))}ensureVideoLane(){if(this.video)return this.video;let t=this.config;if(!t)throw new i("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openVideo;if(!e)throw new i("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",J);return this.video=Promise.resolve(e.call(this.clients,t.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(t){this.ensureVideoLane().then(e=>e.sendInputFrame(t)).catch(e=>this.fail(e))}onActivity(t,e){if(!e.activity.manualActivity)throw new i(`realtimeInput.${t} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(t==="activityStart"){if(this.activityOpen)throw new i("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,e.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new i("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(t){this.queue=this.queue.then(t,()=>{}),this.queue=this.queue.catch(e=>this.fail(e))}async mintResumptionUpdate(){let t=this.config;if(!t?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let e=await this.clients.sessionHandle(t.model);this.proxyHandle=e;let o=(0,Je.randomUUID)();this.registry.store(o,{model:t.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Ne(o))}async handleUpstreamEnd(t){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let e=null;try{e=await this.clients.sessionHandle(this.config.model)}catch{}if(e!==null&&e!==this.proxyHandle){this.proxyHandle=e,this.unsubscribeEnd=await this.clients.onSessionEnd(e,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Le(t.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${t.reason}`))}async runTurn(){let t=this.config;if(!t||this.ws.readyState!==this.ws.OPEN)return;let e={interrupted:!1};this.activeTurn=e;try{let o=await this.clients.createResponse({model:t.model,input:[...this.transcript],stream:!0,tools:t.tools,temperature:t.temperature,max_output_tokens:t.maxOutputTokens}),s,r=!1;for await(let f of o){if(e.interrupted)break;let d=f;if(d.type==="error")throw new i(`upstream error: ${JSON.stringify(d)}`,J);if(d.type==="response.completed"){s=d.response,r=!0;continue}let c=je(d);c&&this.send(c)}if(e.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!r)throw new i("upstream produced no response.completed event",J);let{messages:a,assistantItems:u}=Fe(s);this.transcript.push(...u);for(let f of a)this.send(f);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},yt=(n,t)=>{let e=n.headers["x-goog-api-key"];if(typeof e=="string")return e;let o=n.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):t.searchParams.get("key")??void 0};function Ge(n,t){let e=new Ve.WebSocketServer({noServer:!0}),o=new _e;n.on("upgrade",(s,r,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==de){r.write(`HTTP/1.1 404 Not Found\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
5
|
no WS route for ${u.pathname}`),r.destroy();return}if(t.apiKey&&yt(s,u)!==t.apiKey){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
6
6
|
Connection: close\r
|
|
7
7
|
\r
|
|
8
|
-
invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,
|
|
8
|
+
invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,f=>{new ke(f,t.clients,o)})})}var Ae=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(t,e,o){this.requests[t]=(this.requests[t]??0)+1,this.localInBytes+=e,this.naiveInBytes+=o}modelEntry(t){let e=this.models[t];if(e)return e;let o=Object.keys(this.models).length>=wt?"(other)":t;return this.models[o]??={requests:0,tokens_out:0}}model(t){this.modelEntry(t).requests+=1}track(t,e){let o=this,s=performance.now(),r=null,a=0;return(async function*(){for await(let f of t)f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(r===null&&(r=performance.now(),o.ttftMs.push(r-s),o.ttftMs.length>512&&o.ttftMs.shift()),a+=1,o.tokensOut+=1,o.charsOut+=f.delta.length,e!==void 0&&(o.modelEntry(e).tokens_out+=1)),yield f;let u=(performance.now()-(r??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(t){if(!t.length)return null;let e=[...t].sort((o,s)=>o-s);return e[Math.floor(e.length/2)]}snapshot(){let t=Object.values(this.requests).reduce((e,o)=>e+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:t},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}};function Se(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function H(n,t,e){n.writeHead(t,{"content-type":"application/json"}),n.end(JSON.stringify(e))}function V(n,t,e,o="invalid_request_error"){H(n,t,{error:{message:e,type:o}})}function B(n,t,e,o){H(n,t,{type:"error",error:{type:e,message:o}})}function Re(n,t,e){if(t==="anthropic"){H(n,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}H(n,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var wt=256,_t=128;function Ie(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,_t)}var ze=64*1024*1024,pe=class extends Error{};async function kt(n){let t=[],e=0;for await(let s of n){if(e+=s.length,e>ze)throw new pe(`request body exceeds ${ze} bytes`);t.push(s)}let o=Buffer.concat(t).toString("utf8");return o?JSON.parse(o):{}}function Y(n,t,e,o){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:e,finish_reason:o}]}}var vt=256;function xt(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var be=class{conversations=new Map;thread(t,e){let o=xt(e);if(t==null)return o;let s=this.conversations.get(String(t));if(!s)throw new Error(`unknown previous_response_id ${String(t)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(t,e,o){this.conversations.set(t,[...e,{role:"assistant",content:o}]);for(let s of this.conversations.keys()){if(this.conversations.size<=vt)break;this.conversations.delete(s)}}};function re(n){let t=n?.output;return Array.isArray(t)?t.filter(e=>e.type==="function_call"):[]}function z(n){return n.find(t=>t.type==="response.completed")?.response??null}function fe(n){let t=n?.usage;if(!t||typeof t!="object")return null;let e=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=e(t.input_tokens),s=e(t.output_tokens);if(o===0&&s===0)return null;let r=e(t.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:r}}function Ke(n){let t=fe(n);return t?{prompt_tokens:t.input_tokens,completion_tokens:t.output_tokens,total_tokens:t.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Xe(n){let t=n?.output;if(!Array.isArray(t))return"";let e="";for(let o of t)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let s of o.content)s.type==="reasoning_text"&&(e+=String(s.text??""));return e}function ie(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var K=class{calls=new Map;add(t){let e=this.calls.get(t.tool_index),o=!e;return e||(e={args:""},this.calls.set(t.tool_index,e)),t.call_id&&(e.id=t.call_id),t.name&&(e.name=t.name),e.args+=t.delta,{call:e,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([t,e])=>({type:"function_call",call_id:e.id??`call_${t}`,name:e.name??"",arguments:e.args}))}},At=["<tool_call>","<function="];function bt(n){return At.find(t=>n.includes(t))}function X(n,t){return`serving row emitted a prose tool call (literal ${JSON.stringify(t)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${n}" (see catalog parser_defaults)`}function Q(n,t,e){if(!(!n||t>0))return bt(e)}function St(n){if(Array.isArray(n))return n.map(t=>{let e=t.function;return!e||typeof e!="object"?t:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var me=class extends Error{};function Rt(n,t){return Array.isArray(t)?t.map(e=>{let o=e;if(o.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let s=o.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new me(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):t}function It(n){let t=[];for(let e of n){if(e.role==="tool"){t.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&t.push({role:"assistant",content:e.content});for(let o of e.tool_calls){let s=o.function??{};t.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}t.push({...e,content:Rt(e.role,e.content)})}return t}function ve(n){return re(n).map((t,e)=>({index:e,id:t.call_id??t.id??`call_${e}`,type:"function",function:{name:t.name??"",arguments:t.arguments??"{}"}}))}function We(n,t){let e=t?.output_text;return typeof e=="string"?e:n.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function Ot(n,t,e,o,s){let r=n.stream===!0,a;try{a=e.thread(n.previous_response_id,n.input)}catch(m){V(o,400,String(m instanceof Error?m.message:m));return}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(n.input)));let u=`resp_${Math.random().toString(36).slice(2,14)}`,f=n.store!==!1,d=Ie(n);s.model(d);let c=Array.isArray(n.tools)&&n.tools.length>0,h;try{h=await t.createResponse({model:n.model,input:a,stream:r,tools:n.tools,tool_choice:n.tool_choice,temperature:n.temperature,max_output_tokens:n.max_output_tokens})}catch(m){if(m instanceof F){Re(o,"openai",m);return}throw m}let p=[];if(r){Se(o);let m=y=>{o.write(`event: ${String(y.type??"message")}
|
|
9
9
|
data: ${JSON.stringify(y)}
|
|
10
10
|
|
|
11
|
-
`)},$=y=>y.response&&typeof y.response=="object"?{...y,response:{...y.response,id:u}}:y,S=`item_${u.slice(5)}`,N=`rs_${u.slice(5)}`,T=!1,L=!1,l=0,k=()=>{T||(T=!0,
|
|
11
|
+
`)},$=y=>y.response&&typeof y.response=="object"?{...y,response:{...y.response,id:u}}:y,S=`item_${u.slice(5)}`,N=`rs_${u.slice(5)}`,T=!1,L=!1,l=0,k=()=>{T||(T=!0,m({type:"response.created",response:{id:u,object:"response",status:"in_progress"}}))},U=!1,E=0,M="",D=()=>{U&&(U=!1,m({type:"response.reasoning_text.done",item_id:N,output_index:E,content_index:0,text:M}),m({type:"response.output_item.done",output_index:E,item:{id:N,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:M}],status:"completed"}}))},C=!1,_=0,b="",j=y=>{C&&(C=!1,m({type:"response.output_text.done",item_id:S,output_index:_,content_index:0,text:b}),m({type:"response.content_part.done",item_id:S,output_index:_,content_index:0,part:{type:"output_text",text:b}}),m({type:"response.output_item.done",output_index:_,item:{id:S,type:"message",role:"assistant",status:y,content:[{type:"output_text",text:b}]}}))},q=new K,v=null,W=-1,Z=y=>{if(!v)return;let A=v;v=null,m({type:"response.function_call_arguments.done",item_id:A.fcId,output_index:A.outputIndex,arguments:A.args}),m({type:"response.output_item.done",output_index:A.outputIndex,item:{id:A.fcId,type:"function_call",call_id:A.callId??A.fcId,name:A.name??"",arguments:A.args,status:y}})},ee=!1;for await(let y of s.track(h,d)){p.push(y);let A=String(y.type??"");if(A==="response.created"||A==="response.in_progress"){T=!0,m($(y));continue}if(A==="response.output_item.added"){L=!0,m($(y));continue}if(A==="response.reasoning_text.delta"&&!L){k(),U||(U=!0,E=l++,m({type:"response.output_item.added",output_index:E,item:{id:N,type:"reasoning",summary:[],content:[],status:"in_progress"}})),M+=String(y.delta??""),m({type:"response.reasoning_text.delta",item_id:N,output_index:E,content_index:0,delta:y.delta});continue}if(A==="response.output_text.delta"&&!L){k(),D(),C||(C=!0,_=l++,m({type:"response.output_item.added",output_index:_,item:{id:S,type:"message",role:"assistant",status:"in_progress",content:[]}}),m({type:"response.content_part.added",item_id:S,output_index:_,content_index:0,part:{type:"output_text",text:""}})),b+=String(y.delta??""),m({type:A,item_id:S,output_index:_,content_index:0,delta:y.delta});continue}let R=L?null:ie(y);if(R){if(k(),D(),j("completed"),q.add(R),R.tool_index!==W){Z("completed"),W=R.tool_index;let w=l++;v={fcId:`fc_${u.slice(5)}_${R.tool_index}`,outputIndex:w,callId:R.call_id,name:R.name,args:""},m({type:"response.output_item.added",output_index:w,item:{id:v.fcId,type:"function_call",call_id:v.callId??v.fcId,name:v.name??"",arguments:"",status:"in_progress"}})}v&&(R.call_id&&(v.callId=R.call_id),R.name&&(v.name=R.name),v.args+=R.delta,m({type:"response.function_call_arguments.delta",item_id:v.fcId,output_index:v.outputIndex,delta:R.delta}));continue}if(A==="response.completed"&&!L){let w=re(y.response),I=Q(c,q.size+w.length,b);if(I){ee=!0,m({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:X(d,I)}});break}D(),j("completed"),Z("completed"),q.size===0&&w.forEach(G=>{let te=l++,ue=G.id??G.call_id??`fc_${te}`,ge=G.arguments??"",Oe={id:ue,type:"function_call",call_id:G.call_id??ue,name:G.name??""};m({type:"response.output_item.added",output_index:te,item:{...Oe,arguments:"",status:"in_progress"}}),m({type:"response.function_call_arguments.delta",item_id:ue,output_index:te,delta:ge}),m({type:"response.function_call_arguments.done",item_id:ue,output_index:te,arguments:ge}),m({type:"response.output_item.done",output_index:te,item:{...Oe,arguments:ge,status:"completed"}})}),m($(y));continue}m($(y))}D(),j("incomplete"),Z("incomplete"),f&&!ee&&e.remember(u,a,We(p,z(p))),o.write(`data: [DONE]
|
|
12
12
|
|
|
13
|
-
`),o.end();return}let g=null;for await(let
|
|
13
|
+
`),o.end();return}let g=null;for await(let m of s.track(h,d)){if(p.push(m),m.type==="error"){V(o,502,JSON.stringify(m),"upstream_error");return}m.type==="response.completed"&&(g=m.response)}if(g==null){V(o,502,"upstream produced no response.completed event","upstream_error");return}let O=We(p,g),P=Q(c,re(g).length,O);if(P){V(o,502,X(d,P),"upstream_error");return}f&&e.remember(u,a,O),H(o,200,{...g,id:u})}async function Et(n,t,e,o){let s=n.messages;if(!Array.isArray(s)){V(e,400,"chat/completions requires a messages array");return}let r=String(n.model??"urun"),a=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,u;try{u=It(s)}catch(l){if(l instanceof me){V(e,400,l.message);return}throw l}let f=Ie(n);o.model(f);let d=Array.isArray(n.tools)&&n.tools.length>0,c;try{c=await t.createResponse({model:n.model,input:u,stream:!0,tools:St(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,max_output_tokens:n.max_completion_tokens??n.max_tokens})}catch(l){if(l instanceof F){Re(e,"openai",l);return}throw l}if(n.stream===!0){Se(e);let l=[],k=new K,U="";e.write(`data: ${JSON.stringify(Y(a,r,{role:"assistant"},null))}
|
|
14
14
|
|
|
15
|
-
`);for await(let _ of o.track(
|
|
15
|
+
`);for await(let _ of o.track(c,f)){l.push(_);let b=ie(_);if(_.type==="response.output_text.delta"&&typeof _.delta=="string")U+=_.delta,e.write(`data: ${JSON.stringify(Y(a,r,{content:_.delta},null))}
|
|
16
16
|
|
|
17
17
|
`);else if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")e.write(`data: ${JSON.stringify(Y(a,r,{reasoning_content:_.delta},null))}
|
|
18
18
|
|
|
@@ -20,7 +20,7 @@ data: ${JSON.stringify(y)}
|
|
|
20
20
|
|
|
21
21
|
`)}else if(_.type==="error"){e.write(`data: ${JSON.stringify({error:_})}
|
|
22
22
|
|
|
23
|
-
`),e.end();return}}let E=ve(z(l)),M=Q(
|
|
23
|
+
`),e.end();return}}let E=ve(z(l)),M=Q(d,k.size+E.length,U);if(M){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:X(f,M)}})}
|
|
24
24
|
|
|
25
25
|
`),e.end();return}k.size===0&&E.length>0&&e.write(`data: ${JSON.stringify(Y(a,r,{tool_calls:E},null))}
|
|
26
26
|
|
|
@@ -30,7 +30,12 @@ data: ${JSON.stringify(y)}
|
|
|
30
30
|
|
|
31
31
|
`),e.write(`data: [DONE]
|
|
32
32
|
|
|
33
|
-
`),e.end();return}let h="",p="",g=[],O=new K;for await(let l of o.track(
|
|
33
|
+
`),e.end();return}let h="",p="",g=[],O=new K;for await(let l of o.track(c,f)){g.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(h+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(p+=l.delta);let k=ie(l);if(k&&O.add(k),l.type==="error"){V(e,502,JSON.stringify(l),"upstream_error");return}}let P=z(g),m=ve(P),$=m.length>0?m:ve({output:O.items()}),S=Q(d,$.length,h);if(S){V(e,502,X(f,S),"upstream_error");return}let N=$.map(({index:l,...k})=>k),T={role:"assistant",content:h||null},L=p||Xe(P);L&&(T.reasoning_content=L),N.length>0&&(T.tool_calls=N),H(e,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,message:T,finish_reason:N.length>0?"tool_calls":"stop"}],usage:Ke(P)})}function Tt(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(t=>t.type==="text").map(t=>String(t.text??"")).join(""):""}var ae=class extends Error{};function he(n){return new ae(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ct(n){if(Array.isArray(n))return n.map(t=>{let e=t;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema}})}function Pt(n){if(n==null)return;let t=n.type;if(t==="auto")return"auto";if(t==="none")return"none";if(t==="any")return"required";if(t==="tool")return{type:"function",name:n.name};throw new ae(`unsupported anthropic tool_choice type ${JSON.stringify(String(t))} \u2014 the proxy maps auto, none, any and tool`)}function $t(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw he(typeof n);let t="";for(let e of n){let o=String(e.type??"");if(o!=="text")throw he(`tool_result > ${o}`);t+=String(e.text??"")}return t}function Nt(n){let{role:t,content:e}=n;if(typeof e=="string")return[{role:t,content:e}];if(e==null)return[];if(!Array.isArray(e))throw he(typeof e);let o=[],s="",r=()=>{s&&(o.push({role:t,content:s}),s="")};for(let a of e){let u=String(a.type??"");if(u==="text")s+=String(a.text??"");else if(u==="tool_use")r(),o.push({type:"function_call",call_id:a.id,name:a.name,arguments:JSON.stringify(a.input??{})});else if(u==="tool_result")r(),o.push({type:"function_call_output",call_id:a.tool_use_id,output:$t(a.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw he(u)}}return r(),o}function xe(n){return re(n).map((t,e)=>{let o;try{o=JSON.parse(t.arguments||"{}")}catch{throw new Error(`upstream function_call "${t.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:t.call_id??t.id??`toolu_${e}`,name:t.name??"",input:o}})}async function Lt(n,t,e,o){let s=n.messages;if(!Array.isArray(s)){B(e,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){B(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){B(e,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(l=>typeof l!="string"))){B(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let r=String(n.model??"urun"),a=`msg_${Math.random().toString(36).slice(2,14)}`,u=[],f;try{n.system&&u.push({role:"system",content:Tt(n.system)});for(let l of s)u.push(...Nt(l));f=Pt(n.tool_choice)}catch(l){if(l instanceof ae){B(e,400,"invalid_request_error",l.message);return}throw l}let d=Ie(n);o.model(d);let c=Array.isArray(n.tools)&&n.tools.length>0,h;try{h=await t.createResponse({model:n.model,input:u,stream:!0,tools:Ct(n.tools),tool_choice:f,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences})}catch(l){if(l instanceof F){Re(e,"anthropic",l);return}throw l}let p=(l,k)=>{e.destroyed||e.write(`event: ${l}
|
|
34
34
|
data: ${JSON.stringify({type:l,...k})}
|
|
35
35
|
|
|
36
|
-
`)};if(n.stream===!0){let l=o.track(h,
|
|
36
|
+
`)};if(n.stream===!0){let l=o.track(h,d);Se(e),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:r,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let k=0,U="",E=0,M="none",D=()=>M,C=-1,_=-1,b=new K,j=[],q=()=>{M!=="none"&&(M="none",p("content_block_stop",{index:C}))},v=(w,I)=>{q(),M=w,C=E++,p("content_block_start",{index:C,content_block:I})};for await(let w of l){if(e.destroyed)break;j.push(w);let I=ie(w);if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")D()!=="thinking"&&v("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:C,delta:{type:"thinking_delta",thinking:w.delta}});else if(w.type==="response.output_text.delta"&&typeof w.delta=="string")D()!=="text"&&v("text",{type:"text",text:""}),k+=1,U+=w.delta,p("content_block_delta",{index:C,delta:{type:"text_delta",text:w.delta}});else if(I){let{call:G}=b.add(I);(D()!=="tool"||I.tool_index!==_)&&(_=I.tool_index,v("tool",{type:"tool_use",id:G.id??`call_${I.tool_index}`,name:G.name??"",input:{}})),I.delta&&p("content_block_delta",{index:C,delta:{type:"input_json_delta",partial_json:I.delta}})}else if(w.type==="error"){p("error",{error:{type:"api_error",message:JSON.stringify(w)}}),e.end();return}}if(e.destroyed)return;let W=z(j),Z=re(W),ee=Q(c,b.size+Z.length,U);if(ee){p("error",{error:{type:"api_error",message:X(d,ee)}}),e.end();return}q();let y=[];if(b.size===0)try{y=xe(W)}catch(w){p("error",{error:{type:"api_error",message:String(w instanceof Error?w.message:w)}}),e.end();return}E===0&&y.length===0&&(v("text",{type:"text",text:""}),q()),y.forEach(w=>{let I=E++;p("content_block_start",{index:I,content_block:{...w,input:{}}}),p("content_block_delta",{index:I,delta:{type:"input_json_delta",partial_json:JSON.stringify(w.input??{})}}),p("content_block_stop",{index:I})});let A=b.size>0||y.length>0,R=fe(W);p("message_delta",{delta:{stop_reason:A?"tool_use":"end_turn"},usage:R?{input_tokens:R.input_tokens,output_tokens:R.output_tokens}:{output_tokens:k}}),p("message_stop",{}),e.end();return}let g="",O="",P=[],m=new K;for await(let l of o.track(h,d)){P.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(g+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(O+=l.delta);let k=ie(l);if(k&&m.add(k),l.type==="error"){B(e,502,"api_error",JSON.stringify(l));return}if(e.destroyed)break}if(e.destroyed)return;let $=z(P),S;try{S=xe($),S.length===0&&m.size>0&&(S=xe({output:m.items()}))}catch(l){B(e,502,"api_error",String(l instanceof Error?l.message:l));return}let N=Q(c,S.length,g);if(N){B(e,502,"api_error",X(d,N));return}let T=[],L=O||Xe($);L&&T.push({type:"thinking",thinking:L}),(g||S.length===0)&&T.push({type:"text",text:g}),T.push(...S),H(e,200,{id:a,type:"message",role:"assistant",content:T,model:r,stop_reason:S.length>0?"tool_use":"end_turn",usage:fe($)??{input_tokens:0,output_tokens:0}})}function Qe(n){let{clients:t,apiKey:e,identity:o}=n,s=new be,r=new Ae,a=(0,Ye.createServer)((u,f)=>{let d=new URL(u.url??"/","http://localhost"),c=d.pathname==="/v1/messages"||d.pathname.startsWith("/v1/messages/"),h=(p,g,O,P)=>c?B(f,p,P,g):V(f,p,g,O);(async()=>{if(u.method==="GET"&&d.pathname==="/healthz"){H(f,200,{ok:!0});return}if(u.method==="GET"&&d.pathname==="/stats"){H(f,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(e&&(u.headers.authorization??"")!==`Bearer ${e}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}if(u.method==="GET"&&d.pathname==="/v1/models"){H(f,200,await t.listModels());return}if(u.method!=="POST"){h(404,`no route for ${u.method} ${d.pathname}`,"invalid_request_error","not_found_error");return}let p;try{p=await kt(u)}catch(O){if(O instanceof pe){h(413,O.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=Buffer.byteLength(JSON.stringify(p));if(d.pathname==="/v1/responses"){r.request("responses",g,g),await Ot(p,t,s,f,r);return}if(d.pathname==="/v1/chat/completions"){r.request("chat_completions",g,g),await Et(p,t,f,r);return}if(d.pathname==="/v1/messages"){r.request("messages",g,g),await Lt(p,t,f,r);return}if(d.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",g,g),B(f,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}h(404,`no route for POST ${d.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let g=String(p instanceof Error?p.message:p);if(!f.headersSent){h(500,g,"proxy_error","api_error");return}f.destroyed||(c?f.write(`event: error
|
|
37
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:g}})}
|
|
38
|
+
|
|
39
|
+
`):f.write(`data: ${JSON.stringify({error:{message:g,type:"upstream_error"}})}
|
|
40
|
+
|
|
41
|
+
`)),f.end()})});return Ge(a,{clients:t,apiKey:e}),a}0&&(module.exports={GEMINI_LIVE_PATH,createOpenAIProxy});
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r,b as e}from"../chunk-
|
|
1
|
+
import{a as r,b as e}from"../chunk-TEZ4WLY6.js";import"../chunk-VFHQZ4OM.js";import"../chunk-VXTNG2TP.js";export{r as GEMINI_LIVE_PATH,e as createOpenAIProxy};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.59",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -43,11 +43,11 @@
|
|
|
43
43
|
"dist"
|
|
44
44
|
],
|
|
45
45
|
"scripts": {
|
|
46
|
-
"build": "tsup && node ../../scripts/sanitize-dist.mjs .",
|
|
47
|
-
"prepack": "pnpm build && node scripts/assert-pack-contents.mjs",
|
|
46
|
+
"build": "tsup && node ../../scripts/sanitize-dist.mjs . && node scripts/pi-extension-smoke.mjs",
|
|
47
|
+
"prepack": "pnpm build && node scripts/assert-pack-contents.mjs && node scripts/assert-pi-extension-factory.mjs",
|
|
48
48
|
"test": "vitest run",
|
|
49
49
|
"dev": "tsup --watch",
|
|
50
|
-
"build:bin": "bun build --compile --external @roamhq/wrtc
|
|
50
|
+
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"@urun-sh/core": "^0.2.53"
|