@urun-sh/openai 0.2.58 → 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/standalone.cjs +44 -44
- package/dist/proxy/cli.cjs +28 -23
- package/dist/proxy/cli.js +17 -17
- package/dist/proxy/index.cjs +13 -8
- package/dist/proxy/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,36 +1,41 @@
|
|
|
1
|
-
import{b as V,c as me}from"./chunk-VXTNG2TP.js";var Ce="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",We=1007,Ee=1008,H=1011,ge=1008,
|
|
2
|
-
`)}var Xe={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Qe={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ze=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Se=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function et(n){let t=x(n);if(!t)throw new r("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new r(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 r("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(e??{}))if(s!=="disabled")throw new r(`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 r("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(!Se.includes(t.activityHandling))throw new r(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${Se.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var tt=["temperature","maxOutputTokens","responseModalities"];function Pe(n){for(let[d,g]of Object.entries(Qe))if(n[d]!==void 0)throw new r(g);for(let d of Object.keys(n))if(!Ze.includes(d))throw new r(`unsupported setup field "${d}"`);if(typeof n.model!="string"||n.model.length===0)throw new r('setup.model is required (format "models/{model}")');let t=n.model.replace(/^models\//,""),e,o,s=!1,i=x(n.generationConfig);if(n.generationConfig!==void 0&&!i)throw new r("setup.generationConfig must be an object");if(i){for(let d of Object.keys(i))if(!tt.includes(d))throw new r(`unsupported generationConfig field "${d}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new r("generationConfig.temperature must be a number");e=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new r("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let d=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let g of d){let p=String(g).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new r(`responseModalities ${JSON.stringify(g)} 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:Ne(n.systemInstruction,"setup.systemInstruction")});let u;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new r("setup.tools must be an array");u=[];for(let d of n.tools){let g=x(d);if(!g)throw new r("setup.tools entries must be objects");for(let p of Object.keys(g))if(p!=="functionDeclarations")throw new r(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new r("tool.functionDeclarations must be an array");for(let p of g.functionDeclarations){let y=x(p);if(!y||typeof y.name!="string")throw new r("functionDeclarations entries require a string name");u.push({type:"function",name:y.name,description:y.description,parameters:y.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 r("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(d))if(g!=="handle")throw new r(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(d.handle!==void 0&&(typeof d.handle!="string"||d.handle.length===0))throw new r("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?Xe:et(n.realtimeInputConfig);return{model:t,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:c,sessionResumption:m}}function Me(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function $e(n){let t=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function Le(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new r(`unsupported clientContent field "${o}"`);let t=n.turns===void 0?[]:n.turns;if(!Array.isArray(t))throw new r("clientContent.turns must be an array");let e=[];for(let o of t){let s=x(o);if(!s)throw new r("clientContent.turns entries must be Content objects");let i=s.role===void 0?"user":String(s.role).toLowerCase();if(i!=="user"&&i!=="model")throw new r(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);e.push({role:i==="model"?"assistant":"user",content:Ne(s,"clientContent.turns")})}return{items:e,turnComplete:n.turnComplete===!0}}var ue=16e3,Ue=24e3,nt=`audio/pcm;rate=${Ue}`,je=Buffer.alloc(960).toString("base64");function ot(n,t,e){if(t===e)return n;let o=Math.floor(n.length*e/t),s=new Int16Array(o),i=t/e,a=n.length-1;for(let u=0;u<o;u++){let m=u*i,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 st(n){let t=x(n);if(!t)throw new r("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new r(`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 r("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 r("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(e)}function it(n){let t=x(n);if(!t)throw new r("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new r(`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])!==ue)throw new r(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ue} Hz (audio/pcm;rate=${ue})`);if(typeof t.data!="string"||t.data.length===0)throw new r("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 r(`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 i=ot(s,ue,Ue);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Be(n){if(n.mediaChunks!==void 0)throw new r('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 r("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=n.activityStart!==void 0?"activityStart":"activityEnd",i=x(n[s]);if(!i||Object.keys(i).length!==0)throw new r(`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 r(`unsupported realtimeInput field "${o}"`);let e=t.filter(o=>n[o]!==void 0);if(e.length!==1)throw new r(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${e.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:it(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:st(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new r("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new r("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function qe(n){for(let t of Object.keys(n))if(t!=="functionResponses")throw new r(`unsupported toolResponse field "${t}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new r("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 r("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 De(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function Je(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:nt,data:n}}]}}}}function He(n){let t=x(n)??{},e=Array.isArray(t.output)?t.output:[],o=[],s=[],i=typeof t.output_text=="string"?t.output_text:"";if(!i)for(let c of e){let d=x(c);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let g of d.content){let p=x(g);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&s.push({role:"assistant",content:i});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 r(`upstream function_call item is missing call_id/name: ${JSON.stringify(c)}`,H);let g=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(g)}catch{throw new r(`upstream function_call arguments are not valid JSON: ${g}`,H)}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:g})}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}}import{createServer as ct}from"http";import{randomUUID as rt}from"crypto";import{WebSocketServer as at}from"ws";var ut=256,ye=class{snapshots=new Map;store(t,e){for(this.snapshots.set(t,e);this.snapshots.size>ut;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},ne=n=>n.slice(0,120),he=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 V){this.ws.close(Ee,ne(t.message));return}if(t instanceof me){this.ws.close(ge,ne(t.message));return}if(t instanceof r){this.ws.close(t.closeCode,ne(t.message));return}this.ws.close(H,ne(String(t instanceof Error?t.message:t)))}onMessage(t){try{let e=Te(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 r(`"${e.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(e.kind==="clientContent"){let{items:s,turnComplete:i}=Le(e.clientContent);this.transcript.push(...s),i&&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:je);return}this.transcript.push(...qe(e.toolResponse)),this.enqueue(()=>this.runTurn())}catch(e){this.fail(e)}}async handleSetup(t){if(this.config)throw new r("setup may only be sent once, as the first client message");let e=Pe(t),o=e.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new r("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",ge);if(s.model!==e.model)throw new r(`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 r("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,i=>this.enqueue(()=>this.handleUpstreamEnd(i)))}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 r("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openAudio;if(!e)throw new r("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",H);return this.audio=(async()=>{let o=await e.call(this.clients,t.model);return this.detachAudio=o.onOutputAudio(s=>this.send(Je(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 r("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openVideo;if(!e)throw new r("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",H);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 r(`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 r("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 r("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=rt();this.registry.store(o,{model:t.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Me(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($e(t.timeLeftMs)),this.ws.close(H,ne(`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,i=!1;for await(let m of o){if(e.interrupted)break;let c=m;if(c.type==="error")throw new r(`upstream error: ${JSON.stringify(c)}`,H);if(c.type==="response.completed"){s=c.response,i=!0;continue}let d=De(c);d&&this.send(d)}if(e.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new r("upstream produced no response.completed event",H);let{messages:a,assistantItems:u}=He(s);this.transcript.push(...u);for(let m of a)this.send(m);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},lt=(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 Fe(n,t){let e=new at({noServer:!0}),o=new ye;n.on("upgrade",(s,i,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==Ce){i.write(`HTTP/1.1 404 Not Found\r
|
|
1
|
+
import{b as V,c as me}from"./chunk-VXTNG2TP.js";var Ce="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",We=1007,Ee=1008,H=1011,ge=1008,i=class extends Error{constructor(e,o=We){super(e);this.closeCode=o}closeCode},x=n=>typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null,ae=["setup","clientContent","realtimeInput","toolResponse"];function Te(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=ae.filter(u=>e[u]!==void 0),s=Object.keys(e).filter(u=>!ae.includes(u));if(s.length>0)throw new i(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${ae.join(", ")}`);if(o.length!==1)throw new i(`client message must contain exactly one of ${ae.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 Ne(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 Xe={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Qe={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ze=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Se=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function et(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(!Se.includes(t.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${Se.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var tt=["temperature","maxOutputTokens","responseModalities"];function Pe(n){for(let[c,g]of Object.entries(Qe))if(n[c]!==void 0)throw new i(g);for(let c of Object.keys(n))if(!Ze.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(!tt.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 g of c){let p=String(g).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new i(`responseModalities ${JSON.stringify(g)} 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:Ne(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 g=x(c);if(!g)throw new i("setup.tools entries must be objects");for(let p of Object.keys(g))if(p!=="functionDeclarations")throw new i(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let p of g.functionDeclarations){let y=x(p);if(!y||typeof y.name!="string")throw new i("functionDeclarations entries require a string name");u.push({type:"function",name:y.name,description:y.description,parameters:y.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 g of Object.keys(c))if(g!=="handle")throw new i(`unsupported sessionResumption field "${g}" \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?Xe:et(n.realtimeInputConfig);return{model:t,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:d,sessionResumption:f}}function Me(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function $e(n){let t=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function Le(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:Ne(s,"clientContent.turns")})}return{items:e,turnComplete:n.turnComplete===!0}}var ue=16e3,Ue=24e3,nt=`audio/pcm;rate=${Ue}`,je=Buffer.alloc(960).toString("base64");function ot(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 st(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 rt(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])!==ue)throw new i(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ue} Hz (audio/pcm;rate=${ue})`);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=ot(s,ue,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:rt(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:st(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 qe(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 De(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function Je(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:nt,data:n}}]}}}}function He(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 g of c.content){let p=x(g);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)}`,H);let g=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(g)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${g}`,H)}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:g})}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}}import{createServer as ct}from"http";import{randomUUID as it}from"crypto";import{WebSocketServer as at}from"ws";var ut=256,ye=class{snapshots=new Map;store(t,e){for(this.snapshots.set(t,e);this.snapshots.size>ut;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},ne=n=>n.slice(0,120),he=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 V){this.ws.close(Ee,ne(t.message));return}if(t instanceof me){this.ws.close(ge,ne(t.message));return}if(t instanceof i){this.ws.close(t.closeCode,ne(t.message));return}this.ws.close(H,ne(String(t instanceof Error?t.message:t)))}onMessage(t){try{let e=Te(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}=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:je);return}this.transcript.push(...qe(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=Pe(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",ge);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)",H);return this.audio=(async()=>{let o=await e.call(this.clients,t.model);return this.detachAudio=o.onOutputAudio(s=>this.send(Je(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)",H);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=it();this.registry.store(o,{model:t.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Me(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($e(t.timeLeftMs)),this.ws.close(H,ne(`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)}`,H);if(d.type==="response.completed"){s=d.response,r=!0;continue}let c=De(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",H);let{messages:a,assistantItems:u}=He(s);this.transcript.push(...u);for(let f of a)this.send(f);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},lt=(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 Fe(n,t){let e=new at({noServer:!0}),o=new ye;n.on("upgrade",(s,r,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==Ce){r.write(`HTTP/1.1 404 Not Found\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
no WS route for ${u.pathname}`),
|
|
5
|
+
no WS route for ${u.pathname}`),r.destroy();return}if(t.apiKey&<(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`),
|
|
8
|
+
invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,f=>{new he(f,t.clients,o)})})}var ke=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>=dt?"(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 xe(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function q(n,t,e){n.writeHead(t,{"content-type":"application/json"}),n.end(JSON.stringify(e))}function F(n,t,e,o="invalid_request_error"){q(n,t,{error:{message:e,type:o}})}function B(n,t,e,o){q(n,t,{type:"error",error:{type:e,message:o}})}function Re(n,t,e){if(t==="anthropic"){q(n,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}q(n,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var dt=256,pt=128;function Ae(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,pt)}var Ge=64*1024*1024,le=class extends Error{};async function ft(n){let t=[],e=0;for await(let s of n){if(e+=s.length,e>Ge)throw new le(`request body exceeds ${Ge} bytes`);t.push(s)}let o=Buffer.concat(t).toString("utf8");return o?JSON.parse(o):{}}function W(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 mt=256;function gt(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 ve=class{conversations=new Map;thread(t,e){let o=gt(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<=mt)break;this.conversations.delete(s)}}};function oe(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 ce(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 Ve(n){let t=ce(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 Ke(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 se(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}))}},yt=["<tool_call>","<function="];function ht(n){return yt.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 ht(e)}function _t(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 de=class extends Error{};function wt(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 de(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):t}function kt(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:wt(e.role,e.content)})}return t}function _e(n){return oe(n).map((t,e)=>({index:e,id:t.call_id??t.id??`call_${e}`,type:"function",function:{name:t.name??"",arguments:t.arguments??"{}"}}))}function ze(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 vt(n,t,e,o,s){let r=n.stream===!0,a;try{a=e.thread(n.previous_response_id,n.input)}catch(m){F(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=Ae(n);s.model(d);let c=Array.isArray(n.tools)&&n.tools.length>0,g;try{g=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 V){Re(o,"openai",m);return}throw m}let p=[];if(r){xe(o);let m=h=>{o.write(`event: ${String(h.type??"message")}
|
|
9
9
|
data: ${JSON.stringify(h)}
|
|
10
10
|
|
|
11
|
-
`)},P=h=>h.response&&typeof h.response=="object"?{...h,response:{...h.response,id:u}}:h,b=`item_${u.slice(5)}`,M=`rs_${u.slice(5)}`,E=!1,$=!1,l=0,k=()=>{E||(E=!0,
|
|
11
|
+
`)},P=h=>h.response&&typeof h.response=="object"?{...h,response:{...h.response,id:u}}:h,b=`item_${u.slice(5)}`,M=`rs_${u.slice(5)}`,E=!1,$=!1,l=0,k=()=>{E||(E=!0,m({type:"response.created",response:{id:u,object:"response",status:"in_progress"}}))},U=!1,C=0,L="",j=()=>{U&&(U=!1,m({type:"response.reasoning_text.done",item_id:M,output_index:C,content_index:0,text:L}),m({type:"response.output_item.done",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:L}],status:"completed"}}))},T=!1,w=0,A="",D=h=>{T&&(T=!1,m({type:"response.output_text.done",item_id:b,output_index:w,content_index:0,text:A}),m({type:"response.content_part.done",item_id:b,output_index:w,content_index:0,part:{type:"output_text",text:A}}),m({type:"response.output_item.done",output_index:w,item:{id:b,type:"message",role:"assistant",status:h,content:[{type:"output_text",text:A}]}}))},J=new K,v=null,Y=-1,Z=h=>{if(!v)return;let R=v;v=null,m({type:"response.function_call_arguments.done",item_id:R.fcId,output_index:R.outputIndex,arguments:R.args}),m({type:"response.output_item.done",output_index:R.outputIndex,item:{id:R.fcId,type:"function_call",call_id:R.callId??R.fcId,name:R.name??"",arguments:R.args,status:h}})},ee=!1;for await(let h of s.track(g,d)){p.push(h);let R=String(h.type??"");if(R==="response.created"||R==="response.in_progress"){E=!0,m(P(h));continue}if(R==="response.output_item.added"){$=!0,m(P(h));continue}if(R==="response.reasoning_text.delta"&&!$){k(),U||(U=!0,C=l++,m({type:"response.output_item.added",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[],status:"in_progress"}})),L+=String(h.delta??""),m({type:"response.reasoning_text.delta",item_id:M,output_index:C,content_index:0,delta:h.delta});continue}if(R==="response.output_text.delta"&&!$){k(),j(),T||(T=!0,w=l++,m({type:"response.output_item.added",output_index:w,item:{id:b,type:"message",role:"assistant",status:"in_progress",content:[]}}),m({type:"response.content_part.added",item_id:b,output_index:w,content_index:0,part:{type:"output_text",text:""}})),A+=String(h.delta??""),m({type:R,item_id:b,output_index:w,content_index:0,delta:h.delta});continue}let S=$?null:se(h);if(S){if(k(),j(),D("completed"),J.add(S),S.tool_index!==Y){Z("completed"),Y=S.tool_index;let _=l++;v={fcId:`fc_${u.slice(5)}_${S.tool_index}`,outputIndex:_,callId:S.call_id,name:S.name,args:""},m({type:"response.output_item.added",output_index:_,item:{id:v.fcId,type:"function_call",call_id:v.callId??v.fcId,name:v.name??"",arguments:"",status:"in_progress"}})}v&&(S.call_id&&(v.callId=S.call_id),S.name&&(v.name=S.name),v.args+=S.delta,m({type:"response.function_call_arguments.delta",item_id:v.fcId,output_index:v.outputIndex,delta:S.delta}));continue}if(R==="response.completed"&&!$){let _=oe(h.response),I=Q(c,J.size+_.length,A);if(I){ee=!0,m({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:X(d,I)}});break}j(),D("completed"),Z("completed"),J.size===0&&_.forEach(G=>{let te=l++,ie=G.id??G.call_id??`fc_${te}`,fe=G.arguments??"",be={id:ie,type:"function_call",call_id:G.call_id??ie,name:G.name??""};m({type:"response.output_item.added",output_index:te,item:{...be,arguments:"",status:"in_progress"}}),m({type:"response.function_call_arguments.delta",item_id:ie,output_index:te,delta:fe}),m({type:"response.function_call_arguments.done",item_id:ie,output_index:te,arguments:fe}),m({type:"response.output_item.done",output_index:te,item:{...be,arguments:fe,status:"completed"}})}),m(P(h));continue}m(P(h))}j(),D("incomplete"),Z("incomplete"),f&&!ee&&e.remember(u,a,ze(p,z(p))),o.write(`data: [DONE]
|
|
12
12
|
|
|
13
|
-
`),o.end();return}let y=null;for await(let
|
|
13
|
+
`),o.end();return}let y=null;for await(let m of s.track(g,d)){if(p.push(m),m.type==="error"){F(o,502,JSON.stringify(m),"upstream_error");return}m.type==="response.completed"&&(y=m.response)}if(y==null){F(o,502,"upstream produced no response.completed event","upstream_error");return}let O=ze(p,y),N=Q(c,oe(y).length,O);if(N){F(o,502,X(d,N),"upstream_error");return}f&&e.remember(u,a,O),q(o,200,{...y,id:u})}async function xt(n,t,e,o){let s=n.messages;if(!Array.isArray(s)){F(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=kt(s)}catch(l){if(l instanceof de){F(e,400,l.message);return}throw l}let f=Ae(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:_t(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 V){Re(e,"openai",l);return}throw l}if(n.stream===!0){xe(e);let l=[],k=new K,U="";e.write(`data: ${JSON.stringify(W(a,r,{role:"assistant"},null))}
|
|
14
14
|
|
|
15
|
-
`);for await(let w of o.track(
|
|
15
|
+
`);for await(let w of o.track(c,f)){l.push(w);let A=se(w);if(w.type==="response.output_text.delta"&&typeof w.delta=="string")U+=w.delta,e.write(`data: ${JSON.stringify(W(a,r,{content:w.delta},null))}
|
|
16
16
|
|
|
17
|
-
`);else if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")e.write(`data: ${JSON.stringify(W(a,
|
|
17
|
+
`);else if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")e.write(`data: ${JSON.stringify(W(a,r,{reasoning_content:w.delta},null))}
|
|
18
18
|
|
|
19
|
-
`);else if(A){let{call:D,isNew:J}=k.add(A),v=J?{index:A.tool_index,id:D.id??`call_${A.tool_index}`,type:"function",function:{name:D.name??"",arguments:A.delta}}:{index:A.tool_index,function:{arguments:A.delta}};e.write(`data: ${JSON.stringify(W(a,
|
|
19
|
+
`);else if(A){let{call:D,isNew:J}=k.add(A),v=J?{index:A.tool_index,id:D.id??`call_${A.tool_index}`,type:"function",function:{name:D.name??"",arguments:A.delta}}:{index:A.tool_index,function:{arguments:A.delta}};e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:[v]},null))}
|
|
20
20
|
|
|
21
21
|
`)}else if(w.type==="error"){e.write(`data: ${JSON.stringify({error:w})}
|
|
22
22
|
|
|
23
|
-
`),e.end();return}}let C=_e(z(l)),L=Q(
|
|
23
|
+
`),e.end();return}}let C=_e(z(l)),L=Q(d,k.size+C.length,U);if(L){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:X(f,L)}})}
|
|
24
24
|
|
|
25
|
-
`),e.end();return}k.size===0&&C.length>0&&e.write(`data: ${JSON.stringify(W(a,
|
|
25
|
+
`),e.end();return}k.size===0&&C.length>0&&e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:C},null))}
|
|
26
26
|
|
|
27
|
-
`);let j=k.size>0||C.length>0;e.write(`data: ${JSON.stringify(W(a,
|
|
27
|
+
`);let j=k.size>0||C.length>0;e.write(`data: ${JSON.stringify(W(a,r,{},j?"tool_calls":"stop"))}
|
|
28
28
|
|
|
29
|
-
`),ce(z(l))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:
|
|
29
|
+
`),ce(z(l))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[],usage:Ve(z(l))})}
|
|
30
30
|
|
|
31
31
|
`),e.write(`data: [DONE]
|
|
32
32
|
|
|
33
|
-
`),e.end();return}let g="",p="",y=[],O=new K;for await(let l of o.track(
|
|
33
|
+
`),e.end();return}let g="",p="",y=[],O=new K;for await(let l of o.track(c,f)){y.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"&&(p+=l.delta);let k=se(l);if(k&&O.add(k),l.type==="error"){F(e,502,JSON.stringify(l),"upstream_error");return}}let N=z(y),m=_e(N),P=m.length>0?m:_e({output:O.items()}),b=Q(d,P.length,g);if(b){F(e,502,X(f,b),"upstream_error");return}let M=P.map(({index:l,...k})=>k),E={role:"assistant",content:g||null},$=p||Ke(N);$&&(E.reasoning_content=$),M.length>0&&(E.tool_calls=M),q(e,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,message:E,finish_reason:M.length>0?"tool_calls":"stop"}],usage:Ve(N)})}function Rt(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(t=>t.type==="text").map(t=>String(t.text??"")).join(""):""}var re=class extends Error{};function pe(n){return new re(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function At(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 bt(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 re(`unsupported anthropic tool_choice type ${JSON.stringify(String(t))} \u2014 the proxy maps auto, none, any and tool`)}function St(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw pe(typeof n);let t="";for(let e of n){let o=String(e.type??"");if(o!=="text")throw pe(`tool_result > ${o}`);t+=String(e.text??"")}return t}function It(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 pe(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:St(a.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw pe(u)}}return r(),o}function we(n){return oe(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 Ot(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:Rt(n.system)});for(let l of s)u.push(...It(l));f=bt(n.tool_choice)}catch(l){if(l instanceof re){B(e,400,"invalid_request_error",l.message);return}throw l}let d=Ae(n);o.model(d);let c=Array.isArray(n.tools)&&n.tools.length>0,g;try{g=await t.createResponse({model:n.model,input:u,stream:!0,tools:At(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 V){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(g,
|
|
36
|
+
`)};if(n.stream===!0){let l=o.track(g,d);xe(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="",C=0,L="none",j=()=>L,T=-1,w=-1,A=new K,D=[],J=()=>{L!=="none"&&(L="none",p("content_block_stop",{index:T}))},v=(_,I)=>{J(),L=_,T=C++,p("content_block_start",{index:T,content_block:I})};for await(let _ of l){if(e.destroyed)break;D.push(_);let I=se(_);if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")j()!=="thinking"&&v("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:T,delta:{type:"thinking_delta",thinking:_.delta}});else if(_.type==="response.output_text.delta"&&typeof _.delta=="string")j()!=="text"&&v("text",{type:"text",text:""}),k+=1,U+=_.delta,p("content_block_delta",{index:T,delta:{type:"text_delta",text:_.delta}});else if(I){let{call:G}=A.add(I);(j()!=="tool"||I.tool_index!==w)&&(w=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:T,delta:{type:"input_json_delta",partial_json:I.delta}})}else if(_.type==="error"){p("error",{error:{type:"api_error",message:JSON.stringify(_)}}),e.end();return}}if(e.destroyed)return;let Y=z(D),Z=oe(Y),ee=Q(c,A.size+Z.length,U);if(ee){p("error",{error:{type:"api_error",message:X(d,ee)}}),e.end();return}J();let h=[];if(A.size===0)try{h=we(Y)}catch(_){p("error",{error:{type:"api_error",message:String(_ instanceof Error?_.message:_)}}),e.end();return}C===0&&h.length===0&&(v("text",{type:"text",text:""}),J()),h.forEach(_=>{let I=C++;p("content_block_start",{index:I,content_block:{..._,input:{}}}),p("content_block_delta",{index:I,delta:{type:"input_json_delta",partial_json:JSON.stringify(_.input??{})}}),p("content_block_stop",{index:I})});let R=A.size>0||h.length>0,S=ce(Y);p("message_delta",{delta:{stop_reason:R?"tool_use":"end_turn"},usage:S?{input_tokens:S.input_tokens,output_tokens:S.output_tokens}:{output_tokens:k}}),p("message_stop",{}),e.end();return}let y="",O="",N=[],m=new K;for await(let l of o.track(g,d)){N.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(y+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(O+=l.delta);let k=se(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 P=z(N),b;try{b=we(P),b.length===0&&m.size>0&&(b=we({output:m.items()}))}catch(l){B(e,502,"api_error",String(l instanceof Error?l.message:l));return}let M=Q(c,b.length,y);if(M){B(e,502,"api_error",X(d,M));return}let E=[],$=O||Ke(P);$&&E.push({type:"thinking",thinking:$}),(y||b.length===0)&&E.push({type:"text",text:y}),E.push(...b),q(e,200,{id:a,type:"message",role:"assistant",content:E,model:r,stop_reason:b.length>0?"tool_use":"end_turn",usage:ce(P)??{input_tokens:0,output_tokens:0}})}function Dt(n){let{clients:t,apiKey:e,identity:o}=n,s=new ve,r=new ke,a=ct((u,f)=>{let d=new URL(u.url??"/","http://localhost"),c=d.pathname==="/v1/messages"||d.pathname.startsWith("/v1/messages/"),g=(p,y,O,N)=>c?B(f,p,N,y):F(f,p,y,O);(async()=>{if(u.method==="GET"&&d.pathname==="/healthz"){q(f,200,{ok:!0});return}if(u.method==="GET"&&d.pathname==="/stats"){q(f,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(e&&(u.headers.authorization??"")!==`Bearer ${e}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}if(u.method==="GET"&&d.pathname==="/v1/models"){q(f,200,await t.listModels());return}if(u.method!=="POST"){g(404,`no route for ${u.method} ${d.pathname}`,"invalid_request_error","not_found_error");return}let p;try{p=await ft(u)}catch(O){if(O instanceof le){g(413,O.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let y=Buffer.byteLength(JSON.stringify(p));if(d.pathname==="/v1/responses"){r.request("responses",y,y),await vt(p,t,s,f,r);return}if(d.pathname==="/v1/chat/completions"){r.request("chat_completions",y,y),await xt(p,t,f,r);return}if(d.pathname==="/v1/messages"){r.request("messages",y,y),await Ot(p,t,f,r);return}if(d.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",y,y),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}g(404,`no route for POST ${d.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let y=String(p instanceof Error?p.message:p);if(!f.headersSent){g(500,y,"proxy_error","api_error");return}f.destroyed||(c?f.write(`event: error
|
|
37
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:y}})}
|
|
38
|
+
|
|
39
|
+
`):f.write(`data: ${JSON.stringify({error:{message:y,type:"upstream_error"}})}
|
|
40
|
+
|
|
41
|
+
`)),f.end()})});return Fe(a,{clients:t,apiKey:e}),a}export{Ce as a,Dt as b};
|