@urun-sh/openai 0.5.2 → 0.5.4

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 (39) hide show
  1. package/dist/chunk-4MSBS7M6.js +1 -0
  2. package/dist/{chunk-G3NMGP4N.js → chunk-GBBY3PCZ.js} +1 -1
  3. package/dist/chunk-K23AZPI4.js +1 -0
  4. package/dist/chunk-OI2OY32M.js +1 -0
  5. package/dist/chunk-RQBD4OAA.js +6 -0
  6. package/dist/{chunk-EWCEZIOX.js → chunk-STFRT5OY.js} +1 -1
  7. package/dist/{chunk-M6ICU4F5.js → chunk-VNM4M4P3.js} +12 -12
  8. package/dist/gemini-live.cjs +2 -2
  9. package/dist/gemini-live.d.cts +6 -0
  10. package/dist/gemini-live.d.ts +6 -0
  11. package/dist/gemini-live.js +1 -1
  12. package/dist/hosted/bin.cjs +16 -16
  13. package/dist/hosted/bin.js +1 -1
  14. package/dist/hosted/index.cjs +16 -16
  15. package/dist/hosted/index.d.cts +94 -13
  16. package/dist/hosted/index.d.ts +44 -11
  17. package/dist/hosted/index.js +1 -1
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.d.cts +2 -18
  20. package/dist/index.d.ts +2 -18
  21. package/dist/index.js +1 -1
  22. package/dist/models-NYMZrklp.d.cts +38 -0
  23. package/dist/models-NYMZrklp.d.ts +38 -0
  24. package/dist/pi-extension/index.cjs +6 -6
  25. package/dist/pi-extension/index.js +1 -1
  26. package/dist/pi-extension/standalone.cjs +50 -50
  27. package/dist/proxy/cli.cjs +31 -31
  28. package/dist/proxy/cli.js +1 -1
  29. package/dist/proxy/index.cjs +13 -13
  30. package/dist/proxy/index.d.cts +1 -1
  31. package/dist/proxy/index.d.ts +1 -1
  32. package/dist/proxy/index.js +1 -1
  33. package/dist/{server-l1himPxc.d.ts → server-DuH_5OD9.d.ts} +2 -0
  34. package/dist/{server-BfME37pQ.d.cts → server-wmUnMewW.d.cts} +6 -0
  35. package/package.json +3 -3
  36. package/dist/chunk-F2TEK34X.js +0 -1
  37. package/dist/chunk-TE6632EU.js +0 -6
  38. package/dist/chunk-UVAY7Q7Z.js +0 -1
  39. package/dist/chunk-XHIIEA6Z.js +0 -1
