@urun-sh/openai 0.2.55 → 0.2.56

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.
@@ -25,7 +25,7 @@ data: ${JSON.stringify(g)}
25
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
26
  data: ${JSON.stringify({type:l,...k})}
27
27
 
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)}
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.56";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
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
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}
31
31
  `)}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}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
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)}
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.56";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
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
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}
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}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.2.55",
3
+ "version": "0.2.56",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",