@urun-sh/openai 0.2.59 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-BDl1OIRP.d.cts → ResponsesClient-y8g6OfNN.d.cts} +2 -0
- package/dist/{ResponsesClient-BDl1OIRP.d.ts → ResponsesClient-y8g6OfNN.d.ts} +2 -0
- package/dist/chunk-35LB5OHI.js +1 -0
- package/dist/chunk-3ED25N7E.js +1 -0
- package/dist/chunk-EFBD3CGZ.js +1 -0
- package/dist/chunk-F2TEK34X.js +1 -0
- package/dist/chunk-VG3X2LVG.js +41 -0
- package/dist/chunk-XHIIEA6Z.js +1 -0
- package/dist/chunk-XHRPJIEK.js +6 -0
- package/dist/chunk-YSFSRI3D.js +1 -0
- package/dist/hosted/bin.cjs +56 -0
- package/dist/hosted/bin.js +23 -0
- package/dist/hosted/index.cjs +34 -0
- package/dist/hosted/index.d.cts +620 -0
- package/dist/hosted/index.d.ts +225 -0
- package/dist/hosted/index.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +5 -5
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +7 -7
- package/dist/pi-extension/standalone.cjs +53 -53
- package/dist/proxy/cli.cjs +34 -34
- package/dist/proxy/cli.js +14 -19
- package/dist/proxy/index.cjs +21 -21
- package/dist/proxy/index.d.cts +4 -147
- package/dist/proxy/index.d.ts +4 -61
- package/dist/proxy/index.js +1 -1
- package/dist/server-BBKNv7hV.d.ts +78 -0
- package/dist/server-DiQUIDDg.d.cts +182 -0
- package/package.json +12 -2
- package/dist/chunk-62IL5R2N.js +0 -1
- package/dist/chunk-OLE2YJO3.js +0 -1
- package/dist/chunk-TEZ4WLY6.js +0 -41
- package/dist/chunk-VFHQZ4OM.js +0 -1
- package/dist/chunk-VXTNG2TP.js +0 -1
package/dist/proxy/cli.js
CHANGED
|
@@ -1,20 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as j}from"../chunk-
|
|
3
|
-
`)
|
|
4
|
-
`)}
|
|
5
|
-
`)}
|
|
6
|
-
`)
|
|
7
|
-
`)
|
|
8
|
-
`)
|
|
9
|
-
`)
|
|
10
|
-
`)
|
|
11
|
-
`)
|
|
12
|
-
`),
|
|
13
|
-
`),
|
|
14
|
-
`)
|
|
15
|
-
`)
|
|
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};
|
|
2
|
+
import{a as k,b as $,c as h,d as C,e as U,f as N,g as O,h as L,i as G,j as E,k as I,l as y,n as _,o as P,p as W,q as j,r as B,s as D,t as v,u as K,v as M,w as F}from"../chunk-XHRPJIEK.js";import"../chunk-F2TEK34X.js";import{c as T}from"../chunk-VG3X2LVG.js";import{c as R}from"../chunk-35LB5OHI.js";import"../chunk-EFBD3CGZ.js";import"../chunk-XHIIEA6Z.js";import{c as g}from"../chunk-YSFSRI3D.js";g();import{spawn as V}from"child_process";import{appendFileSync as Y,createWriteStream as re,existsSync as ne,mkdirSync as oe}from"fs";import ae from"path";import t from"process";g();import{ensureNodeWebRTC as Z,nodeWebRTCUnavailableReason as ee}from"@urun-sh/core/internal";var te={ensureWebRTC:Z,webrtcUnavailableReason:ee,audioBackend:R};async function J(e=te){try{await e.ensureWebRTC()}catch(r){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(r)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \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(r){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(r)}`}}return{ok:!0,reason:null}}function ie(e,i){let r=(e.URUN_CATALOG_URL??"").trim(),l=r?_(r,"URUN_CATALOG_URL"):"",n=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!n?(i(`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
|
|
3
|
+
`),null):{catalogUrl:l,anonKey:n}}function se(e){return k({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:ie(t.env,i=>t.stderr.write(i))})}async function le(e,i,r){let l=V(e,i,{stdio:"inherit",env:r});return new Promise(n=>{l.once("exit",o=>n(o??1)),l.once("error",o=>{t.stderr.write(`failed to launch ${e}: ${String(o)}
|
|
4
|
+
`),n(127)})})}function ue(){return L(t.env,import.meta.url,ne)}function q(e){for(let[i,r]of Object.entries(C(e)))t.stdout.write(`export ${i}=${r}
|
|
5
|
+
`)}async function H(e,i){let r=y(t.env),l=i?P(r):void 0,n=se(r),o=T({clients:$(n),identity:l});try{await new Promise((s,d)=>{o.once("error",d),o.listen(e,"127.0.0.1",s)})}catch(s){throw await n.closeAll().catch(()=>{}),s.code==="EADDRINUSE"?new Error(F(e,await W(e))):s}let u=o.address().port;return i&&(t.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1
|
|
6
|
+
`),q(u)),{port:u,close:async()=>{let s=new Promise(d=>o.close(()=>d()));o.closeAllConnections(),await s,await n.closeAll()}}}async function ce(){let e=t.argv.slice(2),i=G(e),r=e.shift()??"proxy";if(r==="env")return q(I(i??E(e))),0;if(r==="selftest"){let{ok:n,reason:o}=await J();return n?(t.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
7
|
+
`),0):(t.stderr.write(`urun-openai selftest: FAIL \u2014 ${o}
|
|
8
|
+
`),1)}if(r==="proxy"){let n=i??E(e),o=await H(n,!0);return await new Promise(u=>{t.once("SIGINT",u),t.once("SIGTERM",u)}),await o.close(),0}let l=r==="run"?e.shift():r;{if(!l)throw new Error(`launch needs an agent (${Object.keys(h).join("|")}) or \`-- <cmd>\``);if(l==="pi"){let a=y(t.env);return le("pi",["-e",ue(),...O(a.appId,e)],t.env)}let n,o,u="openai";if(l==="--"){if(n=e.shift()??"",o=e,!n)throw new Error("`-- <cmd>` needs a command to launch")}else{let a=h[l];if(!a)throw new Error(`unknown command/agent ${l}; commands: proxy | env; agents: ${Object.keys(h).join(" | ")} \u2014 or \`-- <cmd>\``);n=a.bin,o=[...a.args??[],...e],u=a.env}let s=await j(i,P(y(t.env))),d=null,f=s.port;s.mode==="reuse"?t.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${f} (app ${s.identity.app}, fn ${s.identity.fn}, v${s.identity.proxy_version})
|
|
9
|
+
`):s.reason&&t.stderr.write(`urun compat: ${s.reason}
|
|
10
|
+
`);let c=null,b=null,w=null,p=null;s.mode!=="reuse"&&(d=await H(s.port,!1),f=d.port,p=B(f),oe(ae.dirname(p),{recursive:!0}),w=re(p,{flags:"a"}),b=K({streams:t,note:a=>Y(p,a)}).uninstall,w.on("error",a=>{c?.(),c=null,v(t.stderr,`urun compat: proxy log ${p} failed: ${String(a)} \u2014 proxy output continues on the terminal
|
|
11
|
+
`)}),t.stdout.write(`urun openai proxy on http://127.0.0.1:${f}/v1 \u2014 proxy logs: ${p}
|
|
12
|
+
`),c=D(w)),l==="codex"&&(o=N(f,y(t.env).appId,o));let x=V(n,o,{stdio:"inherit",env:U(t.env,f,u)}),z=p!==null?M({logPath:p,appendSync:Y,restore:()=>{c?.(),c=null},writeStderr:a=>t.stderr.write(a),killChild:()=>x.kill("SIGTERM"),exit:a=>t.exit(a),proc:t}):null,A=await new Promise(a=>{x.once("exit",S=>a(S??1)),x.once("error",S=>{c?.(),c=null,v(t.stderr,`failed to launch ${n}: ${String(S)}
|
|
13
|
+
`),a(127)})});z?.();let m=null;try{d&&await d.close()}catch(a){m=a}finally{c?.(),c=null,b?.(),b=null,w?.end()}return m!==null&&v(t.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${A} preserved): ${String(m instanceof Error?m.message:m)}
|
|
14
|
+
`),A}}ce().then(e=>t.exit(e),e=>{t.stderr.write(`${String(e instanceof Error?e.message:e)}
|
|
15
|
+
`),t.exit(1)});
|
package/dist/proxy/index.cjs
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
"use strict";var ye=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(n
|
|
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
|
|
1
|
+
"use strict";var ye=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(t,n)=>{for(var e in n)ye(t,e,{get:n[e],enumerable:!0})},ot=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of et(n))!tt.call(t,s)&&s!==e&&ye(t,s,{get:()=>n[s],enumerable:!(o=Ze(n,s))||o.enumerable});return t};var st=t=>ot(ye({},"__esModule",{value:!0}),t);var Ut={};nt(Ut,{GEMINI_LIVE_PATH:()=>de,createOpenAIProxy:()=>Qe});module.exports=st(Ut);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},b=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,le=["setup","clientContent","realtimeInput","toolResponse"];function Ce(t){let n;try{n=JSON.parse(t)}catch{throw new i("client message is not valid JSON")}let e=b(n);if(!e)throw new i("client message must be a JSON object");let o=le.filter(d=>e[d]!==void 0),s=Object.keys(e).filter(d=>!le.includes(d));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=b(e[r]);if(!a)throw new i(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function Pe(t,n){if(typeof t=="string")return t;let e=b(t),o=e?e.parts:void 0;if(!Array.isArray(o))throw new i(`${n}: expected a Content with a parts array`);let s=[];for(let r of o){let a=b(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new i(`${n}: 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(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new i(`${n}: 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(t){let n=b(t);if(!n)throw new i("setup.realtimeInputConfig must be an object");for(let s of Object.keys(n))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=b(n.automaticActivityDetection);if(n.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(n.activityHandling!==void 0){if(!Ee.includes(n.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Ee.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var dt=["temperature","maxOutputTokens","responseModalities"];function $e(t){for(let[u,f]of Object.entries(ut))if(t[u]!==void 0)throw new i(f);for(let u of Object.keys(t))if(!lt.includes(u))throw new i(`unsupported setup field "${u}"`);if(typeof t.model!="string"||t.model.length===0)throw new i('setup.model is required (format "models/{model}")');let n=t.model.replace(/^models\//,""),e,o,s=!1,r=b(t.generationConfig);if(t.generationConfig!==void 0&&!r)throw new i("setup.generationConfig must be an object");if(r){for(let u of Object.keys(r))if(!dt.includes(u))throw new i(`unsupported generationConfig field "${u}"`);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 u=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let f of u){let g=String(f).toUpperCase();if(g==="AUDIO"){s=!0;continue}if(g!=="TEXT")throw new i(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let a=[];t.systemInstruction!==void 0&&a.push({role:"system",content:Pe(t.systemInstruction,"setup.systemInstruction")});let d;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new i("setup.tools must be an array");d=[];for(let u of t.tools){let f=b(u);if(!f)throw new i("setup.tools entries must be objects");for(let g of Object.keys(f))if(g!=="functionDeclarations")throw new i(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let g of f.functionDeclarations){let y=b(g);if(!y||typeof y.name!="string")throw new i("functionDeclarations entries require a string name");d.push({type:"function",name:y.name,description:y.description,parameters:y.parameters})}}d.length===0&&(d=void 0)}let m={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let u=b(t.sessionResumption);if(!u)throw new i("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(u))if(f!=="handle")throw new i(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(u.handle!==void 0&&(typeof u.handle!="string"||u.handle.length===0))throw new i("sessionResumption.handle must be a non-empty string when present");m={enabled:!0,handle:typeof u.handle=="string"?u.handle:null}}let p=t.realtimeInputConfig===void 0?at:ct(t.realtimeInputConfig);return{model:n,systemItems:a,tools:d,temperature:e,maxOutputTokens:o,audioModality:s,activity:p,sessionResumption:m}}function Ne(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Me(t){let n=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function Le(t){for(let o of Object.keys(t))if(o!=="turns"&&o!=="turnComplete")throw new i(`unsupported clientContent field "${o}"`);let n=t.turns===void 0?[]:t.turns;if(!Array.isArray(n))throw new i("clientContent.turns must be an array");let e=[];for(let o of n){let s=b(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:t.turnComplete===!0}}var ce=16e3,Ue=24e3,pt=`audio/pcm;rate=${Ue}`,De=Buffer.alloc(960).toString("base64");function ft(t,n,e){if(n===e)return t;let o=Math.floor(t.length*e/n),s=new Int16Array(o),r=n/e,a=t.length-1;for(let d=0;d<o;d++){let m=d*r,p=Math.floor(m);if(p>=a){s[d]=t[a];continue}let u=m-p;s[d]=Math.round(t[p]+(t[p+1]-t[p])*u)}return s}function mt(t){let n=b(t);if(!n)throw new i("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new i("realtimeInput.video.data must be non-empty base64");let e=Buffer.from(n.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 gt(t){let n=b(t);if(!n)throw new i("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let e=/;\s*rate=(\d+)/.exec(n.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 n.data!="string"||n.data.length===0)throw new i("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.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(t){if(t.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(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new i("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=t.activityStart!==void 0?"activityStart":"activityEnd",r=b(t[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 n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(t))if(!n.includes(o))throw new i(`unsupported realtimeInput field "${o}"`);let e=n.filter(o=>t[o]!==void 0);if(e.length!==1)throw new i(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${e.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:gt(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:mt(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new i("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new i("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function He(t){for(let n of Object.keys(t))if(n!=="functionResponses")throw new i(`unsupported toolResponse field "${n}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new i("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(n=>{let e=b(n);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(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function qe(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:pt,data:t}}]}}}}function Fe(t){let n=b(t)??{},e=Array.isArray(n.output)?n.output:[],o=[],s=[],r=typeof n.output_text=="string"?n.output_text:"";if(!r)for(let p of e){let u=b(p);if(!(u?.type!=="message"||!Array.isArray(u.content)))for(let f of u.content){let g=b(f);g?.type==="output_text"&&typeof g.text=="string"&&(r+=g.text)}}r&&s.push({role:"assistant",content:r});for(let p of e){let u=b(p);if(u?.type!=="function_call")continue;if(typeof u.call_id!="string"||typeof u.name!="string")throw new i(`upstream function_call item is missing call_id/name: ${JSON.stringify(p)}`,J);let f=typeof u.arguments=="string"&&u.arguments.length>0?u.arguments:"{}",g;try{g=JSON.parse(f)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${f}`,J)}o.push({id:u.call_id,name:u.name,args:g}),s.push({type:"function_call",call_id:u.call_id,name:u.name,arguments:f})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let d=b(n.usage),m={serverContent:{turnComplete:!0}};if(d){let p={};typeof d.input_tokens=="number"&&(p.promptTokenCount=d.input_tokens),typeof d.output_tokens=="number"&&(p.responseTokenCount=d.output_tokens),typeof d.total_tokens=="number"&&(p.totalTokenCount=d.total_tokens),Object.keys(p).length>0&&(m.usageMetadata=p)}return a.push(m),{messages:a,assistantItems:s}}var ht=256,_e=class{snapshots=new Map;store(n,e){for(this.snapshots.set(n,e);this.snapshots.size>ht;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},se=t=>t.slice(0,120),ke=class{constructor(n,e,o){this.ws=n;this.clients=e;this.registry=o;n.on("message",s=>this.onMessage(s)),n.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(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof F){this.ws.close(Te,se(n.message));return}if(n instanceof ne){this.ws.close(we,se(n.message));return}if(n instanceof i){this.ws.close(n.closeCode,se(n.message));return}this.ws.close(J,se(String(n instanceof Error?n.message:n)))}onMessage(n){try{let e=Ce(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).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}=Le(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(n){if(this.config)throw new i("setup may only be sent once, as the first client message");let e=$e(n),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 n=this.config;if(!n)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,n.model);return this.detachAudio=o.onOutputAudio(s=>this.send(qe(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(e=>e.appendInputAudio(n)).catch(e=>this.fail(e))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)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,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(e=>e.sendInputFrame(n)).catch(e=>this.fail(e))}onActivity(n,e){if(!e.activity.manualActivity)throw new i(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="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(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(e=>this.fail(e))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let e=await this.clients.sessionHandle(n.model);this.proxyHandle=e;let o=(0,Je.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Ne(o))}async handleUpstreamEnd(n){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(Me(n.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let e={interrupted:!1};this.activeTurn=e;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),s,r=!1;for await(let m of o){if(e.interrupted)break;let p=m;if(p.type==="error")throw new i(`upstream error: ${JSON.stringify(p)}`,J);if(p.type==="response.completed"){s=p.response,r=!0;continue}let u=je(p);u&&this.send(u)}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:d}=Fe(s);this.transcript.push(...d);for(let m of a)this.send(m);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},yt=(t,n)=>{let e=t.headers["x-goog-api-key"];if(typeof e=="string")return e;let o=t.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Ge(t,n){let e=new Ve.WebSocketServer({noServer:!0}),o=new _e;t.on("upgrade",(s,r,a)=>{let d=new URL(s.url??"/","http://localhost");if(d.pathname!==de){r.write(`HTTP/1.1 404 Not Found\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
no WS route for ${
|
|
5
|
+
no WS route for ${d.pathname}`),r.destroy();return}if(n.apiKey&&yt(s,d)!==n.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,
|
|
9
|
-
data: ${JSON.stringify(
|
|
8
|
+
invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,m=>{new ke(m,n.clients,o)})})}var Ae=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=o}modelEntry(n){let e=this.models[n];if(e)return e;let o=Object.keys(this.models).length>=wt?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let o=this,s=performance.now(),r=null,a=0;return(async function*(){for await(let m of n)m.type==="response.output_text.delta"&&typeof m.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+=m.delta.length,e!==void 0&&(o.modelEntry(e).tokens_out+=1)),yield m;let d=(performance.now()-(r??s))/1e3;a>0&&d>0&&(o.tokRates.push(a/d),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((o,s)=>o-s);return e[Math.floor(e.length/2)]}snapshot(){let n=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:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},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(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function H(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function V(t,n,e,o="invalid_request_error"){H(t,n,{error:{message:e,type:o}})}function B(t,n,e,o){H(t,n,{type:"error",error:{type:e,message:o}})}function Re(t,n,e){if(n==="anthropic"){H(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}H(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var wt=256,_t=128;function Ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,_t)}var Ke=64*1024*1024,pe=class extends Error{};async function kt(t){let n=[],e=0;for await(let s of t){if(e+=s.length,e>Ke)throw new pe(`request body exceeds ${Ke} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Y(t,n,e,o){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:o}]}}var vt=256;function xt(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var be=class{conversations=new Map;thread(n,e){let o=xt(e);if(n==null)return o;let s=this.conversations.get(String(n));if(!s)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(n,e,o){this.conversations.set(n,[...e,{role:"assistant",content:o}]);for(let s of this.conversations.keys()){if(this.conversations.size<=vt)break;this.conversations.delete(s)}}};function re(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function K(t){return t.find(n=>n.type==="response.completed")?.response??null}function fe(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=e(n.input_tokens),s=e(n.output_tokens);if(o===0&&s===0)return null;let r=e(n.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:r}}function ze(t){let n=fe(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Xe(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let o of n)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(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var z=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),o=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},At=["<tool_call>","<function="];function bt(t){return At.find(n=>t.includes(n))}function X(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} 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 "${t}" (see catalog parser_defaults)`}function Q(t,n,e){if(!(!t||n>0))return bt(e)}function St(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var me=class extends Error{};function Rt(t,n){return Array.isArray(n)?n.map(e=>{let o=e;if(o.type==="text")return{type:t==="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`)}):n}function It(t){let n=[];for(let e of t){if(e.role==="tool"){n.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&&n.push({role:"assistant",content:e.content});for(let o of e.tool_calls){let s=o.function??{};n.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}n.push({...e,content:Rt(e.role,e.content)})}return n}function ve(t){return re(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function We(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function Ot(t,n,e,o,s){let r=t.stream===!0,a;try{a=e.thread(t.previous_response_id,t.input)}catch(l){V(o,400,String(l instanceof Error?l.message:l));return}t.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(t.input)));let d=`resp_${Math.random().toString(36).slice(2,14)}`,m=t.store!==!1,p=Ie(t);s.model(p);let u=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await n.createResponse({model:t.model,input:a,stream:r,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(l){if(l instanceof F){Re(o,"openai",l);return}throw l}let g=[];if(r){Se(o);let l=h=>{o.write(`event: ${String(h.type??"message")}
|
|
9
|
+
data: ${JSON.stringify(h)}
|
|
10
10
|
|
|
11
|
-
`)}
|
|
11
|
+
`)},I=h=>h.response&&typeof h.response=="object"?{...h,response:{...h.response,id:d}}:h,O=`item_${d.slice(5)}`,N=`rs_${d.slice(5)}`,P=!1,M=!1,c=0,x=()=>{P||(P=!0,l({type:"response.created",response:{id:d,object:"response",status:"in_progress"}}))},U=!1,C=0,L="",D=()=>{U&&(U=!1,l({type:"response.reasoning_text.done",item_id:N,output_index:C,content_index:0,text:L}),l({type:"response.output_item.done",output_index:C,item:{id:N,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:L}],status:"completed"}}))},$=!1,v=0,R="",j=h=>{$&&($=!1,l({type:"response.output_text.done",item_id:O,output_index:v,content_index:0,text:R}),l({type:"response.content_part.done",item_id:O,output_index:v,content_index:0,part:{type:"output_text",text:R}}),l({type:"response.output_item.done",output_index:v,item:{id:O,type:"message",role:"assistant",status:h,content:[{type:"output_text",text:R}]}}))},q=new z,A=null,W=-1,Z=h=>{if(!A)return;let S=A;A=null,l({type:"response.function_call_arguments.done",item_id:S.fcId,output_index:S.outputIndex,arguments:S.args}),l({type:"response.output_item.done",output_index:S.outputIndex,item:{id:S.fcId,type:"function_call",call_id:S.callId??S.fcId,name:S.name??"",arguments:S.args,status:h}})},ee=!1;for await(let h of s.track(f,p)){g.push(h);let S=String(h.type??"");if(S==="response.created"||S==="response.in_progress"){P=!0,l(I(h));continue}if(S==="response.output_item.added"){M=!0,l(I(h));continue}if(S==="response.reasoning_text.delta"&&!M){x(),U||(U=!0,C=c++,l({type:"response.output_item.added",output_index:C,item:{id:N,type:"reasoning",summary:[],content:[],status:"in_progress"}})),L+=String(h.delta??""),l({type:"response.reasoning_text.delta",item_id:N,output_index:C,content_index:0,delta:h.delta});continue}if(S==="response.output_text.delta"&&!M){x(),D(),$||($=!0,v=c++,l({type:"response.output_item.added",output_index:v,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}}),l({type:"response.content_part.added",item_id:O,output_index:v,content_index:0,part:{type:"output_text",text:""}})),R+=String(h.delta??""),l({type:S,item_id:O,output_index:v,content_index:0,delta:h.delta});continue}let E=M?null:ie(h);if(E){if(x(),D(),j("completed"),q.add(E),E.tool_index!==W){Z("completed"),W=E.tool_index;let w=c++;A={fcId:`fc_${d.slice(5)}_${E.tool_index}`,outputIndex:w,callId:E.call_id,name:E.name,args:""},l({type:"response.output_item.added",output_index:w,item:{id:A.fcId,type:"function_call",call_id:A.callId??A.fcId,name:A.name??"",arguments:"",status:"in_progress"}})}A&&(E.call_id&&(A.callId=E.call_id),E.name&&(A.name=E.name),A.args+=E.delta,l({type:"response.function_call_arguments.delta",item_id:A.fcId,output_index:A.outputIndex,delta:E.delta}));continue}if(S==="response.completed"&&!M){let w=re(h.response),T=Q(u,q.size+w.length,R);if(T){ee=!0,l({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:X(p,T)}});break}D(),j("completed"),Z("completed"),q.size===0&&w.forEach(G=>{let te=c++,ue=G.id??G.call_id??`fc_${te}`,he=G.arguments??"",Oe={id:ue,type:"function_call",call_id:G.call_id??ue,name:G.name??""};l({type:"response.output_item.added",output_index:te,item:{...Oe,arguments:"",status:"in_progress"}}),l({type:"response.function_call_arguments.delta",item_id:ue,output_index:te,delta:he}),l({type:"response.function_call_arguments.done",item_id:ue,output_index:te,arguments:he}),l({type:"response.output_item.done",output_index:te,item:{...Oe,arguments:he,status:"completed"}})}),l(I(h));continue}l(I(h))}D(),j("incomplete"),Z("incomplete"),m&&!ee&&e.remember(d,a,We(g,K(g))),o.write(`data: [DONE]
|
|
12
12
|
|
|
13
|
-
`),o.end();return}let
|
|
13
|
+
`),o.end();return}let y=null;for await(let l of s.track(f,p)){if(g.push(l),l.type==="error"){V(o,502,JSON.stringify(l),"upstream_error");return}l.type==="response.completed"&&(y=l.response)}if(y==null){V(o,502,"upstream produced no response.completed event","upstream_error");return}let k=We(g,y),_=Q(u,re(y).length,k);if(_){V(o,502,X(p,_),"upstream_error");return}m&&e.remember(d,a,k),H(o,200,{...y,id:d})}async function Et(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){V(e,400,"chat/completions requires a messages array");return}let r=String(t.model??"urun"),a=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,d;try{d=It(s)}catch(c){if(c instanceof me){V(e,400,c.message);return}throw c}let m=Ie(t);o.model(m);let p=Array.isArray(t.tools)&&t.tools.length>0,u;try{u=await n.createResponse({model:t.model,input:d,stream:!0,tools:St(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(c){if(c instanceof F){Re(e,"openai",c);return}throw c}if(t.stream===!0){Se(e);let c=[],x=new z,U="";e.write(`data: ${JSON.stringify(Y(a,r,{role:"assistant"},null))}
|
|
14
14
|
|
|
15
|
-
`);for await(let
|
|
15
|
+
`);for await(let v of o.track(u,m)){c.push(v);let R=ie(v);if(v.type==="response.output_text.delta"&&typeof v.delta=="string")U+=v.delta,e.write(`data: ${JSON.stringify(Y(a,r,{content:v.delta},null))}
|
|
16
16
|
|
|
17
|
-
`);else if(
|
|
17
|
+
`);else if(v.type==="response.reasoning_text.delta"&&typeof v.delta=="string")e.write(`data: ${JSON.stringify(Y(a,r,{reasoning_content:v.delta},null))}
|
|
18
18
|
|
|
19
|
-
`);else if(
|
|
19
|
+
`);else if(R){let{call:j,isNew:q}=x.add(R),A=q?{index:R.tool_index,id:j.id??`call_${R.tool_index}`,type:"function",function:{name:j.name??"",arguments:R.delta}}:{index:R.tool_index,function:{arguments:R.delta}};e.write(`data: ${JSON.stringify(Y(a,r,{tool_calls:[A]},null))}
|
|
20
20
|
|
|
21
|
-
`)}else if(
|
|
21
|
+
`)}else if(v.type==="error"){e.write(`data: ${JSON.stringify({error:v})}
|
|
22
22
|
|
|
23
|
-
`),e.end();return}}let
|
|
23
|
+
`),e.end();return}}let C=ve(K(c)),L=Q(p,x.size+C.length,U);if(L){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:X(m,L)}})}
|
|
24
24
|
|
|
25
|
-
`),e.end();return}
|
|
25
|
+
`),e.end();return}x.size===0&&C.length>0&&e.write(`data: ${JSON.stringify(Y(a,r,{tool_calls:C},null))}
|
|
26
26
|
|
|
27
|
-
`);let D=
|
|
27
|
+
`);let D=x.size>0||C.length>0;e.write(`data: ${JSON.stringify(Y(a,r,{},D?"tool_calls":"stop"))}
|
|
28
28
|
|
|
29
|
-
`),fe(
|
|
29
|
+
`),fe(K(c))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[],usage:ze(K(c))})}
|
|
30
30
|
|
|
31
31
|
`),e.write(`data: [DONE]
|
|
32
32
|
|
|
33
|
-
`),e.end();return}let
|
|
34
|
-
data: ${JSON.stringify({type:
|
|
33
|
+
`),e.end();return}let f="",g="",y=[],k=new z;for await(let c of o.track(u,m)){y.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(f+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(g+=c.delta);let x=ie(c);if(x&&k.add(x),c.type==="error"){V(e,502,JSON.stringify(c),"upstream_error");return}}let _=K(y),l=ve(_),I=l.length>0?l:ve({output:k.items()}),O=Q(p,I.length,f);if(O){V(e,502,X(m,O),"upstream_error");return}let N=I.map(({index:c,...x})=>x),P={role:"assistant",content:f||null},M=g||Xe(_);M&&(P.reasoning_content=M),N.length>0&&(P.tool_calls=N),H(e,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,message:P,finish_reason:N.length>0?"tool_calls":"stop"}],usage:ze(_)})}function Tt(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var ae=class extends Error{};function ge(t){return new ae(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ct(t){if(Array.isArray(t))return t.map(n=>{let e=n;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema}})}function Pt(t){if(t==null)return;let n=t.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:t.name};throw new ae(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function $t(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw ge(typeof t);let n="";for(let e of t){let o=String(e.type??"");if(o!=="text")throw ge(`tool_result > ${o}`);n+=String(e.text??"")}return n}function Nt(t){let{role:n,content:e}=t;if(typeof e=="string")return[{role:n,content:e}];if(e==null)return[];if(!Array.isArray(e))throw ge(typeof e);let o=[],s="",r=()=>{s&&(o.push({role:n,content:s}),s="")};for(let a of e){let d=String(a.type??"");if(d==="text")s+=String(a.text??"");else if(d==="tool_use")r(),o.push({type:"function_call",call_id:a.id,name:a.name,arguments:JSON.stringify(a.input??{})});else if(d==="tool_result")r(),o.push({type:"function_call_output",call_id:a.tool_use_id,output:$t(a.content)});else{if(d==="thinking"||d==="redacted_thinking")continue;throw ge(d)}}return r(),o}function xe(t){return re(t).map((n,e)=>{let o;try{o=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${e}`,name:n.name??"",input:o}})}async function Mt(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){B(e,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){B(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.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(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(c=>typeof c!="string"))){B(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let r=String(t.model??"urun"),a=`msg_${Math.random().toString(36).slice(2,14)}`,d=[],m;try{t.system&&d.push({role:"system",content:Tt(t.system)});for(let c of s)d.push(...Nt(c));m=Pt(t.tool_choice)}catch(c){if(c instanceof ae){B(e,400,"invalid_request_error",c.message);return}throw c}let p=Ie(t);o.model(p);let u=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await n.createResponse({model:t.model,input:d,stream:!0,tools:Ct(t.tools),tool_choice:m,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences})}catch(c){if(c instanceof F){Re(e,"anthropic",c);return}throw c}let g=(c,x)=>{e.destroyed||e.write(`event: ${c}
|
|
34
|
+
data: ${JSON.stringify({type:c,...x})}
|
|
35
35
|
|
|
36
|
-
`)};if(
|
|
37
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
36
|
+
`)};if(t.stream===!0){let c=o.track(f,p);Se(e),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:r,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,U="",C=0,L="none",D=()=>L,$=-1,v=-1,R=new z,j=[],q=()=>{L!=="none"&&(L="none",g("content_block_stop",{index:$}))},A=(w,T)=>{q(),L=w,$=C++,g("content_block_start",{index:$,content_block:T})};for await(let w of c){if(e.destroyed)break;j.push(w);let T=ie(w);if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")D()!=="thinking"&&A("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:w.delta}});else if(w.type==="response.output_text.delta"&&typeof w.delta=="string")D()!=="text"&&A("text",{type:"text",text:""}),x+=1,U+=w.delta,g("content_block_delta",{index:$,delta:{type:"text_delta",text:w.delta}});else if(T){let{call:G}=R.add(T);(D()!=="tool"||T.tool_index!==v)&&(v=T.tool_index,A("tool",{type:"tool_use",id:G.id??`call_${T.tool_index}`,name:G.name??"",input:{}})),T.delta&&g("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:T.delta}})}else if(w.type==="error"){g("error",{error:{type:"api_error",message:JSON.stringify(w)}}),e.end();return}}if(e.destroyed)return;let W=K(j),Z=re(W),ee=Q(u,R.size+Z.length,U);if(ee){g("error",{error:{type:"api_error",message:X(p,ee)}}),e.end();return}q();let h=[];if(R.size===0)try{h=xe(W)}catch(w){g("error",{error:{type:"api_error",message:String(w instanceof Error?w.message:w)}}),e.end();return}C===0&&h.length===0&&(A("text",{type:"text",text:""}),q()),h.forEach(w=>{let T=C++;g("content_block_start",{index:T,content_block:{...w,input:{}}}),g("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:JSON.stringify(w.input??{})}}),g("content_block_stop",{index:T})});let S=R.size>0||h.length>0,E=fe(W);g("message_delta",{delta:{stop_reason:S?"tool_use":"end_turn"},usage:E?{input_tokens:E.input_tokens,output_tokens:E.output_tokens}:{output_tokens:x}}),g("message_stop",{}),e.end();return}let y="",k="",_=[],l=new z;for await(let c of o.track(f,p)){_.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(y+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(k+=c.delta);let x=ie(c);if(x&&l.add(x),c.type==="error"){B(e,502,"api_error",JSON.stringify(c));return}if(e.destroyed)break}if(e.destroyed)return;let I=K(_),O;try{O=xe(I),O.length===0&&l.size>0&&(O=xe({output:l.items()}))}catch(c){B(e,502,"api_error",String(c instanceof Error?c.message:c));return}let N=Q(u,O.length,y);if(N){B(e,502,"api_error",X(p,N));return}let P=[],M=k||Xe(I);M&&P.push({type:"thinking",thinking:M}),(y||O.length===0)&&P.push({type:"text",text:y}),P.push(...O),H(e,200,{id:a,type:"message",role:"assistant",content:P,model:r,stop_reason:O.length>0?"tool_use":"end_turn",usage:fe(I)??{input_tokens:0,output_tokens:0}})}function Lt(t){let{clients:n,apiKey:e,identity:o,statusOf:s}=t,r=typeof n=="function"?n:()=>n,a=new WeakMap,d=p=>{let u=a.get(p);return u||(u=new be,a.set(p,u)),u},m=new Ae;return(p,u)=>{let f=new URL(p.url??"/","http://localhost"),g=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),y=(k,_,l,I)=>g?B(u,k,I,_):V(u,k,_,l);(async()=>{if(p.method==="GET"&&f.pathname==="/healthz"){H(u,200,{ok:!0});return}if(p.method==="GET"&&f.pathname==="/stats"){H(u,200,o?{identity:o,...m.snapshot()}:m.snapshot());return}if(e&&(p.headers.authorization??"")!==`Bearer ${e}`){y(401,"invalid local proxy api key","authentication_error","authentication_error");return}let k=await r(p);if(p.method==="GET"&&f.pathname==="/v1/models"){H(u,200,await k.listModels());return}if(p.method!=="POST"){y(404,`no route for ${p.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await kt(p)}catch(I){if(I instanceof pe){y(413,I.message,"request_too_large","request_too_large");return}y(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let l=Buffer.byteLength(JSON.stringify(_));if(f.pathname==="/v1/responses"){m.request("responses",l,l),await Ot(_,k,d(k),u,m);return}if(f.pathname==="/v1/chat/completions"){m.request("chat_completions",l,l),await Et(_,k,u,m);return}if(f.pathname==="/v1/messages"){m.request("messages",l,l),await Mt(_,k,u,m);return}if(f.pathname==="/v1/messages/count_tokens"){m.request("count_tokens",l,l),B(u,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}y(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(k=>{let _=String(k instanceof Error?k.message:k);if(!u.headersSent){let l=s?.(k)??null;if(l){y(l.status,_,l.openaiType,l.anthropicType);return}y(500,_,"proxy_error","api_error");return}u.destroyed||(g?u.write(`event: error
|
|
37
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:_}})}
|
|
38
38
|
|
|
39
|
-
`):
|
|
39
|
+
`):u.write(`data: ${JSON.stringify({error:{message:_,type:"upstream_error"}})}
|
|
40
40
|
|
|
41
|
-
`)),
|
|
41
|
+
`)),u.end()})}}function Qe(t){let{clients:n,apiKey:e}=t,o=(0,Ye.createServer)(Lt(t));return Ge(o,{clients:n,apiKey:e}),o}0&&(module.exports={GEMINI_LIVE_PATH,createOpenAIProxy});
|
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,149 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* WHAT a proxy serves — the `identity` block on `GET /stats`. Reuse of a
|
|
6
|
-
* running proxy is allowed iff every field matches the launching invocation
|
|
7
|
-
* EXACTLY: a partial match (same app, different fn; same everything, older
|
|
8
|
-
* proxy_version) silently routes the agent at the wrong backend, which is
|
|
9
|
-
* worse than any error.
|
|
10
|
-
*/
|
|
11
|
-
interface ProxyIdentity {
|
|
12
|
-
app: string;
|
|
13
|
-
org: string;
|
|
14
|
-
fn: string;
|
|
15
|
-
/**
|
|
16
|
-
* The control-plane URL the proxy's backhaul session opens against
|
|
17
|
-
* (URUN_BASE_URL verbatim — same org/app/fn on staging vs prod are
|
|
18
|
-
* DIFFERENT backends; review finding, #285). Compared exactly: a cosmetic
|
|
19
|
-
* difference (trailing slash) merely refuses reuse and spawns an ephemeral
|
|
20
|
-
* proxy — the safe direction.
|
|
21
|
-
*/
|
|
22
|
-
base_url: string;
|
|
23
|
-
proxy_version: string;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* The local OpenAI-compatible proxy — `npx @urun-sh/openai proxy`.
|
|
28
|
-
*
|
|
29
|
-
* A loopback HTTP server speaking the OpenAI REST surface (`/v1/models`,
|
|
30
|
-
* `/v1/responses`, `/v1/chat/completions`, SSE streaming included), so any
|
|
31
|
-
* OpenAI-env-var tool — coding agents first — integrates with uRun with ZERO
|
|
32
|
-
* code changes: point `OPENAI_BASE_URL` at it and keep making plain, local,
|
|
33
|
-
* "inefficient" HTTP requests. The proxy backhauls each request over the uRun
|
|
34
|
-
* session transport (the `@urun-sh/openai` Responses client → session doc
|
|
35
|
-
* lanes + streams — no public OpenAI-style HTTP leaves the machine), which is
|
|
36
|
-
* also where the delta-sync chat-state doc lane (urun-python
|
|
37
|
-
* `urun/serve/chat_state.py`) plugs in as the transport evolves.
|
|
38
|
-
*
|
|
39
|
-
* Local-trust model: binds 127.0.0.1 by default; `apiKey` (when set) must
|
|
40
|
-
* match the agent's `Authorization: Bearer` — otherwise any local bearer is
|
|
41
|
-
* accepted (the key the agent sends is NEVER forwarded upstream; uRun auth is
|
|
42
|
-
* the session's own).
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
/** The request envelope every Responses-shaped upstream call carries. */
|
|
46
|
-
interface ResponsesCreateParams {
|
|
47
|
-
model?: string;
|
|
48
|
-
input: unknown;
|
|
49
|
-
stream?: boolean;
|
|
50
|
-
tools?: unknown;
|
|
51
|
-
tool_choice?: unknown;
|
|
52
|
-
temperature?: number;
|
|
53
|
-
max_output_tokens?: number;
|
|
54
|
-
top_p?: number;
|
|
55
|
-
stop?: string[];
|
|
56
|
-
}
|
|
57
|
-
/** How one pinned session ended (the native phase machinery's terminal step). */
|
|
58
|
-
interface SessionEndInfo {
|
|
59
|
-
/**
|
|
60
|
-
* Milliseconds until the session's native deadline (`endsAt`), or null when
|
|
61
|
-
* the app declared no maximum session length. NOTE (missing primitive,
|
|
62
|
-
* called out in the PR): core exposes no PRE-expiry notice event — this
|
|
63
|
-
* callback fires AT terminal loss, so timeLeftMs is ~0 on expiry.
|
|
64
|
-
*/
|
|
65
|
-
timeLeftMs: number | null;
|
|
66
|
-
/** The terminal reason (expired / ended / error), for the loud close. */
|
|
67
|
-
reason: string;
|
|
68
|
-
}
|
|
69
|
-
/** The upstream calls the proxy makes — injectable (tests; alt transports). */
|
|
70
|
-
interface ProxyClients {
|
|
71
|
-
/** `UrunResponses(session).responses.create` — an async iterable of Responses stream events. */
|
|
72
|
-
createResponse(params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
|
|
73
|
-
/** `listModels(...)` result (an OpenAI model list object). */
|
|
74
|
-
listModels(): Promise<unknown>;
|
|
75
|
-
/**
|
|
76
|
-
* Open (or reuse) the NATIVE audio lanes on the pooled session `model` routes
|
|
77
|
-
* to — the same first-party machinery as RealtimeClient.enableAudio
|
|
78
|
-
* (transport/media.ts `enableSessionAudio`: AudioBridge over the session's
|
|
79
|
-
* `rt-audio-in`/`rt-audio-out` stream lanes at 24 kHz). One lane per pooled
|
|
80
|
-
* session; repeat calls return the same lane. Optional at the seam because
|
|
81
|
-
* text-only embeddings exist — but a surface that RECEIVES audio while the
|
|
82
|
-
* embedder wired no `openAudio` must fail LOUD, never drop chunks.
|
|
83
|
-
*/
|
|
84
|
-
openAudio?(model: string | undefined): Promise<ProxyAudioLane>;
|
|
85
|
-
/**
|
|
86
|
-
* Open (or reuse) the NATIVE video FRAME lane on the pooled session `model`
|
|
87
|
-
* routes to (transport/media.ts `enableSessionVideo`: discrete JPEG frames →
|
|
88
|
-
* `stream('rt-video-in').emit`, the §5 named-DATA image-bytes path — NOT the
|
|
89
|
-
* RTP media plane, which requires an already-H.264-encoded track). One lane
|
|
90
|
-
* per pooled session; repeat calls return the same lane. Optional at the seam
|
|
91
|
-
* because text-only embeddings exist — but a surface that RECEIVES video
|
|
92
|
-
* frames while the embedder wired no `openVideo` must fail LOUD, never drop
|
|
93
|
-
* frames.
|
|
94
|
-
*/
|
|
95
|
-
openVideo?(model: string | undefined): Promise<ProxyVideoLane>;
|
|
96
|
-
/**
|
|
97
|
-
* SESSION-IDENTITY SEAM (ModelRouter.handleFor): the opaque stable handle
|
|
98
|
-
* for the pooled session currently serving `model`'s turns. Derived from
|
|
99
|
-
* native identity (app slug + uRun session id) — the same identity the
|
|
100
|
-
* serve-side session-affinity tag rides (urun-python#1556/#1582).
|
|
101
|
-
*/
|
|
102
|
-
sessionHandle(model: string | undefined): Promise<string>;
|
|
103
|
-
/**
|
|
104
|
-
* createResponse PINNED to the exact session a handle names
|
|
105
|
-
* (ModelRouter.sessionForHandle). Throws SessionGoneError LOUDLY when that
|
|
106
|
-
* session is gone or was replaced — never silently opens a fresh session
|
|
107
|
-
* while claiming resume. Deliberately NO re-home on this path: re-homing
|
|
108
|
-
* would swap the pinned session out from under the caller.
|
|
109
|
-
*/
|
|
110
|
-
createResponseOn(handle: string, params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
|
|
111
|
-
/**
|
|
112
|
-
* Subscribe to the pinned session's terminal end via core's NATIVE phase
|
|
113
|
-
* machinery (Session.onPhase → terminal 'expired'/'ended'/'error'). Fires
|
|
114
|
-
* `cb` once. Throws SessionGoneError if the handle's session is already
|
|
115
|
-
* gone — which doubles as the loud reattach check at resume time. Returns
|
|
116
|
-
* the unsubscribe.
|
|
117
|
-
*/
|
|
118
|
-
onSessionEnd(handle: string, cb: (end: SessionEndInfo) => void): Promise<() => void>;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* The audio lane handle `openAudio` returns — structurally the transport
|
|
122
|
-
* AudioBridge (media.ts): base64 PCM16 @24 kHz mono in both directions.
|
|
123
|
-
*/
|
|
124
|
-
type ProxyAudioLane = Pick<AudioBridge, 'appendInputAudio' | 'onOutputAudio'>;
|
|
125
|
-
/**
|
|
126
|
-
* The video frame-lane handle `openVideo` returns — structurally the transport
|
|
127
|
-
* VideoFrameLane (media.ts): one raw encoded JPEG frame per call, input-only
|
|
128
|
-
* (Live-style protocols have no video OUT modality).
|
|
129
|
-
*/
|
|
130
|
-
type ProxyVideoLane = Pick<VideoFrameLane, 'sendInputFrame'>;
|
|
131
|
-
interface OpenAIProxyOptions {
|
|
132
|
-
clients: ProxyClients;
|
|
133
|
-
/** Optional bearer the local agent must present (never forwarded upstream). */
|
|
134
|
-
apiKey?: string;
|
|
135
|
-
/**
|
|
136
|
-
* WHAT this proxy serves (app/org/fn/base_url + proxy_version), surfaced as
|
|
137
|
-
* the `identity` block on `GET /stats` so a second `urun compat` invocation
|
|
138
|
-
* can reuse this proxy iff the identity matches its own exactly. Only the
|
|
139
|
-
* standalone `urun compat proxy` command sets it — a launch-mode proxy is
|
|
140
|
-
* child-owned (it dies with its child) and an embedder that omits it is
|
|
141
|
-
* simply never reused.
|
|
142
|
-
*/
|
|
143
|
-
identity?: ProxyIdentity;
|
|
144
|
-
}
|
|
145
|
-
/** Build (not listen) the proxy server — the caller owns listen/close. */
|
|
146
|
-
declare function createOpenAIProxy(options: OpenAIProxyOptions): Server;
|
|
1
|
+
export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, c as createOpenAIProxy } from '../server-DiQUIDDg.cjs';
|
|
2
|
+
import 'node:http';
|
|
3
|
+
import '../media-DCHTX3Ez.cjs';
|
|
147
4
|
|
|
148
5
|
/**
|
|
149
6
|
* Gemini Live (BidiGenerateContent) ⇄ uRun Responses translation — PURE
|
|
@@ -172,4 +29,4 @@ declare function createOpenAIProxy(options: OpenAIProxyOptions): Server;
|
|
|
172
29
|
/** The Live WS endpoint path (v1beta), verbatim from the Google reference. */
|
|
173
30
|
declare const GEMINI_LIVE_PATH = "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
|
|
174
31
|
|
|
175
|
-
export { GEMINI_LIVE_PATH
|
|
32
|
+
export { GEMINI_LIVE_PATH };
|