@@ -1,60 +1,60 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var bn=Object.create;var nt=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var On=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rn(t))!En.call(e,r)&&r!==n&&nt(e,r,{get:()=>t[r],enumerable:!(o=Sn(t,r))||o.enumerable});return e};var te=(e,t,n)=>(n=e!=null?bn(An(e)):{},On(t||!e||!e.__esModule?nt(n,"default",{value:e,enumerable:!0}):n,e));var In=()=>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=In();var et=require("child_process"),Y=require("fs"),kn=te(require("path"),1),_=te(require("process"),1);var le=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 Tn="llm-resp";async function*Ce(e,t){let n=`${Tn}:${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 Pn="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(Pn).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 Cn(){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=Cn(),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 Un(e,n);return await o.startInbound(s),o}function Un(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 $n=24e3,ce=480,Ln=111;async function Nn(){let e=await import("opusscript"),t=e.default??e;return new t($n,1,2048)}async function we(){let e=await import("werift"),t=await Nn();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>=ce;){let l=c.subarray(u,u+ce);u+=ce;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=t.encode(p,ce);r=r+1&65535,s=s+ce>>>0;let h=new e.RtpHeader({version:2,payloadType:Ln,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 Mn="h264";function Dn(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 jn(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;Dn(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=jn(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:Mn,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 Vn(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Bn(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(Bn(l)&&(a=!0),Vn(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 Fn(e,t){return Ne+Buffer.from(JSON.stringify([e,t]),"utf8").toString("base64url")}function Gn(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 Hn=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??Hn;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:Fn(n,this.keyOf(o))}}async sessionForHandle(t){let n=Gn(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 qn=3,Jn="llm",Wn=new Set(["paused","error"]);function yt(e,t){let n=e.doc(Jn),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<qn||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=>{Wn.has(u.name)&&c(new V(`the pooled session for app "${t}" lost its compute binding (phase "${u.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{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 Kn(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,le.App)(t,{baseUrl:n,orgId:o,jwt:s.jwt});return a(wt(p,t,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,le.App)(t,{baseUrl:n,orgId:o,getAccessToken:async()=>(await(0,le.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${t}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(wt(l,t,r))}function Yn(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 zn=new Set(["error","paused"]);function _t(e){let{auth:t,catalog:n}=e,o=null,r=i=>{let a=Kn(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:Yn});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||!zn.has(l.name))return;u=!0;let p=c.endsAt??null;i({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:l.reason??`session ${l.name}`})})}}}var qt=require("http");var jt=require("crypto"),Vt=require("ws");var xt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Qn=1007,bt=1008,W=1011,De=1008,d=class extends Error{constructor(n,o=Qn){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 eo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},to=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",X],kt=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function no(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 oo=["temperature","maxOutputTokens","responseModalities"];function Ot(e){for(let[p,g]of Object.entries(eo))if(e[p]!==void 0)throw new d(g);for(let p of Object.keys(e))if(!to.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(!oo.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:no(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,ro=`audio/pcm;rate=${Ct}`,Ut=Buffer.alloc(960).toString("base64");function so(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 io(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 ao(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=so(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:ao(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:io(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:ro,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 uo=256,je=class{snapshots=new Map;store(t,n){for(this.snapshots.set(t,n);this.snapshots.size>uo;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},de=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,de(t.message));return}if(t instanceof V){this.ws.close(De,de(t.message));return}if(t instanceof d){this.ws.close(t.closeCode,de(t.message));return}this.ws.close(W,de(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,de(`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}}},co=(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
2
+ "use strict";var Tn=Object.create;var ot=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var Un=Object.getOwnPropertyNames;var $n=Object.getPrototypeOf,Nn=Object.prototype.hasOwnProperty;var Ln=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Un(n))!Nn.call(e,r)&&r!==t&&ot(e,r,{get:()=>n[r],enumerable:!(o=Cn(n,r))||o.enumerable});return e};var ne=(e,n,t)=>(t=e!=null?Tn($n(e)):{},Ln(n||!e||!e.__esModule?ot(t,"default",{value:e,enumerable:!0}):t,e));var Mn=()=>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,E=Mn();var tt=require("child_process"),Y=require("fs"),In=ne(require("path"),1),_=ne(require("process"),1);var de=require("@urun-sh/core");async function rt(e){let t=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{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 st(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 it(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.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),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 at(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 Dn="llm-resp";async function*Ue(e,n){let t=`${Dn}:${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 at(i);return}}}var jn="llm",ye=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(jn).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,t){let o=it(n,t,this.consumerId);return this.write(o),Ue(this.session,t)}sendResponseCreate(n,t,o){let r=st(n,t,o,this.consumerId);return this.write(r),Ue(this.session,o)}};var ut=0;function Vn(){return ut+=1,`req_${Date.now().toString(36)}_${ut.toString(36)}`}var we=class{transport;constructor(n){this.transport=new ye(n)}responses={create:async n=>{let t=Vn(),o=this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*o})(),{requestId:t})}}};var $e=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 dt(e,n,t=1e4){let o=new $e(n,{sampleRate:24e3}),r=await o.startOutbound();await e.stream("rt-audio-in").attach(r);let s=await Bn(e,t);return await o.startInbound(s),o}function Bn(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 ct="rt-video-in",lt=256e3;function pt(e){let n=e.stream(ct),t=n.emit;if(typeof t!="function")throw new Error(`enableSessionVideo: session.stream('${ct}') 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>lt)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${lt}-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 Fn=24e3,le=480,Gn=111;async function Hn(){let e=await import("opusscript"),n=e.default??e;return new n(Fn,1,2048)}async function _e(){let e=await import("werift"),n=await Hn();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>=le;){let l=c.subarray(u,u+le);u+=le;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=n.encode(p,le);r=r+1&65535,s=s+le>>>0;let h=new e.RtpHeader({version:2,payloadType:Gn,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),w=new e.RtpPacket(h,g);t.writeRtp(w)}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}}}var ve=require("@urun-sh/core"),Ne="rt-video-out";var qn="h264";function Jn(e,n){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${n}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${n}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${n}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${n}: header key must be a boolean`)}function Wn(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let n=e[0]|e[1]<<8;if(e.byteLength<2+n)throw new Error(`decodeVideoOutRecord: truncated record (header says ${n} bytes, ${e.byteLength-2} present)`);let t;try{t=JSON.parse(new TextDecoder().decode(e.subarray(2,2+n)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let o=t;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;Jn(r,"decodeVideoOutRecord");let s=e.subarray(2+n);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 ft="urun.videoOut.v2-ws";function mt(e){let n=e.stream(Ne);if(typeof n.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Ne}') 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 t=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 n.messages()){if(!(c instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Ne}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Wn(c)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of t)l(u)}for(let c of r)c()};return{codec:qn,onOutputFrame:c=>(t.add(c),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>t.delete(c)),onLaneError:c=>(o.add(c),()=>o.delete(c)),onEnd:c=>(r.add(c),()=>r.delete(c))}}function Kn(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function Yn(e){let n=e?.type;return n==="response.completed"||n==="error"}function gt(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(Yn(l)&&(a=!0),Kn(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}})()}}function X(e){return e.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var zn={chat:!0,code:!0,agent:!0,vl:!0},ht={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Xn(e){let n=e.toLowerCase();return Object.hasOwn(ht,n)?ht[n]:null}function Le(e){let n=e.engine_args?.context_length;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:null}function wt(e,n){let t=n.filter(s=>X(`${s.model_id}-${s.variant}`)===e);if(t.length===1)return t[0];if(t.length>1)return yt(t);let o=n.filter(s=>X(s.model_id)===e),r=new Set(o.map(s=>s.variant));return o.length>0&&r.size===1?yt(o):null}function yt(e){let n=e[0],t=i=>e.every(a=>(a[i]??void 0)===(n[i]??void 0))?n[i]:void 0,o=e.map(Le),r=o[0],s=r!=null&&o.every(i=>i===r)?r:null;return{model_id:n.model_id,variant:n.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),engine_args:s!==null?{context_length:s}:{},updated_at:t("updated_at")}}function _t(e){let n=e.updated_at?Date.parse(e.updated_at):NaN;return Number.isFinite(n)?Math.floor(n/1e3):0}function vt(e,n){let t=wt(e,n);if(!t)return{id:e,object:"model",created:0,owned_by:"urun"};let o=Le(t);return{id:e,object:"model",created:_t(t),owned_by:"urun",name:`${t.model_id}:${t.variant}`,...t.description?{description:t.description}:{},...t.task?{task:t.task}:{},...t.engine?{engine:t.engine}:{},...t.gpu_spec?{gpu_spec:t.gpu_spec}:{},...o!==null?{context_length:o}:{}}}function kt(e,n){let t=[];for(let o of e){let r=wt(o,n);if(!r||!r.task||zn[r.task]!==!0)continue;let s=Le(r),i={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};s!==null&&(i.max_tokens={type:"integer",min:1,max:s,unit:"token"}),t.push({schema_version:"2.4",id:o,name:`${r.model_id}:${r.variant}`,created:_t(r),quantization:Xn(r.variant),description:r.description??"",hugging_face_id:r.hf_repo?r.hf_repo.split("@")[0]??r.hf_repo:"",input_modalities:[{type:"text",...s!==null?{supported_inputs:{max_context_length:{value:s,unit:"token"}}}:{}},...r.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:i}]})}return{data:t}}var bt="https://api.urun.sh/v1",N=class extends Error{},V=class extends Error{},Me="urs1.";function Qn(e,n){return Me+Buffer.from(JSON.stringify([e,n]),"utf8").toString("base64url")}function Zn(e){if(!e.startsWith(Me))return null;try{let n=JSON.parse(Buffer.from(e.slice(Me.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 St(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 xt=6e4,ke=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;rowsCache=null;seed(n,t){this.pool.set(n,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??xt;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}async catalogRows(){if(!this.opts.listCatalog)return[];let n=this.opts.appsTtlMs??xt;if(this.rowsCache&&Date.now()-this.rowsCache.at<n)return this.rowsCache.rows;let t=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows: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=X(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===X(a.model_id)||r===X(`${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:Qn(t,this.keyOf(o))}}async sessionForHandle(n){let t=Zn(n);if(!t)throw new V(`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 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(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(){let n=await this.availableIds(),t=await this.catalogRows().catch(()=>[]);return{object:"list",data:n.map(o=>vt(o,t))}}async openRouterModels(){let n=await this.availableIds(),t=await this.catalogRows();return kt(n,t)}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 eo=3,to="llm",no=new Set(["paused","error"]);function Rt(e,n){let t=e.doc(to),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<eo||c(new V(`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=>{no.has(u.name)&&c(new V(`the pooled session for app "${n}" lost its compute binding (phase "${u.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{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*De(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 At(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 oo(e,n){let{baseUrl:t,orgId:o,fnName:r,auth:s,subject:i}=e,a=p=>({session:p,responses:new we(p),gone:Rt(p,n)});if(s.lane==="jwt"){let p=(0,de.App)(n,{baseUrl:t,orgId:o,jwt:s.jwt});return a(At(p,n,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,de.App)(n,{baseUrl:t,orgId:o,getAccessToken:async()=>(await(0,de.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${n}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(At(l,n,r))}function ro(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 so=new Set(["error","paused"]);function Et(e){let{auth:n,catalog:t}=e,o=null,r=i=>{let a=oo(e,i);return a.gone.onGone(()=>{o?.evict(i,a)}),a},s=new ke({defaultApp:e.defaultApp,fnName:e.fnName,openSession:r,closeSession:async i=>{i.gone.dispose(),await i.session.end()},listApps:n.lane==="api-key"?()=>St({apiUrl:e.apiUrl,apiKey:n.apiKey}):null,listCatalog:t?()=>rt(t):null,sessionKey:ro});return o=s,e.defaultApp!==null&&s.seed(e.defaultApp,r(e.defaultApp)),s}function Ot(e,n=_e){let t=new WeakMap,o=new WeakMap,r=new WeakMap;return{createResponse:gt({sessionFor:s=>e.sessionFor(s),evict:(s,i)=>e.evict(s,i),createStream:async(s,i)=>De(await s.responses.responses.create(i),s.gone)}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),openAudio:async s=>{let{entry:i}=await e.sessionFor(s),a=t.get(i);return a||(a=(async()=>dt(i.session,await n()))(),t.set(i,a),a.catch(()=>t.delete(i))),a},openVideo:async s=>{let{entry:i}=await e.sessionFor(s),a=o.get(i);return a||(a=pt(i.session),o.set(i,a)),a},openVideoOut:async s=>{let{entry:i}=await e.sessionFor(s),a=r.get(i);return a||(a=mt(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 De(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||!so.has(l.name))return;u=!0;let p=c.endsAt??null;i({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:l.reason??`session ${l.name}`})})}}}var Zt=require("http");var Wt=require("crypto"),Kt=require("ws");var Pt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ao=1007,Tt=1008,W=1011,je=1008,d=class extends Error{constructor(t,o=ao){super(t);this.closeCode=o}closeCode},O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,xe=["setup","clientContent","realtimeInput","toolResponse"];function Ct(e){let n;try{n=JSON.parse(e)}catch{throw new d("client message is not valid JSON")}let t=O(n);if(!t)throw new d("client message must be a JSON object");let o=xe.filter(a=>t[a]!==void 0),r=Object.keys(t).filter(a=>!xe.includes(a));if(r.length>0)throw new d(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${xe.join(", ")}`);if(o.length!==1)throw new d(`client message must contain exactly one of ${xe.join(", ")} (got ${o.length})`);let s=o[0],i=O(t[s]);if(!i)throw new d(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ut(e,n){if(typeof e=="string")return e;let t=O(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=O(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 uo={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Q="urun.videoOut";function $t(e){return{framing:ft,codec:e}}function Nt(e){let{seq:n,ptsUs:t,codec:o,key:r}=e.header;return{[Q]:{v:1,seq:n,ptsUs:t,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var co={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},lo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Q],It=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function po(e){let n=O(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=O(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(!It.includes(n.activityHandling))throw new d(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${It.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var fo=["temperature","maxOutputTokens","responseModalities"];function Lt(e){for(let[p,g]of Object.entries(co))if(e[p]!==void 0)throw new d(g);for(let p of Object.keys(e))if(!lo.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 n=e.model.replace(/^models\//,""),t,o,r=!1,s=O(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(!fo.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");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 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:Ut(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=O(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=O(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=O(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?uo:po(e.realtimeInputConfig),l=!1;if(e[Q]!==void 0){if(!O(e[Q]))throw new d(`setup["${Q}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:n,systemItems:i,tools:a,temperature:t,maxOutputTokens:o,audioModality:r,activity:u,sessionResumption:c,videoOut:l}}function Mt(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function Dt(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function jt(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=O(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:Ut(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var be=16e3,Vt=24e3,mo=`audio/pcm;rate=${Vt}`,Bt=Buffer.alloc(960).toString("base64");function go(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 ho(e){let n=O(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 yo(e){let n=O(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])!==be)throw new d(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${be} Hz (audio/pcm;rate=${be})`);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=go(r,be,Vt);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ft(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=O(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:yo(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:ho(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 Gt(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=O(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 Ht(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function qt(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:mo,data:e}}]}}}}function Jt(e){let n=O(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=O(u);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let p of l.content){let g=O(p);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=O(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=O(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 wo=256,Ve=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>wo;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},pe=e=>e.slice(0,120),Be=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?.(),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(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof N){this.ws.close(Tt,pe(n.message));return}if(n instanceof V){this.ws.close(je,pe(n.message));return}if(n instanceof d){this.ws.close(n.closeCode,pe(n.message));return}this.ws.close(W,pe(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=Ct(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}=jt(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=Ft(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:Bt);return}this.transcript.push(...Gt(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=Lt(n),o=t.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",je);if(s.model!==t.model)throw new d(`sessionResumption.handle was issued for model "${s.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=[...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(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...t.systemItems);this.config=t;let r={};if(t.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,t.model),a=i.onOutputFrame(u=>this.send(Nt(u))),c=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),c()},r[Q]=$t(i.codec)}}this.send({setupComplete:r}),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)",W);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(qt(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)",W);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,Wt.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(Mt(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(Dt(n.timeLeftMs)),this.ws.close(W,pe(`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)}`,W);if(u.type==="response.completed"){r=u.response,s=!0;continue}let l=Ht(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",W);let{messages:i,assistantItems:a}=Jt(r);this.transcript.push(...a);for(let c of i)this.send(c);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},_o=(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 Yt(e,n){let t=new Kt.WebSocketServer({noServer:!0}),o=new Ve;e.on("upgrade",(r,s,i)=>{let a=new URL(r.url??"/","http://localhost");if(a.pathname!==Pt){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(t.apiKey&&co(r,a)!==t.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
6
+ no WS route for ${a.pathname}`),s.destroy();return}if(n.apiKey&&_o(r,a)!==n.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
7
7
  Connection: close\r
8
8
  \r
9
- invalid local proxy api key`),s.destroy();return}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>=lo?"(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 lo=256,po=128;function We(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,po)}var Ft=64*1024*1024,be=class extends Error{};async function fo(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 mo=256;function go(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=go(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<=mo)break;this.conversations.delete(r)}}};function pe(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 fe(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}))}},ho=["<tool_call>","<function="];function yo(e){return ho.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 yo(n)}function wo(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 _o(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 vo(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:_o(n.role,n.content)})}return t}function Be(e){return pe(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 ko(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")}
9
+ invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,c=>{new Be(c,n.clients,o)})})}var He=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>=vo?"(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 Je(e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function B(e,n,t){e.writeHead(n,{"content-type":"application/json"}),e.end(JSON.stringify(t))}function K(e,n,t,o="invalid_request_error"){B(e,n,{error:{message:t,type:o}})}function H(e,n,t,o){B(e,n,{type:"error",error:{type:t,message:o}})}function We(e,n,t){if(n==="anthropic"){B(e,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}B(e,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var vo=256,ko=128;function Ke(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,ko)}var zt=64*1024*1024,Se=class extends Error{};async function xo(e){let n=[],t=0;for await(let r of e){if(t+=r.length,t>zt)throw new Se(`request body exceeds ${zt} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function oe(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 bo=256;function So(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 qe=class{conversations=new Map;thread(n,t){let o=So(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<=bo)break;this.conversations.delete(r)}}};function fe(e){let n=e?.output;return Array.isArray(n)?n.filter(t=>t.type==="function_call"):[]}function Z(e){return e.find(n=>n.type==="response.completed")?.response??null}function Re(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 Xt(e){let n=Re(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 en(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 me(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 ee=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}))}},Ro=["<tool_call>","<function="];function Ao(e){return Ro.find(n=>e.includes(n))}function re(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 se(e,n,t){if(!(!e||n>0))return Ao(t)}function Eo(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 Ae=class extends Error{};function Oo(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 Ae(`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:Oo(t.role,t.content)})}return n}function Fe(e){return fe(e).map((n,t)=>({index:t,id:n.call_id??n.id??`call_${t}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function Qt(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 Po(e,n,t,o,r){let s=e.stream===!0,i;try{i=t.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=Ke(e);r.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,p;try{p=await n.createResponse({model:e.model,input:i,stream:s,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,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 N){We(o,"openai",f);return}throw f}let g=[];if(s){Je(o);let f=v=>{o.write(`event: ${String(v.type??"message")}
10
10
  data: ${JSON.stringify(v)}
11
11
 
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,ie=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}})},ae=!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:fe(v);if(P){if(R(),F(),q("completed"),J.add(P),P.tool_index!==ee){ie("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=pe(v.response),C=re(l,J.size+k.length,T);if(C){ae=!0,f({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:oe(u,C)}});break}F(),q("completed"),ie("completed"),J.size===0&&k.forEach(z=>{let ue=m++,ge=z.id??z.call_id??`fc_${ue}`,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:ue,item:{...tt,arguments:"",status:"in_progress"}}),f({type:"response.function_call_arguments.delta",item_id:ge,output_index:ue,delta:Pe}),f({type:"response.function_call_arguments.done",item_id:ge,output_index:ue,arguments:Pe}),f({type:"response.output_item.done",output_index:ue,item:{...tt,arguments:Pe,status:"completed"}})}),f(b(v));continue}f(b(v))}F(),q("incomplete"),ie("incomplete"),c&&!ae&&n.remember(a,i,Ht(g,Q(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)}`,L=!1,D=!1,m=0,R=()=>{L||(L=!0,f({type:"response.created",response:{id:a,object:"response",status:"in_progress"}}))},F=!1,$=0,j="",G=()=>{F&&(F=!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,P="",q=v=>{M&&(M=!1,f({type:"response.output_text.done",item_id:y,output_index:S,content_index:0,text:P}),f({type:"response.content_part.done",item_id:y,output_index:S,content_index:0,part:{type:"output_text",text:P}}),f({type:"response.output_item.done",output_index:S,item:{id:y,type:"message",role:"assistant",status:v,content:[{type:"output_text",text:P}]}}))},J=new ee,A=null,te=-1,ae=v=>{if(!A)return;let I=A;A=null,f({type:"response.function_call_arguments.done",item_id:I.fcId,output_index:I.outputIndex,arguments:I.args}),f({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:v}})},ue=!1;for await(let v of r.track(p,u)){g.push(v);let I=String(v.type??"");if(I==="response.created"||I==="response.in_progress"){L=!0,f(b(v));continue}if(I==="response.output_item.added"){D=!0,f(b(v));continue}if(I==="response.reasoning_text.delta"&&!D){R(),F||(F=!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(I==="response.output_text.delta"&&!D){R(),G(),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:""}})),P+=String(v.delta??""),f({type:I,item_id:y,output_index:S,content_index:0,delta:v.delta});continue}let T=D?null:me(v);if(T){if(R(),G(),q("completed"),J.add(T),T.tool_index!==te){ae("completed"),te=T.tool_index;let k=m++;A={fcId:`fc_${a.slice(5)}_${T.tool_index}`,outputIndex:k,callId:T.call_id,name:T.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&&(T.call_id&&(A.callId=T.call_id),T.name&&(A.name=T.name),A.args+=T.delta,f({type:"response.function_call_arguments.delta",item_id:A.fcId,output_index:A.outputIndex,delta:T.delta}));continue}if(I==="response.completed"&&!D){let k=fe(v.response),C=se(l,J.size+k.length,P);if(C){ue=!0,f({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:re(u,C)}});break}G(),q("completed"),ae("completed"),J.size===0&&k.forEach(z=>{let ce=m++,he=z.id??z.call_id??`fc_${ce}`,Ce=z.arguments??"",nt={id:he,type:"function_call",call_id:z.call_id??he,name:z.name??""};f({type:"response.output_item.added",output_index:ce,item:{...nt,arguments:"",status:"in_progress"}}),f({type:"response.function_call_arguments.delta",item_id:he,output_index:ce,delta:Ce}),f({type:"response.function_call_arguments.done",item_id:he,output_index:ce,arguments:Ce}),f({type:"response.output_item.done",output_index:ce,item:{...nt,arguments:Ce,status:"completed"}})}),f(b(v));continue}f(b(v))}G(),q("incomplete"),ae("incomplete"),c&&!ue&&t.remember(a,i,Qt(g,Z(g))),o.write(`data: [DONE]
13
13
 
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,pe(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 xo(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=vo(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:wo(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))}
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=Qt(g,h),x=se(l,fe(h).length,w);if(x){K(o,502,re(u,x),"upstream_error");return}c&&t.remember(a,i,w),B(o,200,{...h,id:a})}async function To(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){K(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(m){if(m instanceof Ae){K(t,400,m.message);return}throw m}let c=Ke(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:Eo(e.tools),tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,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 N){We(t,"openai",m);return}throw m}if(e.stream===!0){Je(t);let m=[],R=new ee,F="";t.write(`data: ${JSON.stringify(oe(i,s,{role:"assistant"},null))}
15
15
 
16
- `);for await(let S of o.track(l,c)){m.push(S);let T=fe(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))}
16
+ `);for await(let S of o.track(l,c)){m.push(S);let P=me(S);if(S.type==="response.output_text.delta"&&typeof S.delta=="string")F+=S.delta,t.write(`data: ${JSON.stringify(oe(i,s,{content:S.delta},null))}
17
17
 
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))}
18
+ `);else if(S.type==="response.reasoning_text.delta"&&typeof S.delta=="string")t.write(`data: ${JSON.stringify(oe(i,s,{reasoning_content:S.delta},null))}
19
19
 
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))}
20
+ `);else if(P){let{call:q,isNew:J}=R.add(P),A=J?{index:P.tool_index,id:q.id??`call_${P.tool_index}`,type:"function",function:{name:q.name??"",arguments:P.delta}}:{index:P.tool_index,function:{arguments:P.delta}};t.write(`data: ${JSON.stringify(oe(i,s,{tool_calls:[A]},null))}
21
21
 
