@urun-sh/openai 0.3.0 → 0.3.2

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