@urun-sh/openai 0.6.36 → 0.6.37

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 +1 @@
1
- import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-T6RD7TSR.js";import"../chunk-OEITGJY2.js";import"../chunk-CAR4AEQJ.js";import"../chunk-EPG5XWHE.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-GQTWIDJ6.js";import"../chunk-KXKTXZKG.js";import"../chunk-KKCUIOL4.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
1
+ import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-7HOEZLIM.js";import"../chunk-EKNKHD4H.js";import"../chunk-CAR4AEQJ.js";import"../chunk-SYX2HJBJ.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-GQTWIDJ6.js";import"../chunk-LLFROK6B.js";import"../chunk-KKCUIOL4.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as Le}from"../chunk-LM4E5YM2.js";import{a as z}from"../chunk-GQTWIDJ6.js";import{s as x,t as Q}from"../chunk-KXKTXZKG.js";import{a as X,b as Z,d as ee}from"../chunk-KKCUIOL4.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as N}from"../chunk-6K7NOPD5.js";import{b as Oe,c as f}from"../chunk-YSFSRI3D.js";f();var pn=Oe(Le(),1);import b from"process";import{Redis as Pt}from"ioredis";f();f();var U=`
2
+ import{a as Le}from"../chunk-LM4E5YM2.js";import{a as z}from"../chunk-GQTWIDJ6.js";import{s as x,t as Q}from"../chunk-LLFROK6B.js";import{a as X,b as Z,d as ee}from"../chunk-KKCUIOL4.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as N}from"../chunk-6K7NOPD5.js";import{b as Oe,c as f}from"../chunk-YSFSRI3D.js";f();var pn=Oe(Le(),1);import b from"process";import{Redis as Pt}from"ioredis";f();f();var U=`
3
3
  local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
4
4
  local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
5
5
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md
@@ -17,7 +17,7 @@ Connection: close\r
17
17
  Content-Type: text/plain; charset=utf-8\r
18
18
  Content-Length: ${Buffer.byteLength(o)}\r
19
19
  \r
