@urun-sh/openai 0.2.60 → 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.
@@ -1,60 +1,60 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var mn=Object.create;var ge=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var yn=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var _n=(e,n)=>{for(var t in n)ge(e,t,{get:n[t],enumerable:!0})},et=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of hn(n))!wn.call(e,r)&&r!==t&&ge(e,r,{get:()=>n[r],enumerable:!(o=gn(n,r))||o.enumerable});return e};var ee=(e,n,t)=>(t=e!=null?mn(yn(e)):{},et(n||!e||!e.__esModule?ge(t,"default",{value:e,enumerable:!0}):t,e)),kn=e=>et(ge({},"__esModule",{value:!0}),e);var Oo={};_n(Oo,{buildClients:()=>pn,buildRouter:()=>dn});module.exports=kn(Oo);var vn=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,T=vn();var Qe=require("child_process"),Y=require("fs"),ln=ee(require("path"),1),w=ee(require("process"),1),fe=require("@urun-sh/core");function tt(e,n,t,o){let r=e.response??{},s={request_id:t,consumer_id:o,stream:!0,kind:"chat",messages:n};return typeof r.instructions=="string"&&(s.instructions=r.instructions),Array.isArray(r.modalities)&&(s.modalities=r.modalities),typeof r.temperature=="number"&&(s.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(s.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(s.tools=r.tools),s}function nt(e,n,t){let o={request_id:n,consumer_id:t,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),o}function ot(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let n=e,t=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:t.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var xn="llm-resp";async function*Pe(e,n){let t=`${xn}:${n}`,o=`resp_${n}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let s of e.stream(t).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,c=r.get(u)??{};a.id&&(c.id=a.id),a.function?.name&&(c.name=a.function.name),r.set(u,c),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${u}`,tool_index:u,call_id:c.id,name:c.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield ot(i);return}}}var Sn="llm",he=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(Sn).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,t){let o=nt(n,t,this.consumerId);return this.write(o),Pe(this.session,t)}sendResponseCreate(n,t,o){let r=tt(n,t,o,this.consumerId);return this.write(r),Pe(this.session,o)}};var rt=0;function bn(){return rt+=1,`req_${Date.now().toString(36)}_${rt.toString(36)}`}var ye=class{transport;constructor(n){this.transport=new he(n)}responses={create:async n=>{let t=bn(),o=this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*o})(),{requestId:t})}}};var Ce=class{constructor(n,t){this.backend=n;this.opts=t}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let t=Buffer.from(n,"base64"),o=Math.floor(t.byteLength/2),r=new Int16Array(o);for(let s=0;s<o;s++)r[s]=t.readInt16LE(s*2);this.source.onData(r)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=t=>{let o=Buffer.from(t.samples.buffer,t.samples.byteOffset,t.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function at(e,n,t=1e4){let o=new Ce(n,{sampleRate:24e3}),r=await o.startOutbound();await e.stream("rt-audio-in").attach(r);let s=await An(e,t);return await o.startInbound(s),o}function An(e,n){let t=e.stream("rt-audio-out");return t.track!=null?Promise.resolve(t.track):new Promise((o,r)=>{let s,i=setTimeout(()=>{s?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),a=u=>{u!=null&&(clearTimeout(i),s?.(),o(u))};s=t.on?.("track",a),t.track!=null&&a(t.track)})}var st="rt-video-in",it=256e3;function ut(e){let n=e.stream(st),t=n.emit;if(typeof t!="function")throw new Error(`enableSessionVideo: session.stream('${st}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>it)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${it}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await t.call(n,o)}}}var Rn=24e3,ae=480,En=111;async function In(){let e=await import("opusscript"),n=e.default??e;return new n(Rn,1,2048)}async function we(){let e=await import("werift"),n=await In();return{createSource:()=>{let t=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:t,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let c=0;for(;u.length-c>=ae;){let l=u.subarray(c,c+ae);c+=ae;let h=Buffer.from(l.buffer,l.byteOffset,l.byteLength),f=n.encode(h,ae);r=r+1&65535,s=s+ae>>>0;let g=new e.RtpHeader({version:2,payloadType:En,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),b=new e.RtpPacket(g,f);t.writeRtp(b)}i=u.slice(c)}}},createSink:t=>{let o={onframe:null};return t.onReceiveRtp.subscribe(s=>{let i;try{i=n.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);o.onframe?.({samples:a})}),o}}}async function ct(e){let t=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!t.ok)throw new Error(`model_catalog fetch failed: ${t.status}`);return await t.json()}var $t=require("http");var It=require("crypto"),Ot=require("ws");var lt="https://api.urun.sh/v1";function Ue(e){return e.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var M=class extends Error{},B=class extends Error{},$e="urs1.";function On(e,n){return $e+Buffer.from(JSON.stringify([e,n]),"utf8").toString("base64url")}function Tn(e){if(!e.startsWith($e))return null;try{let n=JSON.parse(Buffer.from(e.slice($e.length),"base64url").toString("utf8"));if(Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string")return{app:n[0],key:n[1]}}catch{}return null}async function dt(e){let n=e.fetchImpl??fetch,t=`${e.apiUrl.replace(/\/+$/,"")}/apps`,o=await n(t,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}var Pn=6e4,_e=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;seed(n,t){this.pool.set(n,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??Pn;if(this.appsCache&&Date.now()-this.appsCache.at<n)return this.appsCache.apps;let t=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:t},t}servable(n){return n.filter(t=>t.function_name===this.opts.fnName&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let n=new Set([this.opts.defaultApp]);if(this.opts.listApps)for(let t of this.servable(await this.deployedApps()))n.add(t);for(let t of this.pool.keys())n.add(t);return[this.opts.defaultApp,...[...n].filter(t=>t!==this.opts.defaultApp).sort()]}async resolveApp(n){let t=(n??"").trim();if(!t||t==="urun")return this.opts.defaultApp;let o=Ue(t);if(o===this.opts.defaultApp)return this.opts.defaultApp;if(this.pool.has(o))return o;if(this.opts.listApps){let r=await this.deployedApps(),s=this.servable(r);if(s.includes(o))return o;let i=s.filter(u=>u.startsWith(`${o}-`));if(i.length===1)return i[0];if(i.length>1)throw new M(`model "${t}" is ambiguous across deployed apps ${i.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let a=r.find(u=>u.app_slug===o||u.app_slug.startsWith(`${o}-`));if(a)throw new M(`model "${t}" maps to app "${a.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let s=(await this.opts.listCatalog()).find(i=>t===i.model_id||t===`${i.model_id}:${i.variant}`||o===Ue(i.model_id)||o===Ue(`${i.model_id}-${i.variant}`));if(s)throw new M(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${s.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return this.opts.defaultApp}async sessionFor(n){let t=await this.resolveApp(n),o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o}}keyOf(n){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(n);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(n){let{app:t,entry:o}=await this.sessionFor(n);return{app:t,handle:On(t,this.keyOf(o))}}async sessionForHandle(n){let t=Tn(n);if(!t)throw new B(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,s=this.pool.get(o),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new B(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==r)throw new B(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:i}}async evict(n,t){let o=this.pool.get(n);!o||await o.then(s=>s,()=>null)!==t||this.pool.get(n)!==o||(this.pool.delete(n),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(t=>({id:t,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let n=[...this.pool.values()];this.pool.clear();let t=[];if(await Promise.all(n.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};var ft="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Un=1007,mt=1008,K=1011,Ne=1008,d=class extends Error{constructor(t,o=Un){super(t);this.closeCode=o}closeCode},A=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,ke=["setup","clientContent","realtimeInput","toolResponse"];function gt(e){let n;try{n=JSON.parse(e)}catch{throw new d("client message is not valid JSON")}let t=A(n);if(!t)throw new d("client message must be a JSON object");let o=ke.filter(a=>t[a]!==void 0),r=Object.keys(t).filter(a=>!ke.includes(a));if(r.length>0)throw new d(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${ke.join(", ")}`);if(o.length!==1)throw new d(`client message must contain exactly one of ${ke.join(", ")} (got ${o.length})`);let s=o[0],i=A(t[s]);if(!i)throw new d(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ht(e,n){if(typeof e=="string")return e;let t=A(e),o=t?t.parts:void 0;if(!Array.isArray(o))throw new d(`${n}: expected a Content with a parts array`);let r=[];for(let s of o){let i=A(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new d(`${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`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new d(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new d(`${n}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
3
- `)}var $n={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Nn={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ln=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],pt=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Mn(e){let n=A(e);if(!n)throw new d("setup.realtimeInputConfig must be an object");for(let r of Object.keys(n))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new d(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=A(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!t)throw new d("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new d(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(t?.disabled!==!0)throw new d("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(!pt.includes(n.activityHandling))throw new d(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${pt.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var Dn=["temperature","maxOutputTokens","responseModalities"];function yt(e){for(let[l,h]of Object.entries(Nn))if(e[l]!==void 0)throw new d(h);for(let l of Object.keys(e))if(!Ln.includes(l))throw new d(`unsupported setup field "${l}"`);if(typeof e.model!="string"||e.model.length===0)throw new d('setup.model is required (format "models/{model}")');let n=e.model.replace(/^models\//,""),t,o,r=!1,s=A(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new d("setup.generationConfig must be an object");if(s){for(let l of Object.keys(s))if(!Dn.includes(l))throw new d(`unsupported generationConfig field "${l}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new d("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new d("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let l=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let h of l){let f=String(h).toUpperCase();if(f==="AUDIO"){r=!0;continue}if(f!=="TEXT")throw new d(`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 i=[];e.systemInstruction!==void 0&&i.push({role:"system",content:ht(e.systemInstruction,"setup.systemInstruction")});let a;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new d("setup.tools must be an array");a=[];for(let l of e.tools){let h=A(l);if(!h)throw new d("setup.tools entries must be objects");for(let f of Object.keys(h))if(f!=="functionDeclarations")throw new d(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(h.functionDeclarations))throw new d("tool.functionDeclarations must be an array");for(let f of h.functionDeclarations){let g=A(f);if(!g||typeof g.name!="string")throw new d("functionDeclarations entries require a string name");a.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let l=A(e.sessionResumption);if(!l)throw new d("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let h of Object.keys(l))if(h!=="handle")throw new d(`unsupported sessionResumption field "${h}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new d("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let c=e.realtimeInputConfig===void 0?$n:Mn(e.realtimeInputConfig);return{model:n,systemItems:i,tools:a,temperature:t,maxOutputTokens:o,audioModality:r,activity:c,sessionResumption:u}}function wt(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function _t(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function kt(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new d(`unsupported clientContent field "${o}"`);let n=e.turns===void 0?[]:e.turns;if(!Array.isArray(n))throw new d("clientContent.turns must be an array");let t=[];for(let o of n){let r=A(o);if(!r)throw new d("clientContent.turns entries must be Content objects");let s=r.role===void 0?"user":String(r.role).toLowerCase();if(s!=="user"&&s!=="model")throw new d(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:ht(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var ve=16e3,vt=24e3,jn=`audio/pcm;rate=${vt}`,xt=Buffer.alloc(960).toString("base64");function Bn(e,n,t){if(n===t)return e;let o=Math.floor(e.length*t/n),r=new Int16Array(o),s=n/t,i=e.length-1;for(let a=0;a<o;a++){let u=a*s,c=Math.floor(u);if(c>=i){r[a]=e[i];continue}let l=u-c;r[a]=Math.round(e[c]+(e[c+1]-e[c])*l)}return r}function Gn(e){let n=A(e);if(!n)throw new d("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new d(`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 d("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(n.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new d("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function Fn(e){let n=A(e);if(!n)throw new d("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new d(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(n.mimeType);if(t&&Number(t[1])!==ve)throw new d(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${ve} Hz (audio/pcm;rate=${ve})`);if(typeof n.data!="string"||n.data.length===0)throw new d("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 d(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let i=0;i<r.length;i++)r[i]=o.readInt16LE(i*2);let s=Bn(r,ve,vt);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function St(e){if(e.mediaChunks!==void 0)throw new d('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new d("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=A(e[r]);if(!s||Object.keys(s).length!==0)throw new d(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!n.includes(o))throw new d(`unsupported realtimeInput field "${o}"`);let t=n.filter(o=>e[o]!==void 0);if(t.length!==1)throw new d(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${t.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:Fn(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Gn(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new d("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new d("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function bt(e){for(let n of Object.keys(e))if(n!=="functionResponses")throw new d(`unsupported toolResponse field "${n}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new d("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(n=>{let t=A(n);if(!t||typeof t.id!="string"||t.id.length===0)throw new d("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function At(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Rt(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:jn,data:e}}]}}}}function Et(e){let n=A(e)??{},t=Array.isArray(n.output)?n.output:[],o=[],r=[],s=typeof n.output_text=="string"?n.output_text:"";if(!s)for(let c of t){let l=A(c);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let h of l.content){let f=A(h);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&r.push({role:"assistant",content:s});for(let c of t){let l=A(c);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new d(`upstream function_call item is missing call_id/name: ${JSON.stringify(c)}`,K);let h=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",f;try{f=JSON.parse(h)}catch{throw new d(`upstream function_call arguments are not valid JSON: ${h}`,K)}o.push({id:l.call_id,name:l.name,args:f}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:h})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let a=A(n.usage),u={serverContent:{turnComplete:!0}};if(a){let c={};typeof a.input_tokens=="number"&&(c.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(c.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(c.totalTokenCount=a.total_tokens),Object.keys(c).length>0&&(u.usageMetadata=c)}return i.push(u),{messages:i,assistantItems:r}}var Hn=256,Le=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>Hn;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},ue=e=>e.slice(0,120),Me=class{constructor(n,t,o){this.ws=n;this.clients=t;this.registry=o;n.on("message",r=>this.onMessage(r)),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 M){this.ws.close(mt,ue(n.message));return}if(n instanceof B){this.ws.close(Ne,ue(n.message));return}if(n instanceof d){this.ws.close(n.closeCode,ue(n.message));return}this.ws.close(K,ue(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=gt(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new d(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:s}=kt(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=St(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,o);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:xt);return}this.transcript.push(...bt(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(n){if(this.config)throw new d("setup may only be sent once, as the first client message");let t=yt(n),o=t.sessionResumption.handle;if(o!==null){let r=this.registry.get(o);if(!r)throw new d("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",Ne);if(r.model!==t.model)throw new d(`sessionResumption.handle was issued for model "${r.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new d("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...r.transcript],this.proxyHandle=r.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(r.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s)))}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.transcript.push(...t.systemItems);this.config=t,this.send({setupComplete:{}}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new d("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new d("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",K);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Rt(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(t=>t.appendInputAudio(n)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new d("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new d("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",K);return this.video=Promise.resolve(t.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(t=>t.sendInputFrame(n)).catch(t=>this.fail(t))}onActivity(n,t){if(!t.activity.manualActivity)throw new d(`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 d("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new d("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(t=>this.fail(t))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(n.model);this.proxyHandle=t;let o=(0,It.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(wt(o))}async handleUpstreamEnd(n){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(_t(n.timeLeftMs)),this.ws.close(K,ue(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;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}),r,s=!1;for await(let u of o){if(t.interrupted)break;let c=u;if(c.type==="error")throw new d(`upstream error: ${JSON.stringify(c)}`,K);if(c.type==="response.completed"){r=c.response,s=!0;continue}let l=At(c);l&&this.send(l)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new d("upstream produced no response.completed event",K);let{messages:i,assistantItems:a}=Et(r);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},qn=(e,n)=>{let t=e.headers["x-goog-api-key"];if(typeof t=="string")return t;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Tt(e,n){let t=new Ot.WebSocketServer({noServer:!0}),o=new Le;e.on("upgrade",(r,s,i)=>{let a=new URL(r.url??"/","http://localhost");if(a.pathname!==ft){s.write(`HTTP/1.1 404 Not Found\r
2
+ "use strict";var fn=Object.create;var Ze=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var wn=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of gn(n))!yn.call(e,r)&&r!==t&&Ze(e,r,{get:()=>n[r],enumerable:!(o=mn(n,r))||o.enumerable});return e};var ee=(e,n,t)=>(t=e!=null?fn(hn(e)):{},wn(n||!e||!e.__esModule?Ze(t,"default",{value:e,enumerable:!0}):t,e));var _n=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,P=_n();var Xe=require("child_process"),Y=require("fs"),dn=ee(require("path"),1),w=ee(require("process"),1);var ue=require("@urun-sh/core");async function et(e){let t=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!t.ok)throw new Error(`model_catalog fetch failed: ${t.status}`);return await t.json()}function tt(e,n,t,o){let r=e.response??{},s={request_id:t,consumer_id:o,stream:!0,kind:"chat",messages:n};return typeof r.instructions=="string"&&(s.instructions=r.instructions),Array.isArray(r.modalities)&&(s.modalities=r.modalities),typeof r.temperature=="number"&&(s.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(s.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(s.tools=r.tools),s}function nt(e,n,t){let o={request_id:n,consumer_id:t,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),o}function ot(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let n=e,t=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:t.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var kn="llm-resp";async function*Pe(e,n){let t=`${kn}:${n}`,o=`resp_${n}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let s of e.stream(t).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=r.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),r.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield ot(i);return}}}var vn="llm",ge=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(vn).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,t){let o=nt(n,t,this.consumerId);return this.write(o),Pe(this.session,t)}sendResponseCreate(n,t,o){let r=tt(n,t,o,this.consumerId);return this.write(r),Pe(this.session,o)}};var rt=0;function xn(){return rt+=1,`req_${Date.now().toString(36)}_${rt.toString(36)}`}var he=class{transport;constructor(n){this.transport=new ge(n)}responses={create:async n=>{let t=xn(),o=this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*o})(),{requestId:t})}}};var Te=class{constructor(n,t){this.backend=n;this.opts=t}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let t=Buffer.from(n,"base64"),o=Math.floor(t.byteLength/2),r=new Int16Array(o);for(let s=0;s<o;s++)r[s]=t.readInt16LE(s*2);this.source.onData(r)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=t=>{let o=Buffer.from(t.samples.buffer,t.samples.byteOffset,t.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function at(e,n,t=1e4){let o=new Te(n,{sampleRate:24e3}),r=await o.startOutbound();await e.stream("rt-audio-in").attach(r);let s=await Sn(e,t);return await o.startInbound(s),o}function Sn(e,n){let t=e.stream("rt-audio-out");return t.track!=null?Promise.resolve(t.track):new Promise((o,r)=>{let s,i=setTimeout(()=>{s?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),a=c=>{c!=null&&(clearTimeout(i),s?.(),o(c))};s=t.on?.("track",a),t.track!=null&&a(t.track)})}var st="rt-video-in",it=256e3;function ut(e){let n=e.stream(st),t=n.emit;if(typeof t!="function")throw new Error(`enableSessionVideo: session.stream('${st}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>it)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${it}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await t.call(n,o)}}}var bn=24e3,ae=480,An=111;async function Rn(){let e=await import("opusscript"),n=e.default??e;return new n(bn,1,2048)}async function ye(){let e=await import("werift"),n=await Rn();return{createSource:()=>{let t=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:t,onData:a=>{let c=new Int16Array(i.length+a.length);c.set(i,0),c.set(a,i.length);let u=0;for(;c.length-u>=ae;){let l=c.subarray(u,u+ae);u+=ae;let m=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=n.encode(m,ae);r=r+1&65535,s=s+ae>>>0;let h=new e.RtpHeader({version:2,payloadType:An,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),k=new e.RtpPacket(h,g);t.writeRtp(k)}i=c.slice(u)}}},createSink:t=>{let o={onframe:null};return t.onReceiveRtp.subscribe(s=>{let i;try{i=n.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let c=0;c<a.length;c++)a[c]=i.readInt16LE(c*2);o.onframe?.({samples:a})}),o}}}function En(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function In(e){let n=e?.type;return n==="response.completed"||n==="error"}function lt(e){return async function(t){return(async function*(){for(let r=1;r<=2;r++){let{app:s,entry:i}=await e.sessionFor(t.model),a=!1,c=!1;try{let u=await e.createStream(i,t);for await(let l of u){if(In(l)&&(a=!0),En(l)){if(r>1)continue}else c=!0;yield l}}catch(u){if(r<2&&!c){await e.evict(s,i);continue}throw u}if(a)return;if(r<2&&!c){await e.evict(s,i);continue}return}})()}}var ct="https://api.urun.sh/v1";function Ce(e){return e.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var N=class extends Error{},B=class extends Error{},Ue="urs1.";function On(e,n){return Ue+Buffer.from(JSON.stringify([e,n]),"utf8").toString("base64url")}function Pn(e){if(!e.startsWith(Ue))return null;try{let n=JSON.parse(Buffer.from(e.slice(Ue.length),"base64url").toString("utf8"));if(Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string")return{app:n[0],key:n[1]}}catch{}return null}async function dt(e){let n=e.fetchImpl??fetch,t=`${e.apiUrl.replace(/\/+$/,"")}/apps`,o=await n(t,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}var Tn=6e4,we=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;seed(n,t){this.pool.set(n,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??Tn;if(this.appsCache&&Date.now()-this.appsCache.at<n)return this.appsCache.apps;let t=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:t},t}servable(n){return n.filter(t=>t.function_name===this.opts.fnName&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let n=this.opts.defaultApp,t=new Set(n===null?[]:[n]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())t.add(r);let o=[...t].filter(r=>r!==n).sort();return n===null?o:[n,...o]}async noDefaultApp(n){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new N(n===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${o}`:`model "${n}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${o}`)}async resolveApp(n){let t=(n??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):o;let r=Ce(t);if(r===o)return o;if(this.pool.has(r))return r;if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(r))return r;let a=i.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return a[0];if(a.length>1)throw new N(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let c=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(c)throw new N(`model "${t}" maps to app "${c.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===Ce(a.model_id)||r===Ce(`${a.model_id}-${a.variant}`));if(i)throw new N(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):o}async sessionFor(n){let t=await this.resolveApp(n),o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o}}keyOf(n){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(n);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(n){let{app:t,entry:o}=await this.sessionFor(n);return{app:t,handle:On(t,this.keyOf(o))}}async sessionForHandle(n){let t=Pn(n);if(!t)throw new B(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,s=this.pool.get(o),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new B(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==r)throw new B(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:i}}async evict(n,t){let o=this.pool.get(n);!o||await o.then(s=>s,()=>null)!==t||this.pool.get(n)!==o||(this.pool.delete(n),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(t=>({id:t,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let n=[...this.pool.values()];this.pool.clear();let t=[];if(await Promise.all(n.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};var Cn=3,Un="llm",$n=new Set(["ended","expired","error"]);function pt(e,n){let t=e.doc(Un),o=typeof t.onConnectionState=="function",r=typeof e.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=new Set,a=[],c=u=>{if(!s){s=u;for(let l of[...i])l(u);i.clear()}};return o&&a.push(t.onConnectionState(u=>{u.consecutiveFailures<Cn||c(new B(`the pooled session for app "${n}" is gone: its doc backhaul failed ${u.consecutiveFailures} consecutive times (last close ${u.lastCloseCode===null?"by provider liveness reap":`code ${u.lastCloseCode}`}${u.lastCloseReason?`, reason ${JSON.stringify(u.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),r&&a.push(e.onPhase(u=>{$n.has(u.name)&&c(new B(`the pooled session for app "${n}" is gone: it reached terminal phase "${u.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>s,onGone(u){return s?(u(s),()=>{}):(i.add(u),()=>i.delete(u))},dispose(){i.clear();for(let u of a.splice(0))u()}}}async function*$e(e,n){let t=n.gone();if(t)throw t;let o=e[Symbol.asyncIterator](),r,s=new Promise((i,a)=>{r=n.onGone(c=>a(c))});s.catch(()=>{});try{for(;;){let i=await Promise.race([o.next(),s]);if(i.done)return;yield i.value}}finally{r?.(),o.return?.(void 0)}}function ft(e,n,t){let o=e[t];if(typeof o!="function")throw new Error(`app "${n}" has no function "${t}" (set URUN_FUNCTION)`);let r=o();if(typeof r.end!="function")throw new Error(`app "${n}" function "${t}" returned a session without end()`);return r}function Nn(e,n){let{baseUrl:t,orgId:o,fnName:r,auth:s,subject:i}=e,a=m=>({session:m,responses:new he(m),gone:pt(m,n)});if(s.lane==="jwt"){let m=(0,ue.App)(n,{baseUrl:t,orgId:o,jwt:s.jwt});return a(ft(m,n,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,ue.App)(n,{baseUrl:t,orgId:o,getAccessToken:async()=>(await(0,ue.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${n}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(ft(l,n,r))}function Ln(e){let n=e.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var Mn=new Set(["error","ended","expired"]);function mt(e){let{auth:n,catalog:t}=e,o=null,r=i=>{let a=Nn(e,i);return a.gone.onGone(()=>{o?.evict(i,a)}),a},s=new we({defaultApp:e.defaultApp,fnName:e.fnName,openSession:r,closeSession:async i=>{i.gone.dispose(),await i.session.end()},listApps:n.lane==="api-key"?()=>dt({apiUrl:e.apiUrl,apiKey:n.apiKey}):null,listCatalog:t?()=>et(t):null,sessionKey:Ln});return o=s,e.defaultApp!==null&&s.seed(e.defaultApp,r(e.defaultApp)),s}function gt(e,n=ye){let t=new WeakMap,o=new WeakMap;return{createResponse:lt({sessionFor:r=>e.sessionFor(r),evict:(r,s)=>e.evict(r,s),createStream:async(r,s)=>$e(await r.responses.responses.create(s),r.gone)}),listModels:()=>e.modelList(),openAudio:async r=>{let{entry:s}=await e.sessionFor(r),i=t.get(s);return i||(i=(async()=>at(s.session,await n()))(),t.set(s,i),i.catch(()=>t.delete(s))),i},openVideo:async r=>{let{entry:s}=await e.sessionFor(r),i=o.get(s);return i||(i=ut(s.session),o.set(s,i)),i},sessionHandle:async r=>(await e.handleFor(r)).handle,createResponseOn:async(r,s)=>{let{entry:i}=await e.sessionForHandle(r);return $e(await i.responses.responses.create(s),i.gone)},onSessionEnd:async(r,s)=>{let{entry:i}=await e.sessionForHandle(r),a=i.session;if(typeof a.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let c=!1;return a.onPhase(u=>{if(c||!Mn.has(u.name))return;c=!0;let l=a.endsAt??null;s({timeLeftMs:l?Math.max(0,l.getTime()-Date.now()):null,reason:u.name==="expired"?"session reached its maximum length":`session ${u.name}`})})}}}var Dt=require("http");var Ct=require("crypto"),Ut=require("ws");var yt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",jn=1007,wt=1008,V=1011,Ne=1008,d=class extends Error{constructor(t,o=jn){super(t);this.closeCode=o}closeCode},E=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,_e=["setup","clientContent","realtimeInput","toolResponse"];function _t(e){let n;try{n=JSON.parse(e)}catch{throw new d("client message is not valid JSON")}let t=E(n);if(!t)throw new d("client message must be a JSON object");let o=_e.filter(a=>t[a]!==void 0),r=Object.keys(t).filter(a=>!_e.includes(a));if(r.length>0)throw new d(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${_e.join(", ")}`);if(o.length!==1)throw new d(`client message must contain exactly one of ${_e.join(", ")} (got ${o.length})`);let s=o[0],i=E(t[s]);if(!i)throw new d(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function kt(e,n){if(typeof e=="string")return e;let t=E(e),o=t?t.parts:void 0;if(!Array.isArray(o))throw new d(`${n}: expected a Content with a parts array`);let r=[];for(let s of o){let i=E(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new d(`${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`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new d(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new d(`${n}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
3
+ `)}var Bn={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Gn={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Fn=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],ht=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Hn(e){let n=E(e);if(!n)throw new d("setup.realtimeInputConfig must be an object");for(let r of Object.keys(n))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new d(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=E(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!t)throw new d("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new d(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(t?.disabled!==!0)throw new d("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(!ht.includes(n.activityHandling))throw new d(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${ht.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var qn=["temperature","maxOutputTokens","responseModalities"];function vt(e){for(let[l,m]of Object.entries(Gn))if(e[l]!==void 0)throw new d(m);for(let l of Object.keys(e))if(!Fn.includes(l))throw new d(`unsupported setup field "${l}"`);if(typeof e.model!="string"||e.model.length===0)throw new d('setup.model is required (format "models/{model}")');let n=e.model.replace(/^models\//,""),t,o,r=!1,s=E(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new d("setup.generationConfig must be an object");if(s){for(let l of Object.keys(s))if(!qn.includes(l))throw new d(`unsupported generationConfig field "${l}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new d("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new d("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let l=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of l){let g=String(m).toUpperCase();if(g==="AUDIO"){r=!0;continue}if(g!=="TEXT")throw new d(`responseModalities ${JSON.stringify(m)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let i=[];e.systemInstruction!==void 0&&i.push({role:"system",content:kt(e.systemInstruction,"setup.systemInstruction")});let a;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new d("setup.tools must be an array");a=[];for(let l of e.tools){let m=E(l);if(!m)throw new d("setup.tools entries must be objects");for(let g of Object.keys(m))if(g!=="functionDeclarations")throw new d(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new d("tool.functionDeclarations must be an array");for(let g of m.functionDeclarations){let h=E(g);if(!h||typeof h.name!="string")throw new d("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let c={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let l=E(e.sessionResumption);if(!l)throw new d("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(l))if(m!=="handle")throw new d(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new d("sessionResumption.handle must be a non-empty string when present");c={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let u=e.realtimeInputConfig===void 0?Bn:Hn(e.realtimeInputConfig);return{model:n,systemItems:i,tools:a,temperature:t,maxOutputTokens:o,audioModality:r,activity:u,sessionResumption:c}}function xt(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function St(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function bt(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new d(`unsupported clientContent field "${o}"`);let n=e.turns===void 0?[]:e.turns;if(!Array.isArray(n))throw new d("clientContent.turns must be an array");let t=[];for(let o of n){let r=E(o);if(!r)throw new d("clientContent.turns entries must be Content objects");let s=r.role===void 0?"user":String(r.role).toLowerCase();if(s!=="user"&&s!=="model")throw new d(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:kt(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var ke=16e3,At=24e3,Jn=`audio/pcm;rate=${At}`,Rt=Buffer.alloc(960).toString("base64");function Kn(e,n,t){if(n===t)return e;let o=Math.floor(e.length*t/n),r=new Int16Array(o),s=n/t,i=e.length-1;for(let a=0;a<o;a++){let c=a*s,u=Math.floor(c);if(u>=i){r[a]=e[i];continue}let l=c-u;r[a]=Math.round(e[u]+(e[u+1]-e[u])*l)}return r}function Vn(e){let n=E(e);if(!n)throw new d("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new d(`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 d("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(n.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new d("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function Wn(e){let n=E(e);if(!n)throw new d("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new d(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(n.mimeType);if(t&&Number(t[1])!==ke)throw new d(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${ke} Hz (audio/pcm;rate=${ke})`);if(typeof n.data!="string"||n.data.length===0)throw new d("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 d(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let i=0;i<r.length;i++)r[i]=o.readInt16LE(i*2);let s=Kn(r,ke,At);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Et(e){if(e.mediaChunks!==void 0)throw new d('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new d("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=E(e[r]);if(!s||Object.keys(s).length!==0)throw new d(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!n.includes(o))throw new d(`unsupported realtimeInput field "${o}"`);let t=n.filter(o=>e[o]!==void 0);if(t.length!==1)throw new d(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${t.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:Wn(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:Vn(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new d("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new d("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function It(e){for(let n of Object.keys(e))if(n!=="functionResponses")throw new d(`unsupported toolResponse field "${n}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new d("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(n=>{let t=E(n);if(!t||typeof t.id!="string"||t.id.length===0)throw new d("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function Ot(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Pt(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Jn,data:e}}]}}}}function Tt(e){let n=E(e)??{},t=Array.isArray(n.output)?n.output:[],o=[],r=[],s=typeof n.output_text=="string"?n.output_text:"";if(!s)for(let u of t){let l=E(u);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let m of l.content){let g=E(m);g?.type==="output_text"&&typeof g.text=="string"&&(s+=g.text)}}s&&r.push({role:"assistant",content:s});for(let u of t){let l=E(u);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new d(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,V);let m=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",g;try{g=JSON.parse(m)}catch{throw new d(`upstream function_call arguments are not valid JSON: ${m}`,V)}o.push({id:l.call_id,name:l.name,args:g}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:m})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let a=E(n.usage),c={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(c.usageMetadata=u)}return i.push(c),{messages:i,assistantItems:r}}var Yn=256,Le=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>Yn;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},le=e=>e.slice(0,120),Me=class{constructor(n,t,o){this.ws=n;this.clients=t;this.registry=o;n.on("message",r=>this.onMessage(r)),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 N){this.ws.close(wt,le(n.message));return}if(n instanceof B){this.ws.close(Ne,le(n.message));return}if(n instanceof d){this.ws.close(n.closeCode,le(n.message));return}this.ws.close(V,le(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=_t(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new d(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:s}=bt(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=Et(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,o);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:Rt);return}this.transcript.push(...It(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(n){if(this.config)throw new d("setup may only be sent once, as the first client message");let t=vt(n),o=t.sessionResumption.handle;if(o!==null){let r=this.registry.get(o);if(!r)throw new d("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",Ne);if(r.model!==t.model)throw new d(`sessionResumption.handle was issued for model "${r.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new d("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...r.transcript],this.proxyHandle=r.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(r.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s)))}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.transcript.push(...t.systemItems);this.config=t,this.send({setupComplete:{}}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new d("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new d("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",V);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Pt(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(t=>t.appendInputAudio(n)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new d("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new d("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",V);return this.video=Promise.resolve(t.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(t=>t.sendInputFrame(n)).catch(t=>this.fail(t))}onActivity(n,t){if(!t.activity.manualActivity)throw new d(`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 d("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new d("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(t=>this.fail(t))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(n.model);this.proxyHandle=t;let o=(0,Ct.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(xt(o))}async handleUpstreamEnd(n){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(St(n.timeLeftMs)),this.ws.close(V,le(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;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}),r,s=!1;for await(let c of o){if(t.interrupted)break;let u=c;if(u.type==="error")throw new d(`upstream error: ${JSON.stringify(u)}`,V);if(u.type==="response.completed"){r=u.response,s=!0;continue}let l=Ot(u);l&&this.send(l)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new d("upstream produced no response.completed event",V);let{messages:i,assistantItems:a}=Tt(r);this.transcript.push(...a);for(let c of i)this.send(c);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},zn=(e,n)=>{let t=e.headers["x-goog-api-key"];if(typeof t=="string")return t;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function $t(e,n){let t=new Ut.WebSocketServer({noServer:!0}),o=new Le;e.on("upgrade",(r,s,i)=>{let a=new URL(r.url??"/","http://localhost");if(a.pathname!==yt){s.write(`HTTP/1.1 404 Not Found\r
4
4
  Connection: close\r
5
5
  \r
6
- no WS route for ${a.pathname}`),s.destroy();return}if(n.apiKey&&qn(r,a)!==n.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
6
+ no WS route for ${a.pathname}`),s.destroy();return}if(n.apiKey&&zn(r,a)!==n.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
7
7
  Connection: close\r
8
8
  \r
9
- invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,u=>{new Me(u,n.clients,o)})})}var Be=class e{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,t,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(n){let t=this.models[n];if(t)return t;let o=Object.keys(this.models).length>=Jn?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,t){let o=this,r=performance.now(),s=null,i=0;return(async function*(){for await(let u of n)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-r),o.ttftMs.length>512&&o.ttftMs.shift()),i+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield u;let a=(performance.now()-(s??r))/1e3;i>0&&a>0&&(o.tokRates.push(i/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let t=[...n].sort((o,r)=>o-r);return t[Math.floor(t.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((t,o)=>t+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:e.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:e.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 Fe(e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function q(e,n,t){e.writeHead(n,{"content-type":"application/json"}),e.end(JSON.stringify(t))}function W(e,n,t,o="invalid_request_error"){q(e,n,{error:{message:t,type:o}})}function H(e,n,t,o){q(e,n,{type:"error",error:{type:t,message:o}})}function He(e,n,t){if(n==="anthropic"){q(e,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}q(e,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Jn=256,Vn=128;function qe(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,Vn)}var Pt=64*1024*1024,xe=class extends Error{};async function Kn(e){let n=[],t=0;for await(let r of e){if(t+=r.length,t>Pt)throw new xe(`request body exceeds ${Pt} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function te(e,n,t,o){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:t,finish_reason:o}]}}var Wn=256;function Yn(e){if(typeof e=="string")return[{role:"user",content:e}];if(Array.isArray(e))return e;throw new Error("responses input must be a string or an array of messages/items")}var Ge=class{conversations=new Map;thread(n,t){let o=Yn(t);if(n==null)return o;let r=this.conversations.get(String(n));if(!r)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(n,t,o){this.conversations.set(n,[...t,{role:"assistant",content:o}]);for(let r of this.conversations.keys()){if(this.conversations.size<=Wn)break;this.conversations.delete(r)}}};function ce(e){let n=e?.output;return Array.isArray(n)?n.filter(t=>t.type==="function_call"):[]}function X(e){return e.find(n=>n.type==="response.completed")?.response??null}function Se(e){let n=e?.usage;if(!n||typeof n!="object")return null;let t=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,o=t(n.input_tokens),r=t(n.output_tokens);if(o===0&&r===0)return null;let s=t(n.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:s}}function Ct(e){let n=Se(e);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 Nt(e){let n=e?.output;if(!Array.isArray(n))return"";let t="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function le(e){return e.type!=="response.function_call_arguments.delta"||typeof e.tool_index!="number"?null:{tool_index:e.tool_index,call_id:typeof e.call_id=="string"?e.call_id:void 0,name:typeof e.name=="string"?e.name:void 0,delta:typeof e.delta=="string"?e.delta:""}}var Q=class{calls=new Map;add(n){let t=this.calls.get(n.tool_index),o=!t;return t||(t={args:""},this.calls.set(n.tool_index,t)),n.call_id&&(t.id=n.call_id),n.name&&(t.name=n.name),t.args+=n.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,t])=>({type:"function_call",call_id:t.id??`call_${n}`,name:t.name??"",arguments:t.args}))}},zn=["<tool_call>","<function="];function Xn(e){return zn.find(n=>e.includes(n))}function ne(e,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 "${e}" (see catalog parser_defaults)`}function oe(e,n,t){if(!(!e||n>0))return Xn(t)}function Qn(e){if(Array.isArray(e))return e.map(n=>{let t=n.function;return!t||typeof t!="object"?n:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var be=class extends Error{};function Zn(e,n){return Array.isArray(n)?n.map(t=>{let o=t;if(o.type==="text")return{type:e==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new be(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function eo(e){let n=[];for(let t of e){if(t.role==="tool"){n.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&n.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let r=o.function??{};n.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}n.push({...t,content:Zn(t.role,t.content)})}return n}function De(e){return ce(e).map((n,t)=>({index:t,id:n.call_id??n.id??`call_${t}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function Ut(e,n){let t=n?.output_text;return typeof t=="string"?t:e.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function to(e,n,t,o,r){let s=e.stream===!0,i;try{i=t.thread(e.previous_response_id,e.input)}catch(m){W(o,400,String(m instanceof Error?m.message:m));return}e.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,u=e.store!==!1,c=qe(e);r.model(c);let l=Array.isArray(e.tools)&&e.tools.length>0,h;try{h=await n.createResponse({model:e.model,input:i,stream:s,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(m){if(m instanceof M){He(o,"openai",m);return}throw m}let f=[];if(s){Fe(o);let m=_=>{o.write(`event: ${String(_.type??"message")}
9
+ invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,c=>{new Me(c,n.clients,o)})})}var Be=class e{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,t,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(n){let t=this.models[n];if(t)return t;let o=Object.keys(this.models).length>=Xn?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,t){let o=this,r=performance.now(),s=null,i=0;return(async function*(){for await(let c of n)c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-r),o.ttftMs.length>512&&o.ttftMs.shift()),i+=1,o.tokensOut+=1,o.charsOut+=c.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield c;let a=(performance.now()-(s??r))/1e3;i>0&&a>0&&(o.tokRates.push(i/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let t=[...n].sort((o,r)=>o-r);return t[Math.floor(t.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((t,o)=>t+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:e.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:e.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 Fe(e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function q(e,n,t){e.writeHead(n,{"content-type":"application/json"}),e.end(JSON.stringify(t))}function W(e,n,t,o="invalid_request_error"){q(e,n,{error:{message:t,type:o}})}function H(e,n,t,o){q(e,n,{type:"error",error:{type:t,message:o}})}function He(e,n,t){if(n==="anthropic"){q(e,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}q(e,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Xn=256,Qn=128;function qe(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,Qn)}var Nt=64*1024*1024,ve=class extends Error{};async function Zn(e){let n=[],t=0;for await(let r of e){if(t+=r.length,t>Nt)throw new ve(`request body exceeds ${Nt} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function te(e,n,t,o){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:t,finish_reason:o}]}}var eo=256;function to(e){if(typeof e=="string")return[{role:"user",content:e}];if(Array.isArray(e))return e;throw new Error("responses input must be a string or an array of messages/items")}var Ge=class{conversations=new Map;thread(n,t){let o=to(t);if(n==null)return o;let r=this.conversations.get(String(n));if(!r)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(n,t,o){this.conversations.set(n,[...t,{role:"assistant",content:o}]);for(let r of this.conversations.keys()){if(this.conversations.size<=eo)break;this.conversations.delete(r)}}};function ce(e){let n=e?.output;return Array.isArray(n)?n.filter(t=>t.type==="function_call"):[]}function X(e){return e.find(n=>n.type==="response.completed")?.response??null}function xe(e){let n=e?.usage;if(!n||typeof n!="object")return null;let t=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,o=t(n.input_tokens),r=t(n.output_tokens);if(o===0&&r===0)return null;let s=t(n.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:s}}function Lt(e){let n=xe(e);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 jt(e){let n=e?.output;if(!Array.isArray(n))return"";let t="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function de(e){return e.type!=="response.function_call_arguments.delta"||typeof e.tool_index!="number"?null:{tool_index:e.tool_index,call_id:typeof e.call_id=="string"?e.call_id:void 0,name:typeof e.name=="string"?e.name:void 0,delta:typeof e.delta=="string"?e.delta:""}}var Q=class{calls=new Map;add(n){let t=this.calls.get(n.tool_index),o=!t;return t||(t={args:""},this.calls.set(n.tool_index,t)),n.call_id&&(t.id=n.call_id),n.name&&(t.name=n.name),t.args+=n.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,t])=>({type:"function_call",call_id:t.id??`call_${n}`,name:t.name??"",arguments:t.args}))}},no=["<tool_call>","<function="];function oo(e){return no.find(n=>e.includes(n))}function ne(e,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 "${e}" (see catalog parser_defaults)`}function oe(e,n,t){if(!(!e||n>0))return oo(t)}function ro(e){if(Array.isArray(e))return e.map(n=>{let t=n.function;return!t||typeof t!="object"?n:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Se=class extends Error{};function so(e,n){return Array.isArray(n)?n.map(t=>{let o=t;if(o.type==="text")return{type:e==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new Se(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function io(e){let n=[];for(let t of e){if(t.role==="tool"){n.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&n.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let r=o.function??{};n.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}n.push({...t,content:so(t.role,t.content)})}return n}function De(e){return ce(e).map((n,t)=>({index:t,id:n.call_id??n.id??`call_${t}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function Mt(e,n){let t=n?.output_text;return typeof t=="string"?t:e.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function ao(e,n,t,o,r){let s=e.stream===!0,i;try{i=t.thread(e.previous_response_id,e.input)}catch(p){W(o,400,String(p instanceof Error?p.message:p));return}e.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,c=e.store!==!1,u=qe(e);r.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,m;try{m=await n.createResponse({model:e.model,input:i,stream:s,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(p){if(p instanceof N){He(o,"openai",p);return}throw p}let g=[];if(s){Fe(o);let p=_=>{o.write(`event: ${String(_.type??"message")}
10
10
  data: ${JSON.stringify(_)}
11
11
 
12
- `)},I=_=>_.response&&typeof _.response=="object"?{..._,response:{..._.response,id:a}}:_,y=`item_${a.slice(5)}`,C=`rs_${a.slice(5)}`,N=!1,D=!1,p=0,x=()=>{N||(N=!0,m({type:"response.created",response:{id:a,object:"response",status:"in_progress"}}))},G=!1,U=0,j="",F=()=>{G&&(G=!1,m({type:"response.reasoning_text.done",item_id:C,output_index:U,content_index:0,text:j}),m({type:"response.output_item.done",output_index:U,item:{id:C,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:j}],status:"completed"}}))},L=!1,v=0,E="",J=_=>{L&&(L=!1,m({type:"response.output_text.done",item_id:y,output_index:v,content_index:0,text:E}),m({type:"response.content_part.done",item_id:y,output_index:v,content_index:0,part:{type:"output_text",text:E}}),m({type:"response.output_item.done",output_index:v,item:{id:y,type:"message",role:"assistant",status:_,content:[{type:"output_text",text:E}]}}))},V=new Q,S=null,Z=-1,re=_=>{if(!S)return;let R=S;S=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:_}})},se=!1;for await(let _ of r.track(h,c)){f.push(_);let R=String(_.type??"");if(R==="response.created"||R==="response.in_progress"){N=!0,m(I(_));continue}if(R==="response.output_item.added"){D=!0,m(I(_));continue}if(R==="response.reasoning_text.delta"&&!D){x(),G||(G=!0,U=p++,m({type:"response.output_item.added",output_index:U,item:{id:C,type:"reasoning",summary:[],content:[],status:"in_progress"}})),j+=String(_.delta??""),m({type:"response.reasoning_text.delta",item_id:C,output_index:U,content_index:0,delta:_.delta});continue}if(R==="response.output_text.delta"&&!D){x(),F(),L||(L=!0,v=p++,m({type:"response.output_item.added",output_index:v,item:{id:y,type:"message",role:"assistant",status:"in_progress",content:[]}}),m({type:"response.content_part.added",item_id:y,output_index:v,content_index:0,part:{type:"output_text",text:""}})),E+=String(_.delta??""),m({type:R,item_id:y,output_index:v,content_index:0,delta:_.delta});continue}let O=D?null:le(_);if(O){if(x(),F(),J("completed"),V.add(O),O.tool_index!==Z){re("completed"),Z=O.tool_index;let k=p++;S={fcId:`fc_${a.slice(5)}_${O.tool_index}`,outputIndex:k,callId:O.call_id,name:O.name,args:""},m({type:"response.output_item.added",output_index:k,item:{id:S.fcId,type:"function_call",call_id:S.callId??S.fcId,name:S.name??"",arguments:"",status:"in_progress"}})}S&&(O.call_id&&(S.callId=O.call_id),O.name&&(S.name=O.name),S.args+=O.delta,m({type:"response.function_call_arguments.delta",item_id:S.fcId,output_index:S.outputIndex,delta:O.delta}));continue}if(R==="response.completed"&&!D){let k=ce(_.response),P=oe(l,V.size+k.length,E);if(P){se=!0,m({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ne(c,P)}});break}F(),J("completed"),re("completed"),V.size===0&&k.forEach(z=>{let ie=p++,me=z.id??z.call_id??`fc_${ie}`,Te=z.arguments??"",Ze={id:me,type:"function_call",call_id:z.call_id??me,name:z.name??""};m({type:"response.output_item.added",output_index:ie,item:{...Ze,arguments:"",status:"in_progress"}}),m({type:"response.function_call_arguments.delta",item_id:me,output_index:ie,delta:Te}),m({type:"response.function_call_arguments.done",item_id:me,output_index:ie,arguments:Te}),m({type:"response.output_item.done",output_index:ie,item:{...Ze,arguments:Te,status:"completed"}})}),m(I(_));continue}m(I(_))}F(),J("incomplete"),re("incomplete"),u&&!se&&t.remember(a,i,Ut(f,X(f))),o.write(`data: [DONE]
12
+ `)},S=_=>_.response&&typeof _.response=="object"?{..._,response:{..._.response,id:a}}:_,y=`item_${a.slice(5)}`,U=`rs_${a.slice(5)}`,L=!1,D=!1,f=0,A=()=>{L||(L=!0,p({type:"response.created",response:{id:a,object:"response",status:"in_progress"}}))},G=!1,$=0,j="",F=()=>{G&&(G=!1,p({type:"response.reasoning_text.done",item_id:U,output_index:$,content_index:0,text:j}),p({type:"response.output_item.done",output_index:$,item:{id:U,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:j}],status:"completed"}}))},M=!1,b=0,O="",J=_=>{M&&(M=!1,p({type:"response.output_text.done",item_id:y,output_index:b,content_index:0,text:O}),p({type:"response.content_part.done",item_id:y,output_index:b,content_index:0,part:{type:"output_text",text:O}}),p({type:"response.output_item.done",output_index:b,item:{id:y,type:"message",role:"assistant",status:_,content:[{type:"output_text",text:O}]}}))},K=new Q,R=null,Z=-1,re=_=>{if(!R)return;let I=R;R=null,p({type:"response.function_call_arguments.done",item_id:I.fcId,output_index:I.outputIndex,arguments:I.args}),p({type:"response.output_item.done",output_index:I.outputIndex,item:{id:I.fcId,type:"function_call",call_id:I.callId??I.fcId,name:I.name??"",arguments:I.args,status:_}})},se=!1;for await(let _ of r.track(m,u)){g.push(_);let I=String(_.type??"");if(I==="response.created"||I==="response.in_progress"){L=!0,p(S(_));continue}if(I==="response.output_item.added"){D=!0,p(S(_));continue}if(I==="response.reasoning_text.delta"&&!D){A(),G||(G=!0,$=f++,p({type:"response.output_item.added",output_index:$,item:{id:U,type:"reasoning",summary:[],content:[],status:"in_progress"}})),j+=String(_.delta??""),p({type:"response.reasoning_text.delta",item_id:U,output_index:$,content_index:0,delta:_.delta});continue}if(I==="response.output_text.delta"&&!D){A(),F(),M||(M=!0,b=f++,p({type:"response.output_item.added",output_index:b,item:{id:y,type:"message",role:"assistant",status:"in_progress",content:[]}}),p({type:"response.content_part.added",item_id:y,output_index:b,content_index:0,part:{type:"output_text",text:""}})),O+=String(_.delta??""),p({type:I,item_id:y,output_index:b,content_index:0,delta:_.delta});continue}let T=D?null:de(_);if(T){if(A(),F(),J("completed"),K.add(T),T.tool_index!==Z){re("completed"),Z=T.tool_index;let v=f++;R={fcId:`fc_${a.slice(5)}_${T.tool_index}`,outputIndex:v,callId:T.call_id,name:T.name,args:""},p({type:"response.output_item.added",output_index:v,item:{id:R.fcId,type:"function_call",call_id:R.callId??R.fcId,name:R.name??"",arguments:"",status:"in_progress"}})}R&&(T.call_id&&(R.callId=T.call_id),T.name&&(R.name=T.name),R.args+=T.delta,p({type:"response.function_call_arguments.delta",item_id:R.fcId,output_index:R.outputIndex,delta:T.delta}));continue}if(I==="response.completed"&&!D){let v=ce(_.response),C=oe(l,K.size+v.length,O);if(C){se=!0,p({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ne(u,C)}});break}F(),J("completed"),re("completed"),K.size===0&&v.forEach(z=>{let ie=f++,me=z.id??z.call_id??`fc_${ie}`,Oe=z.arguments??"",Qe={id:me,type:"function_call",call_id:z.call_id??me,name:z.name??""};p({type:"response.output_item.added",output_index:ie,item:{...Qe,arguments:"",status:"in_progress"}}),p({type:"response.function_call_arguments.delta",item_id:me,output_index:ie,delta:Oe}),p({type:"response.function_call_arguments.done",item_id:me,output_index:ie,arguments:Oe}),p({type:"response.output_item.done",output_index:ie,item:{...Qe,arguments:Oe,status:"completed"}})}),p(S(_));continue}p(S(_))}F(),J("incomplete"),re("incomplete"),c&&!se&&t.remember(a,i,Mt(g,X(g))),o.write(`data: [DONE]
13
13
 
14
- `),o.end();return}let g=null;for await(let m of r.track(h,c)){if(f.push(m),m.type==="error"){W(o,502,JSON.stringify(m),"upstream_error");return}m.type==="response.completed"&&(g=m.response)}if(g==null){W(o,502,"upstream produced no response.completed event","upstream_error");return}let b=Ut(f,g),$=oe(l,ce(g).length,b);if($){W(o,502,ne(c,$),"upstream_error");return}u&&t.remember(a,i,b),q(o,200,{...g,id:a})}async function no(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){W(t,400,"chat/completions requires a messages array");return}let s=String(e.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,a;try{a=eo(r)}catch(p){if(p instanceof be){W(t,400,p.message);return}throw p}let u=qe(e);o.model(u);let c=Array.isArray(e.tools)&&e.tools.length>0,l;try{l=await n.createResponse({model:e.model,input:a,stream:!0,tools:Qn(e.tools),tool_choice:e.tool_choice,temperature:e.temperature,max_output_tokens:e.max_completion_tokens??e.max_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(p){if(p instanceof M){He(t,"openai",p);return}throw p}if(e.stream===!0){Fe(t);let p=[],x=new Q,G="";t.write(`data: ${JSON.stringify(te(i,s,{role:"assistant"},null))}
14
+ `),o.end();return}let h=null;for await(let p of r.track(m,u)){if(g.push(p),p.type==="error"){W(o,502,JSON.stringify(p),"upstream_error");return}p.type==="response.completed"&&(h=p.response)}if(h==null){W(o,502,"upstream produced no response.completed event","upstream_error");return}let k=Mt(g,h),x=oe(l,ce(h).length,k);if(x){W(o,502,ne(u,x),"upstream_error");return}c&&t.remember(a,i,k),q(o,200,{...h,id:a})}async function uo(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){W(t,400,"chat/completions requires a messages array");return}let s=String(e.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,a;try{a=io(r)}catch(f){if(f instanceof Se){W(t,400,f.message);return}throw f}let c=qe(e);o.model(c);let u=Array.isArray(e.tools)&&e.tools.length>0,l;try{l=await n.createResponse({model:e.model,input:a,stream:!0,tools:ro(e.tools),tool_choice:e.tool_choice,temperature:e.temperature,max_output_tokens:e.max_completion_tokens??e.max_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(f){if(f instanceof N){He(t,"openai",f);return}throw f}if(e.stream===!0){Fe(t);let f=[],A=new Q,G="";t.write(`data: ${JSON.stringify(te(i,s,{role:"assistant"},null))}
15
15
 
16
- `);for await(let v of o.track(l,u)){p.push(v);let E=le(v);if(v.type==="response.output_text.delta"&&typeof v.delta=="string")G+=v.delta,t.write(`data: ${JSON.stringify(te(i,s,{content:v.delta},null))}
16
+ `);for await(let b of o.track(l,c)){f.push(b);let O=de(b);if(b.type==="response.output_text.delta"&&typeof b.delta=="string")G+=b.delta,t.write(`data: ${JSON.stringify(te(i,s,{content:b.delta},null))}
17
17
 
18
- `);else if(v.type==="response.reasoning_text.delta"&&typeof v.delta=="string")t.write(`data: ${JSON.stringify(te(i,s,{reasoning_content:v.delta},null))}
18
+ `);else if(b.type==="response.reasoning_text.delta"&&typeof b.delta=="string")t.write(`data: ${JSON.stringify(te(i,s,{reasoning_content:b.delta},null))}
19
19
 
20
- `);else if(E){let{call:J,isNew:V}=x.add(E),S=V?{index:E.tool_index,id:J.id??`call_${E.tool_index}`,type:"function",function:{name:J.name??"",arguments:E.delta}}:{index:E.tool_index,function:{arguments:E.delta}};t.write(`data: ${JSON.stringify(te(i,s,{tool_calls:[S]},null))}
20
+ `);else if(O){let{call:J,isNew:K}=A.add(O),R=K?{index:O.tool_index,id:J.id??`call_${O.tool_index}`,type:"function",function:{name:J.name??"",arguments:O.delta}}:{index:O.tool_index,function:{arguments:O.delta}};t.write(`data: ${JSON.stringify(te(i,s,{tool_calls:[R]},null))}
21
21
 
22
- `)}else if(v.type==="error"){t.write(`data: ${JSON.stringify({error:v})}
22
+ `)}else if(b.type==="error"){t.write(`data: ${JSON.stringify({error:b})}
23
23
 
24
- `),t.end();return}}let U=De(X(p)),j=oe(c,x.size+U.length,G);if(j){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ne(u,j)}})}
24
+ `),t.end();return}}let $=De(X(f)),j=oe(u,A.size+$.length,G);if(j){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ne(c,j)}})}
25
25
 
26
- `),t.end();return}x.size===0&&U.length>0&&t.write(`data: ${JSON.stringify(te(i,s,{tool_calls:U},null))}
26
+ `),t.end();return}A.size===0&&$.length>0&&t.write(`data: ${JSON.stringify(te(i,s,{tool_calls:$},null))}
27
27
 
28
- `);let F=x.size>0||U.length>0;t.write(`data: ${JSON.stringify(te(i,s,{},F?"tool_calls":"stop"))}
28
+ `);let F=A.size>0||$.length>0;t.write(`data: ${JSON.stringify(te(i,s,{},F?"tool_calls":"stop"))}
29
29
 
30
- `),Se(X(p))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:Ct(X(p))})}
30
+ `),xe(X(f))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:Lt(X(f))})}
31
31
 
32
32
  `),t.write(`data: [DONE]
33
33
 
34
- `),t.end();return}let h="",f="",g=[],b=new Q;for await(let p of o.track(l,u)){g.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(h+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(f+=p.delta);let x=le(p);if(x&&b.add(x),p.type==="error"){W(t,502,JSON.stringify(p),"upstream_error");return}}let $=X(g),m=De($),I=m.length>0?m:De({output:b.items()}),y=oe(c,I.length,h);if(y){W(t,502,ne(u,y),"upstream_error");return}let C=I.map(({index:p,...x})=>x),N={role:"assistant",content:h||null},D=f||Nt($);D&&(N.reasoning_content=D),C.length>0&&(N.tool_calls=C),q(t,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:s,choices:[{index:0,message:N,finish_reason:C.length>0?"tool_calls":"stop"}],usage:Ct($)})}function oo(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var de=class extends Error{};function Ae(e){return new de(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ro(e){if(Array.isArray(e))return e.map(n=>{let t=n;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function so(e){if(e==null)return;let n=e.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:e.name};throw new de(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function io(e){if(typeof e=="string")return e;if(e==null)return"";if(!Array.isArray(e))throw Ae(typeof e);let n="";for(let t of e){let o=String(t.type??"");if(o!=="text")throw Ae(`tool_result > ${o}`);n+=String(t.text??"")}return n}function ao(e){let{role:n,content:t}=e;if(typeof t=="string")return[{role:n,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Ae(typeof t);let o=[],r="",s=()=>{r&&(o.push({role:n,content:r}),r="")};for(let i of t){let a=String(i.type??"");if(a==="text")r+=String(i.text??"");else if(a==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:io(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ae(a)}}return s(),o}function je(e){return ce(e).map((n,t)=>{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_${t}`,name:n.name??"",input:o}})}async function uo(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){H(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof e.max_tokens!="number"||!Number.isInteger(e.max_tokens)||e.max_tokens<1){H(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(e.top_k!==void 0){H(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(e.stop_sequences!==void 0&&(!Array.isArray(e.stop_sequences)||e.stop_sequences.some(p=>typeof p!="string"))){H(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(e.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,a=[],u;try{e.system&&a.push({role:"system",content:oo(e.system)});for(let p of r)a.push(...ao(p));u=so(e.tool_choice)}catch(p){if(p instanceof de){H(t,400,"invalid_request_error",p.message);return}throw p}let c=qe(e);o.model(c);let l=Array.isArray(e.tools)&&e.tools.length>0,h;try{h=await n.createResponse({model:e.model,input:a,stream:!0,tools:ro(e.tools),tool_choice:u,temperature:e.temperature,max_output_tokens:e.max_tokens,top_p:e.top_p,stop:e.stop_sequences})}catch(p){if(p instanceof M){He(t,"anthropic",p);return}throw p}let f=(p,x)=>{t.destroyed||t.write(`event: ${p}
35
- data: ${JSON.stringify({type:p,...x})}
34
+ `),t.end();return}let m="",g="",h=[],k=new Q;for await(let f of o.track(l,c)){h.push(f),f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(m+=f.delta),f.type==="response.reasoning_text.delta"&&typeof f.delta=="string"&&(g+=f.delta);let A=de(f);if(A&&k.add(A),f.type==="error"){W(t,502,JSON.stringify(f),"upstream_error");return}}let x=X(h),p=De(x),S=p.length>0?p:De({output:k.items()}),y=oe(u,S.length,m);if(y){W(t,502,ne(c,y),"upstream_error");return}let U=S.map(({index:f,...A})=>A),L={role:"assistant",content:m||null},D=g||jt(x);D&&(L.reasoning_content=D),U.length>0&&(L.tool_calls=U),q(t,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:s,choices:[{index:0,message:L,finish_reason:U.length>0?"tool_calls":"stop"}],usage:Lt(x)})}function lo(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var pe=class extends Error{};function be(e){return new pe(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function co(e){if(Array.isArray(e))return e.map(n=>{let t=n;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function po(e){if(e==null)return;let n=e.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:e.name};throw new pe(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function fo(e){if(typeof e=="string")return e;if(e==null)return"";if(!Array.isArray(e))throw be(typeof e);let n="";for(let t of e){let o=String(t.type??"");if(o!=="text")throw be(`tool_result > ${o}`);n+=String(t.text??"")}return n}function mo(e){let{role:n,content:t}=e;if(typeof t=="string")return[{role:n,content:t}];if(t==null)return[];if(!Array.isArray(t))throw be(typeof t);let o=[],r="",s=()=>{r&&(o.push({role:n,content:r}),r="")};for(let i of t){let a=String(i.type??"");if(a==="text")r+=String(i.text??"");else if(a==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:fo(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw be(a)}}return s(),o}function je(e){return ce(e).map((n,t)=>{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_${t}`,name:n.name??"",input:o}})}async function go(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){H(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof e.max_tokens!="number"||!Number.isInteger(e.max_tokens)||e.max_tokens<1){H(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(e.top_k!==void 0){H(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(e.stop_sequences!==void 0&&(!Array.isArray(e.stop_sequences)||e.stop_sequences.some(f=>typeof f!="string"))){H(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(e.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,a=[],c;try{e.system&&a.push({role:"system",content:lo(e.system)});for(let f of r)a.push(...mo(f));c=po(e.tool_choice)}catch(f){if(f instanceof pe){H(t,400,"invalid_request_error",f.message);return}throw f}let u=qe(e);o.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,m;try{m=await n.createResponse({model:e.model,input:a,stream:!0,tools:co(e.tools),tool_choice:c,temperature:e.temperature,max_output_tokens:e.max_tokens,top_p:e.top_p,stop:e.stop_sequences})}catch(f){if(f instanceof N){He(t,"anthropic",f);return}throw f}let g=(f,A)=>{t.destroyed||t.write(`event: ${f}
35
+ data: ${JSON.stringify({type:f,...A})}
36
36
 
37
- `)};if(e.stream===!0){let p=o.track(h,c);Fe(t),f("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,G="",U=0,j="none",F=()=>j,L=-1,v=-1,E=new Q,J=[],V=()=>{j!=="none"&&(j="none",f("content_block_stop",{index:L}))},S=(k,P)=>{V(),j=k,L=U++,f("content_block_start",{index:L,content_block:P})};for await(let k of p){if(t.destroyed)break;J.push(k);let P=le(k);if(k.type==="response.reasoning_text.delta"&&typeof k.delta=="string")F()!=="thinking"&&S("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:L,delta:{type:"thinking_delta",thinking:k.delta}});else if(k.type==="response.output_text.delta"&&typeof k.delta=="string")F()!=="text"&&S("text",{type:"text",text:""}),x+=1,G+=k.delta,f("content_block_delta",{index:L,delta:{type:"text_delta",text:k.delta}});else if(P){let{call:z}=E.add(P);(F()!=="tool"||P.tool_index!==v)&&(v=P.tool_index,S("tool",{type:"tool_use",id:z.id??`call_${P.tool_index}`,name:z.name??"",input:{}})),P.delta&&f("content_block_delta",{index:L,delta:{type:"input_json_delta",partial_json:P.delta}})}else if(k.type==="error"){f("error",{error:{type:"api_error",message:JSON.stringify(k)}}),t.end();return}}if(t.destroyed)return;let Z=X(J),re=ce(Z),se=oe(l,E.size+re.length,G);if(se){f("error",{error:{type:"api_error",message:ne(c,se)}}),t.end();return}V();let _=[];if(E.size===0)try{_=je(Z)}catch(k){f("error",{error:{type:"api_error",message:String(k instanceof Error?k.message:k)}}),t.end();return}U===0&&_.length===0&&(S("text",{type:"text",text:""}),V()),_.forEach(k=>{let P=U++;f("content_block_start",{index:P,content_block:{...k,input:{}}}),f("content_block_delta",{index:P,delta:{type:"input_json_delta",partial_json:JSON.stringify(k.input??{})}}),f("content_block_stop",{index:P})});let R=E.size>0||_.length>0,O=Se(Z);f("message_delta",{delta:{stop_reason:R?"tool_use":"end_turn"},usage:O?{input_tokens:O.input_tokens,output_tokens:O.output_tokens}:{output_tokens:x}}),f("message_stop",{}),t.end();return}let g="",b="",$=[],m=new Q;for await(let p of o.track(h,c)){$.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(g+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(b+=p.delta);let x=le(p);if(x&&m.add(x),p.type==="error"){H(t,502,"api_error",JSON.stringify(p));return}if(t.destroyed)break}if(t.destroyed)return;let I=X($),y;try{y=je(I),y.length===0&&m.size>0&&(y=je({output:m.items()}))}catch(p){H(t,502,"api_error",String(p instanceof Error?p.message:p));return}let C=oe(l,y.length,g);if(C){H(t,502,"api_error",ne(c,C));return}let N=[],D=b||Nt(I);D&&N.push({type:"thinking",thinking:D}),(g||y.length===0)&&N.push({type:"text",text:g}),N.push(...y),q(t,200,{id:i,type:"message",role:"assistant",content:N,model:s,stop_reason:y.length>0?"tool_use":"end_turn",usage:Se(I)??{input_tokens:0,output_tokens:0}})}function Lt(e){let{clients:n,apiKey:t,identity:o}=e,r=new Ge,s=new Be,i=(0,$t.createServer)((a,u)=>{let c=new URL(a.url??"/","http://localhost"),l=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),h=(f,g,b,$)=>l?H(u,f,$,g):W(u,f,g,b);(async()=>{if(a.method==="GET"&&c.pathname==="/healthz"){q(u,200,{ok:!0});return}if(a.method==="GET"&&c.pathname==="/stats"){q(u,200,o?{identity:o,...s.snapshot()}:s.snapshot());return}if(t&&(a.headers.authorization??"")!==`Bearer ${t}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}if(a.method==="GET"&&c.pathname==="/v1/models"){q(u,200,await n.listModels());return}if(a.method!=="POST"){h(404,`no route for ${a.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let f;try{f=await Kn(a)}catch(b){if(b instanceof xe){h(413,b.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=Buffer.byteLength(JSON.stringify(f));if(c.pathname==="/v1/responses"){s.request("responses",g,g),await to(f,n,r,u,s);return}if(c.pathname==="/v1/chat/completions"){s.request("chat_completions",g,g),await no(f,n,u,s);return}if(c.pathname==="/v1/messages"){s.request("messages",g,g),await uo(f,n,u,s);return}if(c.pathname==="/v1/messages/count_tokens"){s.request("count_tokens",g,g),H(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}h(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let g=String(f instanceof Error?f.message:f);if(!u.headersSent){h(500,g,"proxy_error","api_error");return}u.destroyed||(l?u.write(`event: error
38
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:g}})}
37
+ `)};if(e.stream===!0){let f=o.track(m,u);Fe(t),g("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,G="",$=0,j="none",F=()=>j,M=-1,b=-1,O=new Q,J=[],K=()=>{j!=="none"&&(j="none",g("content_block_stop",{index:M}))},R=(v,C)=>{K(),j=v,M=$++,g("content_block_start",{index:M,content_block:C})};for await(let v of f){if(t.destroyed)break;J.push(v);let C=de(v);if(v.type==="response.reasoning_text.delta"&&typeof v.delta=="string")F()!=="thinking"&&R("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:M,delta:{type:"thinking_delta",thinking:v.delta}});else if(v.type==="response.output_text.delta"&&typeof v.delta=="string")F()!=="text"&&R("text",{type:"text",text:""}),A+=1,G+=v.delta,g("content_block_delta",{index:M,delta:{type:"text_delta",text:v.delta}});else if(C){let{call:z}=O.add(C);(F()!=="tool"||C.tool_index!==b)&&(b=C.tool_index,R("tool",{type:"tool_use",id:z.id??`call_${C.tool_index}`,name:z.name??"",input:{}})),C.delta&&g("content_block_delta",{index:M,delta:{type:"input_json_delta",partial_json:C.delta}})}else if(v.type==="error"){g("error",{error:{type:"api_error",message:JSON.stringify(v)}}),t.end();return}}if(t.destroyed)return;let Z=X(J),re=ce(Z),se=oe(l,O.size+re.length,G);if(se){g("error",{error:{type:"api_error",message:ne(u,se)}}),t.end();return}K();let _=[];if(O.size===0)try{_=je(Z)}catch(v){g("error",{error:{type:"api_error",message:String(v instanceof Error?v.message:v)}}),t.end();return}$===0&&_.length===0&&(R("text",{type:"text",text:""}),K()),_.forEach(v=>{let C=$++;g("content_block_start",{index:C,content_block:{...v,input:{}}}),g("content_block_delta",{index:C,delta:{type:"input_json_delta",partial_json:JSON.stringify(v.input??{})}}),g("content_block_stop",{index:C})});let I=O.size>0||_.length>0,T=xe(Z);g("message_delta",{delta:{stop_reason:I?"tool_use":"end_turn"},usage:T?{input_tokens:T.input_tokens,output_tokens:T.output_tokens}:{output_tokens:A}}),g("message_stop",{}),t.end();return}let h="",k="",x=[],p=new Q;for await(let f of o.track(m,u)){x.push(f),f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(h+=f.delta),f.type==="response.reasoning_text.delta"&&typeof f.delta=="string"&&(k+=f.delta);let A=de(f);if(A&&p.add(A),f.type==="error"){H(t,502,"api_error",JSON.stringify(f));return}if(t.destroyed)break}if(t.destroyed)return;let S=X(x),y;try{y=je(S),y.length===0&&p.size>0&&(y=je({output:p.items()}))}catch(f){H(t,502,"api_error",String(f instanceof Error?f.message:f));return}let U=oe(l,y.length,h);if(U){H(t,502,"api_error",ne(u,U));return}let L=[],D=k||jt(S);D&&L.push({type:"thinking",thinking:D}),(h||y.length===0)&&L.push({type:"text",text:h}),L.push(...y),q(t,200,{id:i,type:"message",role:"assistant",content:L,model:s,stop_reason:y.length>0?"tool_use":"end_turn",usage:xe(S)??{input_tokens:0,output_tokens:0}})}function ho(e){let{clients:n,apiKey:t,identity:o,statusOf:r}=e,s=typeof n=="function"?n:()=>n,i=new WeakMap,a=u=>{let l=i.get(u);return l||(l=new Ge,i.set(u,l)),l},c=new Be;return(u,l)=>{let m=new URL(u.url??"/","http://localhost"),g=m.pathname==="/v1/messages"||m.pathname.startsWith("/v1/messages/"),h=(k,x,p,S)=>g?H(l,k,S,x):W(l,k,x,p);(async()=>{if(u.method==="GET"&&m.pathname==="/healthz"){q(l,200,{ok:!0});return}if(u.method==="GET"&&m.pathname==="/stats"){q(l,200,o?{identity:o,...c.snapshot()}:c.snapshot());return}if(t&&(u.headers.authorization??"")!==`Bearer ${t}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let k=await s(u);if(u.method==="GET"&&m.pathname==="/v1/models"){q(l,200,await k.listModels());return}if(u.method!=="POST"){h(404,`no route for ${u.method} ${m.pathname}`,"invalid_request_error","not_found_error");return}let x;try{x=await Zn(u)}catch(S){if(S instanceof ve){h(413,S.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let p=Buffer.byteLength(JSON.stringify(x));if(m.pathname==="/v1/responses"){c.request("responses",p,p),await ao(x,k,a(k),l,c);return}if(m.pathname==="/v1/chat/completions"){c.request("chat_completions",p,p),await uo(x,k,l,c);return}if(m.pathname==="/v1/messages"){c.request("messages",p,p),await go(x,k,l,c);return}if(m.pathname==="/v1/messages/count_tokens"){c.request("count_tokens",p,p),H(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}h(404,`no route for POST ${m.pathname}`,"invalid_request_error","not_found_error")})().catch(k=>{let x=String(k instanceof Error?k.message:k);if(!l.headersSent){let p=r?.(k)??null;if(p){h(p.status,x,p.openaiType,p.anthropicType);return}h(500,x,"proxy_error","api_error");return}l.destroyed||(g?l.write(`event: error
38
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:x}})}
39
39
 
40
- `):u.write(`data: ${JSON.stringify({error:{message:g,type:"upstream_error"}})}
40
+ `):l.write(`data: ${JSON.stringify({error:{message:x,type:"upstream_error"}})}
41
41
 
42
- `)),u.end()})});return Tt(i,{clients:n,apiKey:t}),i}var Dt=ee(require("os"),1),jt=ee(require("path"),1),Bt=require("url"),Gt=require("util");var Mt="0.2.60";var Ft=4141,lo=Mt,Ee={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function Ke(e,n="openai"){if(n==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Ht(e,n,t){let o={...e,...Ke(n,t)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function qt(e,n,t){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=t.indexOf("--"),s=r===-1?t:t.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=t[0]==="exec",u=s.includes("--skip-git-repo-check"),c=a&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...o,...i?[]:["-m",n],...c]}function Jt(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function Vt(e,n,t){let o=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!t(o))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${o}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return o}let r=(0,Bt.fileURLToPath)(new URL("../pi-extension/standalone.cjs",n));if(!t(r))throw new Error(`pi extension entry not found at ${r} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return r}function Kt(e){let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return n}function Wt(e){if(e[0]!=="--port")return null;let n=Kt(e[1]);return e.splice(0,2),n}function We(e){let n=e.indexOf("--port");if(n===-1)return Ft;let t=Kt(e[n+1]);return e.splice(n,2),t}function Yt(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function Je(e,n){let t=(e[n]??"").trim();if(!t)throw new Error(`${n} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function pe(e){let n=po(Je(e,"URUN_BASE_URL")),t=Je(e,"URUN_ORG_ID"),o=Je(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Re(s,"URUN_API_URL"):lt,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:n,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(e.URUN_API_KEY??"").trim();if(u){let c=(e.URUN_GATEWAY_URL??"").trim(),l=c?Re(c):void 0;return{baseUrl:n,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function po(e,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function Re(e,n="URUN_GATEWAY_URL"){let t=new URL(e),o=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!o)throw new Error(`${n} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Ye(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:lo}}function fo(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var mo=250;async function ze(e,n=mo){try{let t=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(n)});if(!t.ok)return null;let o=(await t.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:u}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var zt=2e3;async function go(e,n=zt){try{let t=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(n)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function Xt(e,n,t=Ft,o=zt){if(e!=null)return{mode:"spawn",port:e};let r=await ze(t);if(r!==null&&fo(r,n)){let s=await go(t,o);return s===null?{mode:"reuse",port:t,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function Qt(e,n=Dt.default.homedir()){return jt.default.join(n,".urun","logs",`compat-proxy-${e}.log`)}var Ve=["log","info","warn","error","debug","trace"];function Zt(e,n=process,t=console){let o=n.stdout.write,r=n.stderr.write,s=(a,...u)=>e.write(a,...u);n.stdout.write=s,n.stderr.write=s;let i=Object.fromEntries(Ve.map(a=>[a,t[a]]));for(let a of Ve)t[a]=(...u)=>{e.write(`${(0,Gt.format)(...u)}
43
- `)};return()=>{n.stdout.write=o,n.stderr.write=r;for(let a of Ve)t[a]=i[a]}}var ho=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function en(e){let n=e?.code;return typeof n=="string"&&ho.has(n)}function Ie(e,n){try{return e.write(n),!0}catch(t){if(en(t))return!1;throw t}}function tn(e){let n={stdout:!1,stderr:!1},t=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{en(i)&&(n[o]=!0);let a=i?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${o} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
44
- `)}catch{}};r.on("error",s),t.push([r,s])}return{isDead:o=>n[o],uninstall:()=>{for(let[o,r]of t)o.off("error",r)}}}function nn(e){let n=t=>{let o=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
42
+ `)),l.end()})}}function Bt(e){let{clients:n,apiKey:t}=e,o=(0,Dt.createServer)(ho(e));return $t(o,{clients:n,apiKey:t}),o}var Ft=ee(require("os"),1),Ht=ee(require("path"),1),qt=require("url"),Jt=require("util");var Gt="0.3.0";var Kt=4141,wo=Gt,Re={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function Ve(e,n="openai"){if(n==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Vt(e,n,t){let o={...e,...Ve(n,t)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function Wt(e,n,t){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=t.indexOf("--"),s=r===-1?t:t.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=t[0]==="exec",c=s.includes("--skip-git-repo-check"),u=a&&!c?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...o,...i?[]:["-m",n],...u]}function Yt(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function zt(e,n,t){let o=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!t(o))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${o}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return o}let r=(0,qt.fileURLToPath)(new URL("../pi-extension/standalone.cjs",n));if(!t(r))throw new Error(`pi extension entry not found at ${r} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return r}function Xt(e){let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return n}function Qt(e){if(e[0]!=="--port")return null;let n=Xt(e[1]);return e.splice(0,2),n}function We(e){let n=e.indexOf("--port");if(n===-1)return Kt;let t=Xt(e[n+1]);return e.splice(n,2),t}function Zt(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function Je(e,n){let t=(e[n]??"").trim();if(!t)throw new Error(`${n} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function fe(e){let n=_o(Je(e,"URUN_BASE_URL")),t=Je(e,"URUN_ORG_ID"),o=Je(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Ae(s,"URUN_API_URL"):ct,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:n,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let c=(e.URUN_API_KEY??"").trim();if(c){let u=(e.URUN_GATEWAY_URL??"").trim(),l=u?Ae(u):void 0;return{baseUrl:n,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:c,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function _o(e,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function Ae(e,n="URUN_GATEWAY_URL"){let t=new URL(e),o=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!o)throw new Error(`${n} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Ye(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:wo}}function ko(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var vo=250;async function ze(e,n=vo){try{let t=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(n)});if(!t.ok)return null;let o=(await t.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:c}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof c!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:c}}catch{return null}}var en=2e3;async function xo(e,n=en){try{let t=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(n)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function tn(e,n,t=Kt,o=en){if(e!=null)return{mode:"spawn",port:e};let r=await ze(t);if(r!==null&&ko(r,n)){let s=await xo(t,o);return s===null?{mode:"reuse",port:t,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function nn(e,n=Ft.default.homedir()){return Ht.default.join(n,".urun","logs",`compat-proxy-${e}.log`)}var Ke=["log","info","warn","error","debug","trace"];function on(e,n=process,t=console){let o=n.stdout.write,r=n.stderr.write,s=(a,...c)=>e.write(a,...c);n.stdout.write=s,n.stderr.write=s;let i=Object.fromEntries(Ke.map(a=>[a,t[a]]));for(let a of Ke)t[a]=(...c)=>{e.write(`${(0,Jt.format)(...c)}
43
+ `)};return()=>{n.stdout.write=o,n.stderr.write=r;for(let a of Ke)t[a]=i[a]}}var So=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function rn(e){let n=e?.code;return typeof n=="string"&&So.has(n)}function Ee(e,n){try{return e.write(n),!0}catch(t){if(rn(t))return!1;throw t}}function sn(e){let n={stdout:!1,stderr:!1},t=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{rn(i)&&(n[o]=!0);let a=i?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${o} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
44
+ `)}catch{}};r.on("error",s),t.push([r,s])}return{isDead:o=>n[o],uninstall:()=>{for(let[o,r]of t)o.off("error",r)}}}function an(e){let n=t=>{let o=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
45
45
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
46
46
  `)}catch(r){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(r?.code??r)}) \u2014 the terminal is gone
47
- `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function on(e,n){let t="pass --port 0 for an OS-assigned ephemeral port";return n?`port ${e} is held by another urun-openai proxy serving app ${n.app} (org ${n.org}, fn ${n.fn}, version ${n.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${t}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}function yo(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function wo(e){let n=e?.type;return n==="response.completed"||n==="error"}function rn(e){return async function(t){return(async function*(){for(let r=1;r<=2;r++){let{app:s,entry:i}=await e.sessionFor(t.model),a=!1,u=!1;try{let c=await e.createStream(i,t);for await(let l of c){if(wo(l)&&(a=!0),yo(l)){if(r>1)continue}else u=!0;yield l}}catch(c){if(r<2&&!u){await e.evict(s,i);continue}throw c}if(a)return;if(r<2&&!u){await e.evict(s,i);continue}return}})()}}var _o=3,ko="llm",vo=new Set(["ended","expired","error"]);function sn(e,n){let t=e.doc(ko),o=typeof t.onConnectionState=="function",r=typeof e.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=new Set,a=[],u=c=>{if(!s){s=c;for(let l of[...i])l(c);i.clear()}};return o&&a.push(t.onConnectionState(c=>{c.consecutiveFailures<_o||u(new B(`the pooled session for app "${n}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),r&&a.push(e.onPhase(c=>{vo.has(c.name)&&u(new B(`the pooled session for app "${n}" is gone: it reached terminal phase "${c.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>s,onGone(c){return s?(c(s),()=>{}):(i.add(c),()=>i.delete(c))},dispose(){i.clear();for(let c of a.splice(0))c()}}}async function*Xe(e,n){let t=n.gone();if(t)throw t;let o=e[Symbol.asyncIterator](),r,s=new Promise((i,a)=>{r=n.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([o.next(),s]);if(i.done)return;yield i.value}}finally{r?.(),o.return?.(void 0)}}var Oe=require("@urun-sh/core/internal");var xo={ensureWebRTC:Oe.ensureNodeWebRTC,webrtcUnavailableReason:Oe.nodeWebRTCUnavailableReason,audioBackend:we};async function an(e=xo){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let n=e.webrtcUnavailableReason();if(n)return{ok:!1,reason:`${n} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function un(e,n,t){let o=e[t];if(typeof o!="function")throw new Error(`app "${n}" has no function "${t}" (set URUN_FUNCTION)`);let r=o();if(typeof r.end!="function")throw new Error(`app "${n}" function "${t}" returned a session without end()`);return r}function So(e,n){let{baseUrl:t,orgId:o,fnName:r,auth:s}=e,i=l=>({session:l,responses:new ye(l),gone:sn(l,n)});if(s.lane==="jwt"){let l=(0,fe.App)(n,{baseUrl:t,orgId:o,jwt:s.jwt});return i(un(l,n,r))}let{apiKey:a,gatewayUrl:u}=s,c=(0,fe.App)(n,{baseUrl:t,orgId:o,getAccessToken:async()=>(await(0,fe.createClientToken)(a,{baseUrl:u,expiresIn:300,allowedFunctions:[`${n}/${r}`]})).token});return i(un(c,n,r))}function bo(e){let n=e.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var Ao=new Set(["error","ended","expired"]);function dn(e){let n=(w.default.env.URUN_CATALOG_URL??"").trim(),t=n?Re(n,"URUN_CATALOG_URL"):"",o=(w.default.env.URUN_CATALOG_ANON_KEY??"").trim();(!t||!o)&&w.default.stderr.write(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
48
- `);let r=e.auth,s=null,i=u=>{let c=So(e,u);return c.gone.onGone(()=>{s?.evict(u,c)}),c},a=new _e({defaultApp:e.appId,fnName:e.fnName,openSession:i,closeSession:async u=>{u.gone.dispose(),await u.session.end()},listApps:r.lane==="api-key"?()=>dt({apiUrl:e.apiUrl,apiKey:r.apiKey}):null,listCatalog:t&&o?()=>ct({catalogUrl:t,anonKey:o}):null,sessionKey:bo});return s=a,a.seed(e.appId,i(e.appId)),a}function pn(e,n=we){let t=new WeakMap,o=new WeakMap;return{createResponse:rn({sessionFor:r=>e.sessionFor(r),evict:(r,s)=>e.evict(r,s),createStream:async(r,s)=>Xe(await r.responses.responses.create(s),r.gone)}),listModels:()=>e.modelList(),openAudio:async r=>{let{entry:s}=await e.sessionFor(r),i=t.get(s);return i||(i=(async()=>at(s.session,await n()))(),t.set(s,i),i.catch(()=>t.delete(s))),i},openVideo:async r=>{let{entry:s}=await e.sessionFor(r),i=o.get(s);return i||(i=ut(s.session),o.set(s,i)),i},sessionHandle:async r=>(await e.handleFor(r)).handle,createResponseOn:async(r,s)=>{let{entry:i}=await e.sessionForHandle(r);return Xe(await i.responses.responses.create(s),i.gone)},onSessionEnd:async(r,s)=>{let{entry:i}=await e.sessionForHandle(r),a=i.session;if(typeof a.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let u=!1;return a.onPhase(c=>{if(u||!Ao.has(c.name))return;u=!0;let l=a.endsAt??null;s({timeLeftMs:l?Math.max(0,l.getTime()-Date.now()):null,reason:c.name==="expired"?"session reached its maximum length":`session ${c.name}`})})}}}async function Ro(e,n,t){let o=(0,Qe.spawn)(e,n,{stdio:"inherit",env:t});return new Promise(r=>{o.once("exit",s=>r(s??1)),o.once("error",s=>{w.default.stderr.write(`failed to launch ${e}: ${String(s)}
49
- `),r(127)})})}function Eo(){return Vt(w.default.env,T,Y.existsSync)}function fn(e){for(let[n,t]of Object.entries(Ke(e)))w.default.stdout.write(`export ${n}=${t}
50
- `)}async function cn(e,n){let t=pe(w.default.env),o=n?Ye(t):void 0,r=dn(t),s=Lt({clients:pn(r),identity:o});try{await new Promise((a,u)=>{s.once("error",u),s.listen(e,"127.0.0.1",a)})}catch(a){throw await r.closeAll().catch(()=>{}),a.code==="EADDRINUSE"?new Error(on(e,await ze(e))):a}let i=s.address().port;return n&&(w.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${i}/v1
51
- `),fn(i)),{port:i,close:async()=>{let a=new Promise(u=>s.close(()=>u()));s.closeAllConnections(),await a,await r.closeAll()}}}async function Io(){let e=w.default.argv.slice(2),n=Wt(e),t=e.shift()??"proxy";if(t==="env")return fn(Yt(n??We(e))),0;if(t==="selftest"){let{ok:r,reason:s}=await an();return r?(w.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
47
+ `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function un(e,n){let t="pass --port 0 for an OS-assigned ephemeral port";return n?`port ${e} is held by another urun-openai proxy serving app ${n.app} (org ${n.org}, fn ${n.fn}, version ${n.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${t}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}var Ie=require("@urun-sh/core/internal");var bo={ensureWebRTC:Ie.ensureNodeWebRTC,webrtcUnavailableReason:Ie.nodeWebRTCUnavailableReason,audioBackend:ye};async function ln(e=bo){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let n=e.webrtcUnavailableReason();if(n)return{ok:!1,reason:`${n} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function Ao(e,n){let t=(e.URUN_CATALOG_URL??"").trim(),o=t?Ae(t,"URUN_CATALOG_URL"):"",r=(e.URUN_CATALOG_ANON_KEY??"").trim();return!o||!r?(n(`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
48
+ `),null):{catalogUrl:o,anonKey:r}}function Ro(e){return mt({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:Ao(w.default.env,n=>w.default.stderr.write(n))})}async function Eo(e,n,t){let o=(0,Xe.spawn)(e,n,{stdio:"inherit",env:t});return new Promise(r=>{o.once("exit",s=>r(s??1)),o.once("error",s=>{w.default.stderr.write(`failed to launch ${e}: ${String(s)}
49
+ `),r(127)})})}function Io(){return zt(w.default.env,P,Y.existsSync)}function pn(e){for(let[n,t]of Object.entries(Ve(e)))w.default.stdout.write(`export ${n}=${t}
50
+ `)}async function cn(e,n){let t=fe(w.default.env),o=n?Ye(t):void 0,r=Ro(t),s=Bt({clients:gt(r),identity:o});try{await new Promise((a,c)=>{s.once("error",c),s.listen(e,"127.0.0.1",a)})}catch(a){throw await r.closeAll().catch(()=>{}),a.code==="EADDRINUSE"?new Error(un(e,await ze(e))):a}let i=s.address().port;return n&&(w.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${i}/v1
51
+ `),pn(i)),{port:i,close:async()=>{let a=new Promise(c=>s.close(()=>c()));s.closeAllConnections(),await a,await r.closeAll()}}}async function Oo(){let e=w.default.argv.slice(2),n=Qt(e),t=e.shift()??"proxy";if(t==="env")return pn(Zt(n??We(e))),0;if(t==="selftest"){let{ok:r,reason:s}=await ln();return r?(w.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
52
52
  `),0):(w.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
53
- `),1)}if(t==="proxy"){let r=n??We(e),s=await cn(r,!0);return await new Promise(i=>{w.default.once("SIGINT",i),w.default.once("SIGTERM",i)}),await s.close(),0}let o=t==="run"?e.shift():t;{if(!o)throw new Error(`launch needs an agent (${Object.keys(Ee).join("|")}) or \`-- <cmd>\``);if(o==="pi"){let y=pe(w.default.env);return Ro("pi",["-e",Eo(),...Jt(y.appId,e)],w.default.env)}let r,s,i="openai";if(o==="--"){if(r=e.shift()??"",s=e,!r)throw new Error("`-- <cmd>` needs a command to launch")}else{let y=Ee[o];if(!y)throw new Error(`unknown command/agent ${o}; commands: proxy | env; agents: ${Object.keys(Ee).join(" | ")} \u2014 or \`-- <cmd>\``);r=y.bin,s=[...y.args??[],...e],i=y.env}let a=await Xt(n,Ye(pe(w.default.env))),u=null,c=a.port;a.mode==="reuse"?w.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${c} (app ${a.identity.app}, fn ${a.identity.fn}, v${a.identity.proxy_version})
53
+ `),1)}if(t==="proxy"){let r=n??We(e),s=await cn(r,!0);return await new Promise(i=>{w.default.once("SIGINT",i),w.default.once("SIGTERM",i)}),await s.close(),0}let o=t==="run"?e.shift():t;{if(!o)throw new Error(`launch needs an agent (${Object.keys(Re).join("|")}) or \`-- <cmd>\``);if(o==="pi"){let y=fe(w.default.env);return Eo("pi",["-e",Io(),...Yt(y.appId,e)],w.default.env)}let r,s,i="openai";if(o==="--"){if(r=e.shift()??"",s=e,!r)throw new Error("`-- <cmd>` needs a command to launch")}else{let y=Re[o];if(!y)throw new Error(`unknown command/agent ${o}; commands: proxy | env; agents: ${Object.keys(Re).join(" | ")} \u2014 or \`-- <cmd>\``);r=y.bin,s=[...y.args??[],...e],i=y.env}let a=await tn(n,Ye(fe(w.default.env))),c=null,u=a.port;a.mode==="reuse"?w.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${u} (app ${a.identity.app}, fn ${a.identity.fn}, v${a.identity.proxy_version})
54
54
  `):a.reason&&w.default.stderr.write(`urun compat: ${a.reason}
55
- `);let l=null,h=null,f=null,g=null;a.mode!=="reuse"&&(u=await cn(a.port,!1),c=u.port,g=Qt(c),(0,Y.mkdirSync)(ln.default.dirname(g),{recursive:!0}),f=(0,Y.createWriteStream)(g,{flags:"a"}),h=tn({streams:w.default,note:y=>(0,Y.appendFileSync)(g,y)}).uninstall,f.on("error",y=>{l?.(),l=null,Ie(w.default.stderr,`urun compat: proxy log ${g} failed: ${String(y)} \u2014 proxy output continues on the terminal
56
- `)}),w.default.stdout.write(`urun openai proxy on http://127.0.0.1:${c}/v1 \u2014 proxy logs: ${g}
57
- `),l=Zt(f)),o==="codex"&&(s=qt(c,pe(w.default.env).appId,s));let b=(0,Qe.spawn)(r,s,{stdio:"inherit",env:Ht(w.default.env,c,i)}),$=g!==null?nn({logPath:g,appendSync:Y.appendFileSync,restore:()=>{l?.(),l=null},writeStderr:y=>w.default.stderr.write(y),killChild:()=>b.kill("SIGTERM"),exit:y=>w.default.exit(y),proc:w.default}):null,m=await new Promise(y=>{b.once("exit",C=>y(C??1)),b.once("error",C=>{l?.(),l=null,Ie(w.default.stderr,`failed to launch ${r}: ${String(C)}
58
- `),y(127)})});$?.();let I=null;try{u&&await u.close()}catch(y){I=y}finally{l?.(),l=null,h?.(),h=null,f?.end()}return I!==null&&Ie(w.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${m} preserved): ${String(I instanceof Error?I.message:I)}
59
- `),m}}Io().then(e=>w.default.exit(e),e=>{w.default.stderr.write(`${String(e instanceof Error?e.message:e)}
60
- `),w.default.exit(1)});0&&(module.exports={buildClients,buildRouter});
55
+ `);let l=null,m=null,g=null,h=null;a.mode!=="reuse"&&(c=await cn(a.port,!1),u=c.port,h=nn(u),(0,Y.mkdirSync)(dn.default.dirname(h),{recursive:!0}),g=(0,Y.createWriteStream)(h,{flags:"a"}),m=sn({streams:w.default,note:y=>(0,Y.appendFileSync)(h,y)}).uninstall,g.on("error",y=>{l?.(),l=null,Ee(w.default.stderr,`urun compat: proxy log ${h} failed: ${String(y)} \u2014 proxy output continues on the terminal
56
+ `)}),w.default.stdout.write(`urun openai proxy on http://127.0.0.1:${u}/v1 \u2014 proxy logs: ${h}
57
+ `),l=on(g)),o==="codex"&&(s=Wt(u,fe(w.default.env).appId,s));let k=(0,Xe.spawn)(r,s,{stdio:"inherit",env:Vt(w.default.env,u,i)}),x=h!==null?an({logPath:h,appendSync:Y.appendFileSync,restore:()=>{l?.(),l=null},writeStderr:y=>w.default.stderr.write(y),killChild:()=>k.kill("SIGTERM"),exit:y=>w.default.exit(y),proc:w.default}):null,p=await new Promise(y=>{k.once("exit",U=>y(U??1)),k.once("error",U=>{l?.(),l=null,Ee(w.default.stderr,`failed to launch ${r}: ${String(U)}
58
+ `),y(127)})});x?.();let S=null;try{c&&await c.close()}catch(y){S=y}finally{l?.(),l=null,m?.(),m=null,g?.end()}return S!==null&&Ee(w.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${p} preserved): ${String(S instanceof Error?S.message:S)}
59
+ `),p}}Oo().then(e=>w.default.exit(e),e=>{w.default.stderr.write(`${String(e instanceof Error?e.message:e)}
60
+ `),w.default.exit(1)});