@urun-sh/openai 0.2.55 → 0.2.57

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