@urun-sh/openai 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,7 +39,7 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:x}})}
39
39
 
40
40
  `):l.write(`data: ${JSON.stringify({error:{message:x,type:"upstream_error"}})}
41
41
 
42
- `)),l.end()})}}function Wt(e){let{clients:t,apiKey:n}=e,o=(0,qt.createServer)(Ao(e));return Bt(o,{clients:t,apiKey:n}),o}var Yt=te(require("os"),1),zt=te(require("path"),1),Xt=require("url"),Qt=require("util");var Kt="0.3.1";var Zt=4141,Oo=Kt,Oe={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ze(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function en(e,t,n){let o={...e,...ze(t,n)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function tn(e,t,n){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=n.indexOf("--"),s=r===-1?n:n.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",c=s.includes("--skip-git-repo-check"),u=a&&!c?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...o,...i?[]:["-m",t],...u]}function nn(e,t){return t.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function on(e,t,n){let o=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!n(o))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${o}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return o}let r=(0,Xt.fileURLToPath)(new URL("../pi-extension/standalone.cjs",t));if(!n(r))throw new Error(`pi extension entry not found at ${r} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return r}function rn(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function sn(e){if(e[0]!=="--port")return null;let t=rn(e[1]);return e.splice(0,2),t}function Xe(e){let t=e.indexOf("--port");if(t===-1)return Zt;let n=rn(e[t+1]);return e.splice(t,2),n}function an(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function Ke(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function me(e){let t=Io(Ke(e,"URUN_BASE_URL")),n=Ke(e,"URUN_ORG_ID"),o=Ke(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Ee(s,"URUN_API_URL"):gt,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let c=(e.URUN_API_KEY??"").trim();if(c){let u=(e.URUN_GATEWAY_URL??"").trim(),l=u?Ee(u):void 0;return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:c,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function Io(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function Ee(e,t="URUN_GATEWAY_URL"){let n=new URL(e),o=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!o)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Qe(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Oo}}function To(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var Po=250;async function Ze(e,t=Po){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let o=(await n.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:c}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof c!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:c}}catch{return null}}var un=2e3;async function Co(e,t=un){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function cn(e,t,n=Zt,o=un){if(e!=null)return{mode:"spawn",port:e};let r=await Ze(n);if(r!==null&&To(r,t)){let s=await Co(n,o);return s===null?{mode:"reuse",port:n,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ln(e,t=Yt.default.homedir()){return zt.default.join(t,".urun","logs",`compat-proxy-${e}.log`)}var Ye=["log","info","warn","error","debug","trace"];function dn(e,t=process,n=console){let o=t.stdout.write,r=t.stderr.write,s=(a,...c)=>e.write(a,...c);t.stdout.write=s,t.stderr.write=s;let i=Object.fromEntries(Ye.map(a=>[a,n[a]]));for(let a of Ye)n[a]=(...c)=>{e.write(`${(0,Qt.format)(...c)}
42
+ `)),l.end()})}}function Wt(e){let{clients:t,apiKey:n}=e,o=(0,qt.createServer)(Ao(e));return Bt(o,{clients:t,apiKey:n}),o}var Yt=te(require("os"),1),zt=te(require("path"),1),Xt=require("url"),Qt=require("util");var Kt="0.3.2";var Zt=4141,Oo=Kt,Oe={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ze(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function en(e,t,n){let o={...e,...ze(t,n)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function tn(e,t,n){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=n.indexOf("--"),s=r===-1?n:n.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",c=s.includes("--skip-git-repo-check"),u=a&&!c?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...o,...i?[]:["-m",t],...u]}function nn(e,t){return t.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function on(e,t,n){let o=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!n(o))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${o}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return o}let r=(0,Xt.fileURLToPath)(new URL("../pi-extension/standalone.cjs",t));if(!n(r))throw new Error(`pi extension entry not found at ${r} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return r}function rn(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function sn(e){if(e[0]!=="--port")return null;let t=rn(e[1]);return e.splice(0,2),t}function Xe(e){let t=e.indexOf("--port");if(t===-1)return Zt;let n=rn(e[t+1]);return e.splice(t,2),n}function an(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function Ke(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function me(e){let t=Io(Ke(e,"URUN_BASE_URL")),n=Ke(e,"URUN_ORG_ID"),o=Ke(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Ee(s,"URUN_API_URL"):gt,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let c=(e.URUN_API_KEY??"").trim();if(c){let u=(e.URUN_GATEWAY_URL??"").trim(),l=u?Ee(u):void 0;return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:c,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function Io(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function Ee(e,t="URUN_GATEWAY_URL"){let n=new URL(e),o=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!o)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Qe(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Oo}}function To(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var Po=250;async function Ze(e,t=Po){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let o=(await n.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:c}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof c!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:c}}catch{return null}}var un=2e3;async function Co(e,t=un){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function cn(e,t,n=Zt,o=un){if(e!=null)return{mode:"spawn",port:e};let r=await Ze(n);if(r!==null&&To(r,t)){let s=await Co(n,o);return s===null?{mode:"reuse",port:n,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ln(e,t=Yt.default.homedir()){return zt.default.join(t,".urun","logs",`compat-proxy-${e}.log`)}var Ye=["log","info","warn","error","debug","trace"];function dn(e,t=process,n=console){let o=t.stdout.write,r=t.stderr.write,s=(a,...c)=>e.write(a,...c);t.stdout.write=s,t.stderr.write=s;let i=Object.fromEntries(Ye.map(a=>[a,n[a]]));for(let a of Ye)n[a]=(...c)=>{e.write(`${(0,Qt.format)(...c)}
43
43
  `)};return()=>{t.stdout.write=o,t.stderr.write=r;for(let a of Ye)n[a]=i[a]}}var Uo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function pn(e){let t=e?.code;return typeof t=="string"&&Uo.has(t)}function Ie(e,t){try{return e.write(t),!0}catch(n){if(pn(n))return!1;throw n}}function fn(e){let t={stdout:!1,stderr:!1},n=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{pn(i)&&(t[o]=!0);let a=i?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${o} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
44
44
  `)}catch{}};r.on("error",s),n.push([r,s])}return{isDead:o=>t[o],uninstall:()=>{for(let[o,r]of n)o.off("error",r)}}}function mn(e){let t=n=>{let o=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
45
45
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as k,b as $,c as h,d as C,e as U,f as N,g as O,h as L,i as G,j as E,k as I,l as y,n as _,o as P,p as W,q as j,r as B,s as D,t as v,u as K,v as M,w as F}from"../chunk-54VWZJU7.js";import"../chunk-F2TEK34X.js";import{b as T}from"../chunk-M6ICU4F5.js";import"../chunk-G3NMGP4N.js";import"../chunk-XHIIEA6Z.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-UVAY7Q7Z.js";import{c as g}from"../chunk-YSFSRI3D.js";g();import{spawn as V}from"child_process";import{appendFileSync as Y,createWriteStream as re,existsSync as ne,mkdirSync as oe}from"fs";import ae from"path";import t from"process";g();import{ensureNodeWebRTC as Z,nodeWebRTCUnavailableReason as ee}from"@urun-sh/core/internal";var te={ensureWebRTC:Z,webrtcUnavailableReason:ee,audioBackend:R};async function J(e=te){try{await e.ensureWebRTC()}catch(r){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(r)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(r){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(r)}`}}return{ok:!0,reason:null}}function ie(e,i){let r=(e.URUN_CATALOG_URL??"").trim(),l=r?_(r,"URUN_CATALOG_URL"):"",n=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!n?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
2
+ import{a as k,b as $,c as h,d as C,e as U,f as N,g as O,h as L,i as G,j as E,k as I,l as y,n as _,o as P,p as W,q as j,r as B,s as D,t as v,u as K,v as M,w as F}from"../chunk-FVFF5EWK.js";import"../chunk-F2TEK34X.js";import{b as T}from"../chunk-M6ICU4F5.js";import"../chunk-G3NMGP4N.js";import"../chunk-XHIIEA6Z.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-UVAY7Q7Z.js";import{c as g}from"../chunk-YSFSRI3D.js";g();import{spawn as V}from"child_process";import{appendFileSync as Y,createWriteStream as re,existsSync as ne,mkdirSync as oe}from"fs";import ae from"path";import t from"process";g();import{ensureNodeWebRTC as Z,nodeWebRTCUnavailableReason as ee}from"@urun-sh/core/internal";var te={ensureWebRTC:Z,webrtcUnavailableReason:ee,audioBackend:R};async function J(e=te){try{await e.ensureWebRTC()}catch(r){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(r)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(r){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(r)}`}}return{ok:!0,reason:null}}function ie(e,i){let r=(e.URUN_CATALOG_URL??"").trim(),l=r?_(r,"URUN_CATALOG_URL"):"",n=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!n?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
3
3
  `),null):{catalogUrl:l,anonKey:n}}function se(e){return k({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:ie(t.env,i=>t.stderr.write(i))})}async function le(e,i,r){let l=V(e,i,{stdio:"inherit",env:r});return new Promise(n=>{l.once("exit",o=>n(o??1)),l.once("error",o=>{t.stderr.write(`failed to launch ${e}: ${String(o)}
4
4
  `),n(127)})})}function ue(){return L(t.env,import.meta.url,ne)}function q(e){for(let[i,r]of Object.entries(C(e)))t.stdout.write(`export ${i}=${r}
5
5
  `)}async function H(e,i){let r=y(t.env),l=i?P(r):void 0,n=se(r),o=T({clients:$(n),identity:l});try{await new Promise((s,d)=>{o.once("error",d),o.listen(e,"127.0.0.1",s)})}catch(s){throw await n.closeAll().catch(()=>{}),s.code==="EADDRINUSE"?new Error(F(e,await W(e))):s}let u=o.address().port;return i&&(t.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -70,7 +70,7 @@
70
70
  "build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
71
71
  },
72
72
  "peerDependencies": {
73
- "@urun-sh/core": "^0.3.1"
73
+ "@urun-sh/core": "^0.3.2"
74
74
  },
75
75
  "dependencies": {
76
76
  "openai": "4.104.0",