@urun-sh/openai 0.6.52 → 0.6.53
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.
- package/dist/{chunk-JU5V4ZET.js → chunk-5PA6542H.js} +1 -1
- package/dist/chunk-7IT4XK2K.js +66 -0
- package/dist/{chunk-3O4TBGQL.js → chunk-D7PBMXB6.js} +1 -1
- package/dist/{chunk-2JEZNE5Z.js → chunk-K5TQMHAY.js} +1 -1
- package/dist/{chunk-JR5TNOMP.js → chunk-ZWDQPTSH.js} +1 -1
- package/dist/{composite-D7icObdD.d.cts → composite-4ppY0Kv6.d.cts} +11 -0
- package/dist/{composite-DyRe-KRu.d.ts → composite-BKEde6hP.d.ts} +2 -0
- package/dist/hosted/bin.cjs +41 -41
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +33 -33
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +36 -36
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +24 -24
- package/dist/proxy/index.d.cts +10 -2
- package/dist/proxy/index.d.ts +10 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-ONFTTWZH.js +0 -66
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as D}from"./chunk-
|
|
1
|
+
import{c as D}from"./chunk-ZWDQPTSH.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(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 P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("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 o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \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:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.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 q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
2
2
|
`)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-
|
|
1
|
+
import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-7IT4XK2K.js";import{c as ee,f as V,g as ne,p as oe}from"./chunk-64VO62LW.js";import{a as ge,b as G}from"./chunk-XGAF2NDT.js";import{c as ue}from"./chunk-ZWDQPTSH.js";import{a as H}from"./chunk-526ZJAOW.js";import{b as Z,d as j}from"./chunk-AWCC5WRB.js";import{b as se,c as re,d as ie,g as ae,j as F,m as B,n as _,o as ce,r as R,s as L,t as de,u as le}from"./chunk-C452ZIU5.js";import{c as b}from"./chunk-YSFSRI3D.js";b();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Be,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as We,SessionFailedError as z}from"@urun-sh/core";b();import{SessionFailedError as _e}from"@urun-sh/core";var q=2;function Le(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Te(e){let t=e?.type;return t==="response.completed"||t==="error"}function ye(e){return async function(r,i){let a=await e.sessionFor(r.model);return(async function*(){for(let l=1;l<=q;l++){let{app:g,entry:y,identity:S}=l===1?a:await e.sessionFor(r.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:S});let p=!1,u=!1;try{let f=await e.createStream(y,r);for await(let m of f){if(Te(m)&&(p=!0),Le(m)){if(l>1)continue}else u=!0;yield m}}catch(f){if(f instanceof _e&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<q&&!u){await e.evict(g,y);continue}throw f}if(p)return;if(l<q&&!u){await e.evict(g,y);continue}return}})()}}import{randomUUID as Oe}from"crypto";b();import{request as Fe}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(r,i,a,c){super(a);this.status=r;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Me=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(r=>r.role==="system"||r.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},Ne=e=>{let t=e.messages?.find(r=>r.role!=="system"&&r.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let r=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(r===void 0)return;if(typeof r=="string")return r;if(r!==null&&typeof r=="object"&&"content"in r){let i=r.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(r)}},he=e=>new Promise((t,r)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",r)}),De=async e=>{let t="pooler_error",r=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await he(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(t=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(r=a.message)}}catch{}return new k(e.status,t,r,e.retryAfterSeconds)};async function xe(e,t,r,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:r,streaming:a,payload:t,affinity:{systemPrompt:Me(t),firstMessage:Ne(t)}});return new Promise((g,y)=>{let S=Fe({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},p=>{let u=Number(p.headers["retry-after"]??"");g({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(u)?u:void 0,body:p})});S.on("error",p=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),S.end(l)})}var we=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let r;try{r=JSON.parse(t)}catch{return null}if(r===null||typeof r!="object")return null;let i=r;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*Ce(e){let t="";for await(let i of e.body)for(t+=String(i);;){let a=t.indexOf(`
|
|
2
2
|
|
|
3
3
|
`);if(a===-1)break;let c=t.slice(0,a);t=t.slice(a+2);let l=we(c);l!==null&&(yield l)}let r=we(t);r!==null&&(yield r)}async function on(e,t,r,i){let a=Z(t,r,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await xe(e,a,r,c,t.stream===!0);if(l.status>=400)throw await De(l);let g=t.stream===!0?j(r,Ce(l)):await Ue(l,r);return(async function*(){yield{type:"response.created",response:{id:`resp_${r}`,status:"in_progress"}},yield*g})()}async function Ue(e,t){let r=await he(e.body),i=null;try{let c=JSON.parse(r);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return j(t,(async function*(){yield a})())}b();import{encodeStreamEnvelope as Se}from"@urun-sh/core";var $e="audio";function Pe(e){let t=e.streamEndpoint($e);return{sessionId:e.id,appendInputAudio(r,i){let a=Buffer.from(r,"base64");if(a.byteLength!==0){if(i===void 0){t.send(Se(new Uint8Array(a)));return}t.send(Se({pcm16:r,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}b();import{encodeStreamEnvelope as je}from"@urun-sh/core";var Ve="rt-video-in";function ve(e){let t=e.streamEndpoint(Ve);return{sendInputFrame:async r=>{t.send(je(r))}}}var Ge=0,qe=4,Je=4;function Fn(e,t){let r=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let S=Number.parseInt(y,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):Ge;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=r("URUN_DECISION_POOL_MAX",Math.max(a,qe));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:r("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||t||"proxy"}}function Rn(e){let t=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!t)return W;let r=Number.parseInt(t,10);if(!Number.isInteger(r)||r<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return r*1e3}function K(e,t,r,i){let a=e[r];if(typeof a!="function")throw new Error(`app "${t}" has no function "${r}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${t}" function "${r}" returned a session without end()`);return c}function ke(e,t,r,i){let{baseUrl:a,orgId:c,auth:l}=e,g=t.fnName??e.fnName,y=e.sessionStartOptions?.(r),S={...t.sharedApp?{sharedApp:!0}:{},...y,...i,presenceIdleMs:3e4},p=h=>({session:h,responses:new H(h),gone:ge(h,r)});if(l.lane==="jwt"){let h=J(t.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return p(K(h,t.appSlug,g,S))}if(l.lane==="machine"||l.lane==="user"){let h=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,C=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),T=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(h,{baseUrl:I,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:C,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(T,t.appSlug,g,S))}let{apiKey:u,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),w=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(u,{baseUrl:f,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:m,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(w,t.appSlug,g,S))}function Ie(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,r=e.status.error?.code;return t===410||t===409&&(r==="cancelled"||r==="expired")?!0:r==="client_ended"}var Ke=new Set(["error","paused"]);function Mn(e){let{auth:t,catalog:r}=e,i=null,a=(l,g)=>{let y=ke(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new le({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:t.lane==="api-key"?()=>ce({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:e.catalogRows??(r?()=>te(r):null),listPrices:r?()=>ie(r):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return se(l)}:t.lane==="api-key"?()=>re({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:Ie});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,t){let r=e.decisionPool;if(!r)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=r.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=p=>{process.stderr.write(`[decision-pool] ${p}
|
|
4
4
|
`)},y=(p,u)=>{let f=a.get(u);if(f)return f;let m=new pe({min:r.min,max:r.max,idleGraceMs:r.idleGraceMs,inFlightCap:r.inFlightCap,replicaId:i,onLease:w=>w.session.activity?.(),openSlot:async w=>{let h=ke(e,p,u,{concurrencyKey:w.concurrencyKey});return h.gone.onGone(I=>I.bindingLost?m.evict(h):m.markSessionDead(h)),await x(h.session),g(`slot attached pool=${u} slot=${w.concurrencyKey} session=${h.session.id??"(no id)"}`),h},closeSlot:async w=>{w.gone.dispose(),w.audioDispose?.(),await w.session.end()},onDetach:(w,h)=>g(`slot detached pool=${u} slot=${w.concurrencyKey} reason=${h}`),terminalOpenFailure:w=>w instanceof z&&X(w)});return c.set(u,{target:p,env:r}),a.set(u,m),m},S=async(p,u)=>{let f=c.get(u);if(f)try{let m=await t.poolTuningFor(p);y(p,u).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){g(`pool tuning refresh failed pool=${u} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let p={appSlug:e.defaultApp};await y(p,L(p)).boot()},async sessionFor(p){let u=await t.resolveTargetFor(p),f=L(u),m=y(u,f);await S(u,f);let w=await m.acquire({timeoutMs:m.requestWaitMs}),h=l.get(w.entry)??[];return h.push(w),l.set(w.entry,h),{app:f,entry:w.entry,identity:de(u)}},async warmFor(p){let u=await t.resolveTargetFor(p);await y(u,L(u)).boot()},end(p){let u=l.get(p)?.shift();u&&(l.get(p)?.length===0&&l.delete(p),u.release())},evict(p){for(let u of a.values())u.evict(p)},markSessionDead(p){for(let u of a.values())u.markSessionDead(p)},reap(){for(let[p,{target:u}]of c)S(u,p).then(()=>{let f=a.get(p);f&&f.reap()})},async pingReady(p){for(let u of a.values())if(await u.pingReady(p))return!0;return!1},stats(){return[...a.entries()].map(([p,u])=>({poolKey:p,...u.stats()}))},async drain(p){await Promise.all([...a.values()].map(u=>u.drain({timeoutMs:p})))},async close(){await Promise.all([...a.values()].map(p=>p.close()))}}}function ze(e){return We(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:Be:be}async function x(e,t){let r=e.whenLive;if(typeof r!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await r.call(e,{timeout:ze(e.phase),signal:t})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Ae(e){let t=e.phase?.name;if(t==="live"||t==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function D(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Dn(e,t=ne,r,i,a=W,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,S=new WeakMap,p=new Map,u=new WeakMap,f=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},m="lane",w=n=>{let s=_(n);if(!c||!s||s.app!==m)return null;let o=c.entryFor(s.key);if(!o)throw new F(`the lane behind this handle (${s.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:s.key,entry:o}},h=async n=>w(n)?.entry??(await e.sessionForHandle(n)).entry,I=n=>{let s=l.get(n);if(!s){let o={waiting:0,gone:new AbortController};u.set(n,o),s=(async()=>{if(await x(n.session,o.gone.signal),o.gone.signal.aborted)throw D(o.gone.signal);u.get(n)===o&&u.delete(n);let d=await ee(n.session,await t());return Object.assign(d,{sessionId:n.session.id})})(),l.set(n,s),s.then(d=>{l.get(n)===s&&(n.audioDispose=()=>d.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{u.get(n)===o&&u.delete(n)},()=>{u.get(n)===o&&u.delete(n)})}return s},C=n=>{let s=S.get(n);return s||(s=(async()=>{let o=await I(n);return{appendInputAudio:(d,v)=>o.appendInputAudio(d,v),onOutputAudio:d=>o.onOutputAudio(d),sessionId:f(n)}})(),S.set(n,s),s.catch(()=>{S.get(n)===s&&S.delete(n)})),s},T=async(n,s,o,d=!1)=>{let v=()=>d?Ae(n.session):Xe(n.session);if(o?.aborted){let O=u.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await v().catch(()=>{}),D(o)}let E=s(n),P=u.get(n);return P!==void 0&&P.waiting++,o===void 0?E:new Promise((O,A)=>{let Q=()=>{P!==void 0&&--P.waiting===0&&u.get(n)===P&&(P.gone.abort(),u.delete(n),l.delete(n),S.delete(n),v().catch(()=>{})),A(D(o))};o.addEventListener("abort",Q,{once:!0});let Y=()=>o.removeEventListener("abort",Q);E.then($=>{Y(),O($)},$=>{Y(),A($)})})},U=async(n,s,o)=>{try{return await o}catch(d){throw(d instanceof F||d instanceof z&&X(d))&&(e.evict(n,s),d instanceof z&&r?.(n,d.kind==="never-live"?"never-live":"create-failed")),d}};return{createResponse:ye({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let o=await c.sessionFor(n,s);return{app:o.app,entry:o.entry,identity:o.identity}}catch(o){if(o instanceof ue)return i?i.sessionFor(n):e.sessionFor(n);if(o instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${o.name} ${o.code}: ${o.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw o}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>f(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,o)=>{X(o)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),r?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await x(n.session);let o=fe(G(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return o;let d=n;return(async function*(){try{yield*o}catch(E){throw me(E)&&(c&&c.owns(d)?c.evict(d):i&&(E instanceof F&&!E.bindingLost?i.markSessionDead(d):i.evict(d))),E}finally{c&&c.owns(d)?c.release(d):i?.end(d)}})()}catch(o){throw c&&c.owns(n)?c.release(n):i&&i.end(n),o}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{app:o,entry:d}=await e.sessionFor(n);return await U(o,d,T(d,I,s))},openAudioOn:async(n,s,o,d)=>{let v=w(n);if(v){let A=v.entry.session;return Pe(A)}let{app:E,entry:P}=await e.sessionForHandle(n);if(d&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;d({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=_(n)?.app.startsWith(R)??!1;return await U(E,P,T(P,C,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw D(s);let o=await h(n);yield*ae(o.session,s)},openVideoOn:async n=>{let s=w(n);if(s)return ve(s.entry.session);let{entry:o}=await e.sessionForHandle(n),d=g.get(o);return d||(d=V(o.session),g.set(o,d)),d},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=g.get(s);return o||(o=V(s.session),g.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=y.get(s);return o||(o=oe(s.session),y.set(s,o)),o},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let o=await c.sessionFor(n,s),d=f(o.entry);if(d===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return B(m,d)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:o,entry:d}=await e.dedicatedSessionFor(n);return B(o,Ie(d))},touchSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);o||(o=new Map,p.set(n,o)),o.set(s,Date.now());let d=null;try{d=await h(n)}catch{return}d.session.activity?.()})()},detachSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);if(o?.delete(s),o&&o.size===0&&p.delete(n),o&&o.size>0)return;let d=null;try{d=await h(n)}catch{return}d.session.presenceDetach?.()})()},releaseSessionHandle:n=>{let s=_(n);if(!s)return;if(s.app.startsWith(R)){(async()=>{let d=null;try{d=(await e.sessionForHandle(n)).entry}catch{return}await Ae(d.session).catch(()=>{}),await e.evict(s.app,d)})();return}if(!c||s.app!==m)return;let o=c.entryFor(s.key);o&&c.release(o)},endDedicatedSession:async n=>{let s=_(n);if(!s||!s.app.startsWith(R))return;let o=null;try{o=(await e.sessionForHandle(n)).entry}catch{return}if(typeof o.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let d=await o.session.end();return await e.evict(s.app,o),d},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s,o)=>{let d=await h(n);await x(d.session);let v=o!==void 0&&w(n)?new H({...d.session,consumerId:o},{sessionTag:o}):d.responses;return G(await v.responses.create(s),d.gone)},onSessionEnd:async(n,s)=>{let o=w(n);if(o)return o.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:d}=await e.sessionForHandle(n),v=d.session;if(typeof v.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return v.onPhase(P=>{if(E||!Ke.has(P.name))return;E=!0;let O=v.endsAt??null;s({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Fn as c,Rn as d,Mn as e,Nn as f,Dn as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-C452ZIU5.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.
|
|
1
|
+
import{h as m}from"./chunk-C452ZIU5.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.53";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}
|
|
@@ -420,6 +420,17 @@ interface RealtimeBinding<S = unknown> {
|
|
|
420
420
|
* the leg — the loud `session_gone` close carries the name.
|
|
421
421
|
*/
|
|
422
422
|
composite?: true;
|
|
423
|
+
/**
|
|
424
|
+
* THE DUPLEX ENGINE: the backend is a self-turning full-duplex speech
|
|
425
|
+
* engine (the s2s cascade, Moshi-class models) that decides its OWN turns
|
|
426
|
+
* and serves no upstream turn seam. The connection subscribes its voice
|
|
427
|
+
* OUT at connect; the engine's `turn_end` commits the user item but never
|
|
428
|
+
* dispatches a model turn; engine speech opens a SERVER-INITIATED response
|
|
429
|
+
* (`response.output_audio.delta`), closed `completed` by a quiet-track run
|
|
430
|
+
* or `cancelled` by the user's `turn_start`; a client `response.create` is
|
|
431
|
+
* the non-fatal `duplex_engine_owns_turns` error. Requires `voice`.
|
|
432
|
+
*/
|
|
433
|
+
duplex?: boolean;
|
|
423
434
|
/**
|
|
424
435
|
* THE COMPOSITE TURN'S PROMPT CANCEL (ENG-451): stop the ACTIVE turn's
|
|
425
436
|
* legs beyond the turn seam — the composite binding aborts its per-turn
|