@urun-sh/openai 0.6.55 → 0.6.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.
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-N3Y2GDQK.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.55";var y=4141,A=g,M={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 O(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 F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){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=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.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=k(new URL("../pi-extension/standalone.cjs",t));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 x(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 Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(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 l(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 te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,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 $(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 f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(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 T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});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:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){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 re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(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 oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
1
+ import{h as m}from"./chunk-N3Y2GDQK.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.56";var y=4141,A=g,M={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 O(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 F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){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=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.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=k(new URL("../pi-extension/standalone.cjs",t));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 x(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 Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(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 l(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 te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,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 $(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 f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(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 T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});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:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){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 re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(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 oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[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
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}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}
@@ -1,2 +1,2 @@
1
- import{c as v}from"./chunk-Z74YK7AL.js";import{c as D}from"./chunk-YSFSRI3D.js";D();import{createClientToken as H}from"@urun-sh/core";import{Queue as I}from"bullmq";import{randomUUID as V}from"crypto";var O=3e4;var q=1e3,X=12e4;function T(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var M=class extends Error{};async function $(n,s){let t;try{await Promise.race([n,new Promise(l=>{t=setTimeout(l,Math.max(0,s))})])}finally{clearTimeout(t)}}function Y(n){let s=n.now??Date.now,t=new Map,l=new Map,h=new Map,u=new Map,g=new Map,_=new Map,b=new Map,L=new Set,k=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??x(e),t.set(e,a)),a},x=e=>{let a=n.redis,c=new I(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let i=(await c.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,o)=>r.timestamp-o.timestamp);if(i.length===0)return{found:0};for(let r of i)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of i.slice(1))try{await r.remove()}catch{}return{found:i.length}},close:()=>c.close()}},E=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),c=[],p=new Map;for(let[r,o]of Object.entries(a)){let d=T(o);d&&d.proxy_url===n.docHostUrl&&(c.push(r),p.set(r,d.region))}if(c.length===0)return[];let y=await n.redis.mget(...c.map(r=>`lane_hosts:${r}`)),i=[];return c.forEach((r,o)=>{let d=y[o];d&&i.push({laneId:r,host:d,region:p.get(r)})}),i},S=async(e,a,c,p,y,i)=>{let r=c,o=p,d=y;if(typeof r!="string"||r===""||typeof o!="string"||o===""){let C=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(C)r=C.app,o=C.fn,d=C.sharedApp??d;else{let F=h.get(e)??0;if(s()-F<O)return;throw h.set(e,s()),new M("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let m=l.get(e)??0,w=s();if(w-m<O)return;if(l.set(e,w),(await k(e).reassertWaiting(s()).catch(C=>{throw l.delete(e),C})).found>0){g.set(a??"",(g.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let A=`lane-${V().replaceAll("-","")}`,P=await n.admission.createLaneSession({pool:e,app:r,fn:o,...d?{sharedApp:!0}:{},...i?{requestorOrgId:i}:{},laneId:A,laneHostUrl:n.docHostUrl});if(P.sessionId!==A)throw new Error(`session-api lane admission returned session_id "${P.sessionId}" for requested logical_id "${A}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:c,sharedApp:p,requestorOrgId:y,model:i,holdMs:r=0}){if(L.add(e),n.targets!==void 0&&i!==void 0&&!n.targets.some(f=>f.model===i)){let f=`no pooler target for ${i} \u2014 refusing to mint a lane demand`;throw _.set("untargeted",(_.get("untargeted")??0)+1),b.set(e,f),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:f}),new v(e,i)}let o=async f=>{try{await S(e,i,a,c,p,f)}catch(R){let A=R instanceof Error?R.message:String(R),P=R instanceof M?"identity":"admission";_.set(P,(_.get(P)??0)+1),b.set(e,A),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:A})}},d=async()=>{try{return await E(e)}catch{return[]}},m=await d();if(m.length>0){let f=n.laneMinFor?.(e)??0;return f>m.length&&(async()=>{for(let R=m.length;R<f;R++)await o(void 0)})(),m}let w=s()+r;for(await $(o(y),r);s()<w;){if(await new Promise(f=>setTimeout(f,q)),m=await d(),m.length>0)return m;await $(o(y),w-s())}return[]},async status(){let e=[...L].sort();return Promise.all(e.map(async a=>{let c=[];try{let p=await n.redis.hgetall(`lanes:${a}`),y=Object.keys(p),i=y.length===0?[]:await n.redis.mget(...y.map(o=>`lane_hosts:${o}`)),r=s();c=y.map((o,d)=>{let m=p[o],w=m===void 0?null:T(m);return{laneId:o,occupantId:w?.occupant_id??"",capacity:w?.capacity??0,heartbeatAgeMs:w===null?null:r-w.heartbeat_ms,advertisedHere:w?.proxy_url===n.docHostUrl,hosted:!!i[d]}})}catch{}return{pool:a,lanes:c,lastDemandAt:l.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),...g.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:g.get(a)??0}))},demandRefusals(){return[..._.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var j=4e3,Q=5e3;function J(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(j)})}function Z(n){return{createLaneSession:async({pool:s,app:t,fn:l,sharedApp:h,requestorOrgId:u,laneId:g,laneHostUrl:_})=>{let b=await H(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${l}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:J(n.fetch??globalThis.fetch)}),L=n.fetch??globalThis.fetch,k;try{k=await L(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(Q),headers:{"content-type":"application/json",authorization:`Bearer ${b.token}`,"x-tenant-id":b.orgId},body:JSON.stringify({app:t,function:l,...h?{shared_app:!0}:{},...h&&u?{requestor_org_id:u}:{},logical_id:g,idempotency_key:g,concurrency_key:g,lane_host_url:_})})}catch(S){throw new Error(`session-api lane admission for ${g} (app ${t}/${l}) failed: ${S instanceof Error?S.message:String(S)}`)}let x={};try{x=await k.json()}catch{}let E=x.session_id;if(k.status!==200||x.status!=="allocated"||typeof E!="string"){let S=typeof x.message=="string"?x.message:`HTTP ${k.status}`;throw new Error(`session-api lane admission refused for ${g} (app ${t}/${l}): ${S}`)}return{sessionId:E}}}}D();var K="urun:catalog:v1";function te(n){let s=n.refreshMs??5e3,t=n.now??Date.now,l=null,h=0,u=null,g=async()=>{let b=await n.redis.hgetall(K),L=[];for(let k of Object.values(b))try{L.push(JSON.parse(k))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
1
+ import{c as v}from"./chunk-6R3TCKOH.js";import{c as D}from"./chunk-YSFSRI3D.js";D();import{createClientToken as H}from"@urun-sh/core";import{Queue as I}from"bullmq";import{randomUUID as V}from"crypto";var O=3e4;var q=1e3,X=12e4;function T(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var M=class extends Error{};async function $(n,s){let t;try{await Promise.race([n,new Promise(l=>{t=setTimeout(l,Math.max(0,s))})])}finally{clearTimeout(t)}}function Y(n){let s=n.now??Date.now,t=new Map,l=new Map,h=new Map,u=new Map,g=new Map,_=new Map,b=new Map,L=new Set,k=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??x(e),t.set(e,a)),a},x=e=>{let a=n.redis,c=new I(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let i=(await c.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,o)=>r.timestamp-o.timestamp);if(i.length===0)return{found:0};for(let r of i)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of i.slice(1))try{await r.remove()}catch{}return{found:i.length}},close:()=>c.close()}},E=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),c=[],p=new Map;for(let[r,o]of Object.entries(a)){let d=T(o);d&&d.proxy_url===n.docHostUrl&&(c.push(r),p.set(r,d.region))}if(c.length===0)return[];let y=await n.redis.mget(...c.map(r=>`lane_hosts:${r}`)),i=[];return c.forEach((r,o)=>{let d=y[o];d&&i.push({laneId:r,host:d,region:p.get(r)})}),i},S=async(e,a,c,p,y,i)=>{let r=c,o=p,d=y;if(typeof r!="string"||r===""||typeof o!="string"||o===""){let C=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(C)r=C.app,o=C.fn,d=C.sharedApp??d;else{let F=h.get(e)??0;if(s()-F<O)return;throw h.set(e,s()),new M("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let m=l.get(e)??0,w=s();if(w-m<O)return;if(l.set(e,w),(await k(e).reassertWaiting(s()).catch(C=>{throw l.delete(e),C})).found>0){g.set(a??"",(g.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let A=`lane-${V().replaceAll("-","")}`,P=await n.admission.createLaneSession({pool:e,app:r,fn:o,...d?{sharedApp:!0}:{},...i?{requestorOrgId:i}:{},laneId:A,laneHostUrl:n.docHostUrl});if(P.sessionId!==A)throw new Error(`session-api lane admission returned session_id "${P.sessionId}" for requested logical_id "${A}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:c,sharedApp:p,requestorOrgId:y,model:i,holdMs:r=0}){if(L.add(e),n.targets!==void 0&&i!==void 0&&!n.targets.some(f=>f.model===i)){let f=`no pooler target for ${i} \u2014 refusing to mint a lane demand`;throw _.set("untargeted",(_.get("untargeted")??0)+1),b.set(e,f),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:f}),new v(e,i)}let o=async f=>{try{await S(e,i,a,c,p,f)}catch(R){let A=R instanceof Error?R.message:String(R),P=R instanceof M?"identity":"admission";_.set(P,(_.get(P)??0)+1),b.set(e,A),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:A})}},d=async()=>{try{return await E(e)}catch{return[]}},m=await d();if(m.length>0){let f=n.laneMinFor?.(e)??0;return f>m.length&&(async()=>{for(let R=m.length;R<f;R++)await o(void 0)})(),m}let w=s()+r;for(await $(o(y),r);s()<w;){if(await new Promise(f=>setTimeout(f,q)),m=await d(),m.length>0)return m;await $(o(y),w-s())}return[]},async status(){let e=[...L].sort();return Promise.all(e.map(async a=>{let c=[];try{let p=await n.redis.hgetall(`lanes:${a}`),y=Object.keys(p),i=y.length===0?[]:await n.redis.mget(...y.map(o=>`lane_hosts:${o}`)),r=s();c=y.map((o,d)=>{let m=p[o],w=m===void 0?null:T(m);return{laneId:o,occupantId:w?.occupant_id??"",capacity:w?.capacity??0,heartbeatAgeMs:w===null?null:r-w.heartbeat_ms,advertisedHere:w?.proxy_url===n.docHostUrl,hosted:!!i[d]}})}catch{}return{pool:a,lanes:c,lastDemandAt:l.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),...g.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:g.get(a)??0}))},demandRefusals(){return[..._.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var j=4e3,Q=5e3;function J(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(j)})}function Z(n){return{createLaneSession:async({pool:s,app:t,fn:l,sharedApp:h,requestorOrgId:u,laneId:g,laneHostUrl:_})=>{let b=await H(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${l}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:J(n.fetch??globalThis.fetch)}),L=n.fetch??globalThis.fetch,k;try{k=await L(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(Q),headers:{"content-type":"application/json",authorization:`Bearer ${b.token}`,"x-tenant-id":b.orgId},body:JSON.stringify({app:t,function:l,...h?{shared_app:!0}:{},...h&&u?{requestor_org_id:u}:{},logical_id:g,idempotency_key:g,concurrency_key:g,lane_host_url:_})})}catch(S){throw new Error(`session-api lane admission for ${g} (app ${t}/${l}) failed: ${S instanceof Error?S.message:String(S)}`)}let x={};try{x=await k.json()}catch{}let E=x.session_id;if(k.status!==200||x.status!=="allocated"||typeof E!="string"){let S=typeof x.message=="string"?x.message:`HTTP ${k.status}`;throw new Error(`session-api lane admission refused for ${g} (app ${t}/${l}): ${S}`)}return{sessionId:E}}}}D();var K="urun:catalog:v1";function te(n){let s=n.refreshMs??5e3,t=n.now??Date.now,l=null,h=0,u=null,g=async()=>{let b=await n.redis.hgetall(K),L=[];for(let k of Object.values(b))try{L.push(JSON.parse(k))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
2
2
  `)}return l=L,h=t(),L},_=()=>l===null||t()-h>=s;return{rows(){return _()?(u||(u=g().finally(()=>{u=null})),u):Promise.resolve(l)},close(){l=null,u=null}}}export{X as a,Y as b,Z as c,K as d,te as e};