20
- ${o}`)}function Es(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:Gu}),r=new We,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let g;try{g=new URL(d.url??"/","http://localhost")}catch{pn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),g.pathname!==Hu){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){pn(c,401,"invalid local proxy api key");return}let w;try{w=await u(d)}catch(S){let v=e.statusOf?.(S)??null;pn(c,v?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new cr(S,w,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&pn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=pr();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let g of s)g.destroy();s.clear();for(let g of i)g.destroy();i.clear();for(let g of o)g.close(1001,"server shutting down");let p=setTimeout(()=>{for(let g of o)g.readyState!==Fe.WebSocket.CLOSED&&g.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Er=require("@urun-sh/core");var As=require("@urun-sh/core"),Yu={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Xu={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function $t(t,e){let n=Xu[t.code];return e?`${n} (${e})`:n}function fn(t){if(t==null)return null;let e=Yu[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function mn(t){if(t.kind==="create-failed")return fn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=As.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return fn(e?"cold_start_exceeded":"queue_timeout")}var Os=tt(require("os"),1),Ts=tt(require("path"),1),Ps=require("url"),Cs=require("util");var Is="0.6.36";var $s=4141,Zu=Is,hn={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function gr(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function Ms(t,e,n){let r={...t,...gr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Ls(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function Ns(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Us(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Ds(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(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,Ps.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(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 Fs(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function qs(t){if(t[0]!=="--port")return null;let e=Fs(t[1]);return t.splice(0,2),e}function hr(t){let e=t.indexOf("--port");if(e===-1)return $s;let n=Fs(t[e+1]);return t.splice(e,2),n}function js(t){if(t===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 t}function fr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} 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 ct(t){let e=el(fr(t,"URUN_BASE_URL")),n=fr(t,"URUN_ORG_ID"),r=fr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?gn(s,"URUN_API_URL"):To,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?gn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,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 el(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \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 t}function gn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function yr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Zu}}function tl(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var nl=250;async function wr(t,e=nl){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Bs=2e3;async function rl(t,e=Bs){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});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 Hs(t,e,n=$s,r=Bs){if(t!=null)return{mode:"spawn",port:t};let o=await wr(n);if(o!==null&&tl(o,e)){let s=await rl(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{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 _r(t,e=Os.default.homedir()){return Ts.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var mr=["log","info","warn","error","debug","trace"];function Gs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(mr.map(u=>[u,n[u]]));for(let u of mr)n[u]=(...a)=>{t.write(`${(0,Cs.format)(...a)}
20
+ ${o}`)}function Es(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:Gu}),r=new We,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let g;try{g=new URL(d.url??"/","http://localhost")}catch{pn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),g.pathname!==Hu){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){pn(c,401,"invalid local proxy api key");return}let w;try{w=await u(d)}catch(S){let v=e.statusOf?.(S)??null;pn(c,v?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new cr(S,w,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&pn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=pr();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let g of s)g.destroy();s.clear();for(let g of i)g.destroy();i.clear();for(let g of o)g.close(1001,"server shutting down");let p=setTimeout(()=>{for(let g of o)g.readyState!==Fe.WebSocket.CLOSED&&g.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Er=require("@urun-sh/core");var As=require("@urun-sh/core"),Yu={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Xu={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function $t(t,e){let n=Xu[t.code];return e?`${n} (${e})`:n}function fn(t){if(t==null)return null;let e=Yu[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function mn(t){if(t.kind==="create-failed")return fn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=As.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return fn(e?"cold_start_exceeded":"queue_timeout")}var Os=tt(require("os"),1),Ts=tt(require("path"),1),Ps=require("url"),Cs=require("util");var Is="0.6.37";var $s=4141,Zu=Is,hn={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function gr(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function Ms(t,e,n){let r={...t,...gr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Ls(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function Ns(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Us(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Ds(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(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,Ps.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(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 Fs(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function qs(t){if(t[0]!=="--port")return null;let e=Fs(t[1]);return t.splice(0,2),e}function hr(t){let e=t.indexOf("--port");if(e===-1)return $s;let n=Fs(t[e+1]);return t.splice(e,2),n}function js(t){if(t===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 t}function fr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} 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 ct(t){let e=el(fr(t,"URUN_BASE_URL")),n=fr(t,"URUN_ORG_ID"),r=fr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?gn(s,"URUN_API_URL"):To,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?gn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,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 el(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \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 t}function gn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function yr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Zu}}function tl(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var nl=250;async function wr(t,e=nl){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Bs=2e3;async function rl(t,e=Bs){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});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 Hs(t,e,n=$s,r=Bs){if(t!=null)return{mode:"spawn",port:t};let o=await wr(n);if(o!==null&&tl(o,e)){let s=await rl(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{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 _r(t,e=Os.default.homedir()){return Ts.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var mr=["log","info","warn","error","debug","trace"];function Gs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(mr.map(u=>[u,n[u]]));for(let u of mr)n[u]=(...a)=>{t.write(`${(0,Cs.format)(...a)}
21
21
  `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of mr)n[u]=i[u]}}var ol=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Js(t){let e=t?.code;return typeof e=="string"&&ol.has(e)}function xe(t,e){try{return t.write(e),!0}catch(n){if(Js(n))return!1;throw n}}function Vs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Js(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
22
22
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function Ws(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
23
23
  `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as J,b as q,c as H,d as Y,e as V}from"../chunk-OEITGJY2.js";import"../chunk-CAR4AEQJ.js";import{E as K}from"../chunk-EPG5XWHE.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-GQTWIDJ6.js";import{a as v,b as $,c as C,d as U,e as I,f as L,g as N,h as O,i as x,j as _,k as g,m as G,n as P,o as D,p as M,q as A,r as W,s as b,t as B,u as j,v as F}from"../chunk-KXKTXZKG.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}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(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(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 J,b as q,c as H,d as Y,e as V}from"../chunk-EKNKHD4H.js";import"../chunk-CAR4AEQJ.js";import{E as K}from"../chunk-SYX2HJBJ.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-GQTWIDJ6.js";import{a as v,b as $,c as C,d as U,e as I,f as L,g as N,h as O,i as x,j as _,k as g,m as G,n as P,o as D,p as M,q as A,r as W,s as b,t as B,u as j,v as F}from"../chunk-LLFROK6B.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}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(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(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:s}}function me(e){let i={baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:fe(n.env,l=>n.stderr.write(l)),decisionPool:J(n.env,n.env.HOSTNAME)??void 0},t=H(i);return{router:t,decision:i.decisionPool?Y(i,t):null}}async function Q(e,i,t){let l=ee(e,i,{stdio:"inherit",env:t});return new Promise(s=>{l.once("exit",r=>s(r??1)),l.once("error",r=>{n.stderr.write(`failed to launch ${e}: ${String(r)}
4
4
  `),s(127)})})}function X(){return N(n.env,import.meta.url,pe)}function te(e){for(let[i,t]of Object.entries($(e)))n.stdout.write(`export ${i}=${t}
5
5
  `)}async function Z(e,i){let t=g(n.env),l=i?P(t):void 0,{router:s,decision:r}=me(t);r&&(r.boot().then(()=>r.reap()).catch(u=>n.stderr.write(`[decision-pool] boot FAILED: ${String(u instanceof Error?u.message:u)}
@@ -1 +1 @@
1
- import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-EPG5XWHE.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-KXKTXZKG.js";import{i as r,j as i}from"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
1
+ import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-SYX2HJBJ.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-LLFROK6B.js";import{i as r,j as i}from"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.36",
3
+ "version": "0.6.37",
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.6.36"
73
+ "@urun-sh/core": "^0.6.37"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",