22
- `)}else if(S.type==="error"){n.write(`data: ${JSON.stringify({error:S})}
22
+ `)}else if(S.type==="error"){t.write(`data: ${JSON.stringify({error:S})}
23
23
 
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)}})}
24
+ `),t.end();return}}let $=Fe(Z(m)),j=se(u,R.size+$.length,F);if(j){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:re(c,j)}})}
25
25
 
26
- `),n.end();return}R.size===0&&$.length>0&&n.write(`data: ${JSON.stringify(ne(i,s,{tool_calls:$},null))}
26
+ `),t.end();return}R.size===0&&$.length>0&&t.write(`data: ${JSON.stringify(oe(i,s,{tool_calls:$},null))}
27
27
 
28
- `);let F=R.size>0||$.length>0;n.write(`data: ${JSON.stringify(ne(i,s,{},F?"tool_calls":"stop"))}
28
+ `);let G=R.size>0||$.length>0;t.write(`data: ${JSON.stringify(oe(i,s,{},G?"tool_calls":"stop"))}
29
29
 
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))})}
30
+ `),Re(Z(m))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:Xt(Z(m))})}
31
31
 
32
- `),n.write(`data: [DONE]
32
+ `),t.write(`data: [DONE]
33
33
 
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=fe(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 bo(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>String(t.text??"")).join(""):""}var me=class extends Error{};function Ae(e){return new me(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function So(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 Ro(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 me(`unsupported anthropic tool_choice type ${JSON.stringify(String(t))} \u2014 the proxy maps auto, none, any and tool`)}function Ao(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 Eo(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:Ao(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ae(a)}}return s(),o}function Fe(e){return pe(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 Oo(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:bo(e.system)});for(let m of r)a.push(...Eo(m));c=Ro(e.tool_choice)}catch(m){if(m instanceof me){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:So(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}
34
+ `),t.end();return}let p="",g="",h=[],w=new ee;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=me(m);if(R&&w.add(R),m.type==="error"){K(t,502,JSON.stringify(m),"upstream_error");return}}let x=Z(h),f=Fe(x),b=f.length>0?f:Fe({output:w.items()}),y=se(u,b.length,p);if(y){K(t,502,re(c,y),"upstream_error");return}let U=b.map(({index:m,...R})=>R),L={role:"assistant",content:p||null},D=g||en(x);D&&(L.reasoning_content=D),U.length>0&&(L.tool_calls=U),B(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:Xt(x)})}function Co(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var ge=class extends Error{};function Ee(e){return new ge(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Uo(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 $o(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 ge(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function No(e){if(typeof e=="string")return e;if(e==null)return"";if(!Array.isArray(e))throw Ee(typeof e);let n="";for(let t of e){let o=String(t.type??"");if(o!=="text")throw Ee(`tool_result > ${o}`);n+=String(t.text??"")}return n}function Lo(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 Ee(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:No(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ee(a)}}return s(),o}function Ge(e){return fe(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 Mo(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(m=>typeof m!="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:Co(e.system)});for(let m of r)a.push(...Lo(m));c=$o(e.tool_choice)}catch(m){if(m instanceof ge){H(t,400,"invalid_request_error",m.message);return}throw m}let u=Ke(e);o.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,p;try{p=await n.createResponse({model:e.model,input:a,stream:!0,tools:Uo(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 N){We(t,"anthropic",m);return}throw m}let g=(m,R)=>{t.destroyed||t.write(`event: ${m}
35
35
  data: ${JSON.stringify({type:m,...R})}
36
36
 
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=fe(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),ie=pe(ee),ae=re(l,T.size+ie.length,B);if(ae){g("error",{error:{type:"api_error",message:oe(u,ae)}}),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=fe(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 Io(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 fo(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 ko(x,w,a(w),l,c);return}if(p.pathname==="/v1/chat/completions"){c.request("chat_completions",f,f),await xo(x,w,l,c);return}if(p.pathname==="/v1/messages"){c.request("messages",f,f),await Oo(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
37
+ `)};if(e.stream===!0){let m=o.track(p,u);Je(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 R=0,F="",$=0,j="none",G=()=>j,M=-1,S=-1,P=new ee,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(t.destroyed)break;q.push(k);let C=me(k);if(k.type==="response.reasoning_text.delta"&&typeof k.delta=="string")G()!=="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")G()!=="text"&&A("text",{type:"text",text:""}),R+=1,F+=k.delta,g("content_block_delta",{index:M,delta:{type:"text_delta",text:k.delta}});else if(C){let{call:z}=P.add(C);(G()!=="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)}}),t.end();return}}if(t.destroyed)return;let te=Z(q),ae=fe(te),ue=se(l,P.size+ae.length,F);if(ue){g("error",{error:{type:"api_error",message:re(u,ue)}}),t.end();return}J();let v=[];if(P.size===0)try{v=Ge(te)}catch(k){g("error",{error:{type:"api_error",message:String(k instanceof Error?k.message:k)}}),t.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 I=P.size>0||v.length>0,T=Re(te);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:R}}),g("message_stop",{}),t.end();return}let h="",w="",x=[],f=new ee;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=me(m);if(R&&f.add(R),m.type==="error"){H(t,502,"api_error",JSON.stringify(m));return}if(t.destroyed)break}if(t.destroyed)return;let b=Z(x),y;try{y=Ge(b),y.length===0&&f.size>0&&(y=Ge({output:f.items()}))}catch(m){H(t,502,"api_error",String(m instanceof Error?m.message:m));return}let U=se(l,y.length,h);if(U){H(t,502,"api_error",re(u,U));return}let L=[],D=w||en(b);D&&L.push({type:"thinking",thinking:D}),(h||y.length===0)&&L.push({type:"text",text:h}),L.push(...y),B(t,200,{id:i,type:"message",role:"assistant",content:L,model:s,stop_reason:y.length>0?"tool_use":"end_turn",usage:Re(b)??{input_tokens:0,output_tokens:0}})}function Do(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 qe,i.set(u,l)),l},c=new He;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?H(l,w,b,x):K(l,w,x,f);(async()=>{if(u.method==="GET"&&p.pathname==="/healthz"){B(l,200,{ok:!0});return}if(u.method==="GET"&&p.pathname==="/stats"){B(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 w=await s(u);if(u.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){if(!w.openRouterModels){h(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}B(l,200,await w.openRouterModels());return}B(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 xo(u)}catch(b){if(b instanceof Se){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 Po(x,w,a(w),l,c);return}if(p.pathname==="/v1/chat/completions"){c.request("chat_completions",f,f),await To(x,w,l,c);return}if(p.pathname==="/v1/messages"){c.request("messages",f,f),await Mo(x,w,l,c);return}if(p.pathname==="/v1/messages/count_tokens"){c.request("count_tokens",f,f),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 ${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 Wt(e){let{clients:t,apiKey:n}=e,o=(0,qt.createServer)(Io(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.5.2";var Zt=4141,Po=Kt,Oe={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",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){return t.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function rn(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 sn(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 an(e){if(e[0]!=="--port")return null;let t=sn(e[1]);return e.splice(0,2),t}function Xe(e){let t=e.indexOf("--port");if(t===-1)return Zt;let n=sn(e[t+1]);return e.splice(t,2),n}function un(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 se(e){let t=Co(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 Co(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:Po}}function Uo(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 $o=250;async function Ze(e,t=$o){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 cn=2e3;async function Lo(e,t=cn){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 ln(e,t,n=Zt,o=cn){if(e!=null)return{mode:"spawn",port:e};let r=await Ze(n);if(r!==null&&Uo(r,t)){let s=await Lo(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 dn(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 pn(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 No=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function fn(e){let t=e?.code;return typeof t=="string"&&No.has(t)}function Ie(e,t){try{return e.write(t),!0}catch(n){if(fn(n))return!1;throw n}}function mn(e){let t={stdout:!1,stderr:!1},n=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{fn(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 gn(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}
42
+ `)),l.end()})}}function tn(e){let{clients:n,apiKey:t}=e,o=(0,Zt.createServer)(Do(e));return Yt(o,{clients:n,apiKey:t}),o}var on=ne(require("os"),1),rn=ne(require("path"),1),sn=require("url"),an=require("util");var nn="0.5.4";var un=4141,Vo=nn,Ie={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function Xe(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 cn(e,n,t){let o={...e,...Xe(n,t)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function ln(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 dn(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function pn(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--model",`urun/${e}`,...n]}function fn(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,sn.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 mn(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 gn(e){if(e[0]!=="--port")return null;let n=mn(e[1]);return e.splice(0,2),n}function Qe(e){let n=e.indexOf("--port");if(n===-1)return un;let t=mn(e[n+1]);return e.splice(n,2),t}function hn(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 Ye(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 ie(e){let n=Bo(Ye(e,"URUN_BASE_URL")),t=Ye(e,"URUN_ORG_ID"),o=Ye(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Oe(s,"URUN_API_URL"):bt,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?Oe(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 Bo(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 Oe(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 Ze(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Vo}}function Fo(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var Go=250;async function et(e,n=Go){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 yn=2e3;async function Ho(e,n=yn){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 wn(e,n,t=un,o=yn){if(e!=null)return{mode:"spawn",port:e};let r=await et(t);if(r!==null&&Fo(r,n)){let s=await Ho(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 _n(e,n=on.default.homedir()){return rn.default.join(n,".urun","logs",`compat-proxy-${e}.log`)}var ze=["log","info","warn","error","debug","trace"];function vn(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(ze.map(a=>[a,t[a]]));for(let a of ze)t[a]=(...c)=>{e.write(`${(0,an.format)(...c)}
43
+ `)};return()=>{n.stdout.write=o,n.stderr.write=r;for(let a of ze)t[a]=i[a]}}var qo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function kn(e){let n=e?.code;return typeof n=="string"&&qo.has(n)}function Pe(e,n){try{return e.write(n),!0}catch(t){if(kn(t))return!1;throw t}}function xn(e){let n={stdout:!1,stderr:!1},t=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{kn(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 bn(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}
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",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function hn(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 Mo={ensureWebRTC:Te.ensureNodeWebRTC,webrtcUnavailableReason:Te.nodeWebRTCUnavailableReason,audioBackend:we};async function yn(e=Mo){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 Do(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 jo(e){return _t({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:Do(_.default.env,t=>_.default.stderr.write(t))})}async function wn(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 _n(){return rn(_.default.env,I,Y.existsSync)}function xn(e){for(let[t,n]of Object.entries(ze(e)))_.default.stdout.write(`export ${t}=${n}
50
- `)}async function vn(e,t){let n=se(_.default.env),o=t?Qe(n):void 0,r=jo(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(hn(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
- `),xn(i)),{port:i,close:async()=>{let a=new Promise(c=>s.close(()=>c()));s.closeAllConnections(),await a,await r.closeAll()}}}async function Vo(){let e=_.default.argv.slice(2),t=an(e),n=e.shift()??"proxy";if(n==="env")return xn(un(t??Xe(e))),0;if(n==="selftest"){let{ok:r,reason:s}=await yn();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
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 Sn(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 Te=require("@urun-sh/core/internal");var Jo={ensureWebRTC:Te.ensureNodeWebRTC,webrtcUnavailableReason:Te.nodeWebRTCUnavailableReason,audioBackend:_e};async function Rn(e=Jo){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 Wo(e,n){let t=(e.URUN_CATALOG_URL??"").trim(),o=t?Oe(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 Ko(e){return Et({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:Wo(_.default.env,n=>_.default.stderr.write(n))})}async function An(e,n,t){let o=(0,tt.spawn)(e,n,{stdio:"inherit",env:t});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 En(){return fn(_.default.env,E,Y.existsSync)}function Pn(e){for(let[n,t]of Object.entries(Xe(e)))_.default.stdout.write(`export ${n}=${t}
50
+ `)}async function On(e,n){let t=ie(_.default.env),o=n?Ze(t):void 0,r=Ko(t),s=tn({clients:Ot(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(Sn(e,await et(e))):a}let i=s.address().port;return n&&(_.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 Yo(){let e=_.default.argv.slice(2),n=gn(e),t=e.shift()??"proxy";if(t==="env")return Pn(hn(n??Qe(e))),0;if(t==="selftest"){let{ok:r,reason:s}=await Rn();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
52
  `),0):(_.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
53
- `),1)}if(n==="proxy"){let r=t??Xe(e),s=await vn(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=se(_.default.env);return wn("pi",["-e",_n(),...nn(y.appId,e)],_.default.env)}if(o==="omp"){let y=se(_.default.env);return wn("omp",["-e",_n(),...on(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 ln(t,Qe(se(_.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})
53
+ `),1)}if(t==="proxy"){let r=n??Qe(e),s=await On(r,!0);return await new Promise(i=>{_.default.once("SIGINT",i),_.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(Ie).join("|")}) or \`-- <cmd>\``);if(o==="pi"){let y=ie(_.default.env);return An("pi",["-e",En(),...dn(y.appId,e)],_.default.env)}if(o==="omp"){let y=ie(_.default.env);return An("omp",["-e",En(),...pn(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=Ie[o];if(!y)throw new Error(`unknown command/agent ${o}; commands: proxy | env; agents: ${Object.keys(Ie).join(" | ")} \u2014 or \`-- <cmd>\``);r=y.bin,s=[...y.args??[],...e],i=y.env}let a=await wn(n,Ze(ie(_.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
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 vn(a.port,!1),u=c.port,h=dn(u),(0,Y.mkdirSync)(kn.default.dirname(h),{recursive:!0}),g=(0,Y.createWriteStream)(h,{flags:"a"}),p=mn({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
55
+ `);let l=null,p=null,g=null,h=null;a.mode!=="reuse"&&(c=await On(a.port,!1),u=c.port,h=_n(u),(0,Y.mkdirSync)(In.default.dirname(h),{recursive:!0}),g=(0,Y.createWriteStream)(h,{flags:"a"}),p=xn({streams:_.default,note:y=>(0,Y.appendFileSync)(h,y)}).uninstall,g.on("error",y=>{l?.(),l=null,Pe(_.default.stderr,`urun compat: proxy log ${h} failed: ${String(y)} \u2014 proxy output continues on the terminal
56
56
  `)}),_.default.stdout.write(`urun openai proxy on http://127.0.0.1:${u}/v1 \u2014 proxy logs: ${h}
57
- `),l=pn(g)),o==="codex"&&(s=tn(u,se(_.default.env).appId,s));let w=(0,et.spawn)(r,s,{stdio:"inherit",env:en(_.default.env,u,i)}),x=h!==null?gn({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}}Vo().then(e=>_.default.exit(e),e=>{_.default.stderr.write(`${String(e instanceof Error?e.message:e)}
57
+ `),l=vn(g)),o==="codex"&&(s=ln(u,ie(_.default.env).appId,s));let w=(0,tt.spawn)(r,s,{stdio:"inherit",env:cn(_.default.env,u,i)}),x=h!==null?bn({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,Pe(_.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&&Pe(_.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}}Yo().then(e=>_.default.exit(e),e=>{_.default.stderr.write(`${String(e instanceof Error?e.message:e)}
60
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 L,h as O,i as I,j as G,k as E,l as _,m,o as W,p as A,q as j,r as B,s as D,t as K,u as v,v as M,w as F,x as J}from"../chunk-TE6632EU.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 w}from"../chunk-YSFSRI3D.js";w();import{spawn as Q}from"child_process";import{appendFileSync as H,createWriteStream as ae,existsSync as ie,mkdirSync as se}from"fs";import le from"path";import t from"process";w();import{ensureNodeWebRTC as re,nodeWebRTCUnavailableReason as ne}from"@urun-sh/core/internal";var oe={ensureWebRTC:re,webrtcUnavailableReason:ne,audioBackend:R};async function Y(e=oe){try{await e.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}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(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function ue(e,i){let n=(e.URUN_CATALOG_URL??"").trim(),l=n?W(n,"URUN_CATALOG_URL"):"",o=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!o?(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 L,h as O,i as I,j as G,k as E,l as _,m,o as W,p as A,q as j,r as B,s as D,t as K,u as v,v as M,w as F,x as J}from"../chunk-RQBD4OAA.js";import"../chunk-K23AZPI4.js";import{b as T}from"../chunk-VNM4M4P3.js";import"../chunk-GBBY3PCZ.js";import"../chunk-4MSBS7M6.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-OI2OY32M.js";import{c as w}from"../chunk-YSFSRI3D.js";w();import{spawn as Q}from"child_process";import{appendFileSync as H,createWriteStream as ae,existsSync as ie,mkdirSync as se}from"fs";import le from"path";import t from"process";w();import{ensureNodeWebRTC as re,nodeWebRTCUnavailableReason as ne}from"@urun-sh/core/internal";var oe={ensureWebRTC:re,webrtcUnavailableReason:ne,audioBackend:R};async function Y(e=oe){try{await e.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}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(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function ue(e,i){let n=(e.URUN_CATALOG_URL??"").trim(),l=n?W(n,"URUN_CATALOG_URL"):"",o=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!o?(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:o}}function ce(e){return k({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:ue(t.env,i=>t.stderr.write(i))})}async function V(e,i,n){let l=Q(e,i,{stdio:"inherit",env:n});return new Promise(o=>{l.once("exit",a=>o(a??1)),l.once("error",a=>{t.stderr.write(`failed to launch ${e}: ${String(a)}
4
4
  `),o(127)})})}function q(){return I(t.env,import.meta.url,ie)}function X(e){for(let[i,n]of Object.entries(C(e)))t.stdout.write(`export ${i}=${n}
5
5
  `)}async function z(e,i){let n=m(t.env),l=i?A(n):void 0,o=ce(n),a=T({clients:$(o),identity:l});try{await new Promise((s,d)=>{a.once("error",d),a.listen(e,"127.0.0.1",s)})}catch(s){throw await o.closeAll().catch(()=>{}),s.code==="EADDRINUSE"?new Error(J(e,await j(e))):s}let u=a.address().port;return i&&(t.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1