@urun-sh/openai 0.6.40 → 0.6.41

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,2 +1,2 @@
1
- import{a as Q}from"./chunk-CAR4AEQJ.js";import{f as re,g as U,h as ae,i as ce}from"./chunk-G5VRFFBE.js";import{c as J,f as M,g as X,p as z}from"./chunk-Z3QCHKJB.js";import{a as de,b as C}from"./chunk-L4QBHSVY.js";import{a as D}from"./chunk-4NMMWAKD.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as x,l as N,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-HPUX2H65.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as j,createClientToken as fe,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as me,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";A();import{SessionFailedError as he}from"@urun-sh/core";var V=2;function Se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function Pe(e){let s=e?.type;return s==="response.completed"||s==="error"}function le(e){return async function(a,p){let m=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=V;l++){let{app:w,entry:g,identity:S}=l===1?m:await e.sessionFor(a.model);p?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let i=!1,d=!1;try{let u=await e.createStream(g,a);for await(let f of u){if(Pe(f)&&(i=!0),Se(f)){if(l>1)continue}else d=!0;yield f}}catch(u){if(u instanceof he&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(l<V&&!d){await e.evict(w,g);continue}throw u}if(i)return;if(l<V&&!d){await e.evict(w,g);continue}return}})()}}import{randomUUID as ge}from"crypto";A();import{encodeStreamEnvelope as Ee}from"@urun-sh/core";var ve="audio";function pe(e){let s=e.streamEndpoint(ve);return{sessionId:e.id,appendInputAudio(a){let p=Buffer.from(a,"base64");p.byteLength!==0&&s.send(Ee(new Uint8Array(p)))},onOutputAudio(){return()=>{}}}}A();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function ue(e){let s=e.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(e,s){let a=(l,w)=>{let g=(e[l]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},p=(e.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let m=p?Number.parseInt(p,10):_e;if(!Number.isInteger(m)||m<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(m,ke));return{min:m,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=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 a*1e3}function W(e,s,a,p){let m=e[a];if(typeof m!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?m(void 0,p):m();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function we(e,s,a,p){let{baseUrl:m,orgId:c,auth:l}=e,w=s.fnName??e.fnName,g=e.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new D(y),gone:de(y,a)});if(l.lane==="jwt"){let y=j(s.appSlug,{baseUrl:m,orgId:c,jwt:l.jwt});return i(W(y,s.appSlug,w,S))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:F}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??ge(),L=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:d,gatewayUrl:u}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ge(),h=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(d,{baseUrl:u,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:f,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function ye(e){let s=e.session.id;if(typeof s!="string"||s.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 s}function q(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(e){let{auth:s,catalog:a}=e,p=null,m=(l,w)=>{let g=we(e,l,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:m,closeSession:async l=>{if(l.gone.dispose(),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:s.lane==="api-key"?()=>oe({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:e.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:s.lane==="api-key"?()=>Z({apiUrl:e.apiUrl,apiKey:s.apiKey}):s.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return Y(l)}:null,sessionKey:ye});return p=c,e.defaultApp!==null&&c.seed(e.defaultApp,m({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),c}function cn(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",m=new Map,c=new Map,l=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
1
+ import{a as Q}from"./chunk-CAR4AEQJ.js";import{f as re,g as U,h as ae,i as ce}from"./chunk-PAAFRUQZ.js";import{c as J,f as M,g as X,p as z}from"./chunk-Z3QCHKJB.js";import{a as de,b as C}from"./chunk-L4QBHSVY.js";import{a as D}from"./chunk-4NMMWAKD.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as x,l as N,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-HPUX2H65.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as j,createClientToken as fe,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as me,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";A();import{SessionFailedError as he}from"@urun-sh/core";var V=2;function Se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function Pe(e){let s=e?.type;return s==="response.completed"||s==="error"}function le(e){return async function(a,p){let m=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=V;l++){let{app:w,entry:g,identity:S}=l===1?m:await e.sessionFor(a.model);p?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let i=!1,d=!1;try{let u=await e.createStream(g,a);for await(let f of u){if(Pe(f)&&(i=!0),Se(f)){if(l>1)continue}else d=!0;yield f}}catch(u){if(u instanceof he&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(l<V&&!d){await e.evict(w,g);continue}throw u}if(i)return;if(l<V&&!d){await e.evict(w,g);continue}return}})()}}import{randomUUID as ge}from"crypto";A();import{encodeStreamEnvelope as Ee}from"@urun-sh/core";var ve="audio";function pe(e){let s=e.streamEndpoint(ve);return{sessionId:e.id,appendInputAudio(a){let p=Buffer.from(a,"base64");p.byteLength!==0&&s.send(Ee(new Uint8Array(p)))},onOutputAudio(){return()=>{}}}}A();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function ue(e){let s=e.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(e,s){let a=(l,w)=>{let g=(e[l]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},p=(e.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let m=p?Number.parseInt(p,10):_e;if(!Number.isInteger(m)||m<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(m,ke));return{min:m,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=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 a*1e3}function W(e,s,a,p){let m=e[a];if(typeof m!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?m(void 0,p):m();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function we(e,s,a,p){let{baseUrl:m,orgId:c,auth:l}=e,w=s.fnName??e.fnName,g=e.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new D(y),gone:de(y,a)});if(l.lane==="jwt"){let y=j(s.appSlug,{baseUrl:m,orgId:c,jwt:l.jwt});return i(W(y,s.appSlug,w,S))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:F}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??ge(),L=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:d,gatewayUrl:u}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ge(),h=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(d,{baseUrl:u,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:f,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function ye(e){let s=e.session.id;if(typeof s!="string"||s.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 s}function q(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(e){let{auth:s,catalog:a}=e,p=null,m=(l,w)=>{let g=we(e,l,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:m,closeSession:async l=>{if(l.gone.dispose(),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:s.lane==="api-key"?()=>oe({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:e.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:s.lane==="api-key"?()=>Z({apiUrl:e.apiUrl,apiKey:s.apiKey}):s.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return Y(l)}:null,sessionKey:ye});return p=c,e.defaultApp!==null&&c.seed(e.defaultApp,m({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),c}function cn(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",m=new Map,c=new Map,l=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
2
2
  `)},g=(i,d)=>{let u=m.get(d);if(u)return u;let f=new re({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:p,openSlot:async h=>{let y=we(e,i,d,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>f.markSessionDead(y)),await T(y.session),w(`slot attached pool=${d} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${d} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof B&&q(h)});return c.set(d,{target:i,env:a}),m.set(d,f),f},S=async(i,d)=>{let u=c.get(d);if(u)try{let f=await s.poolTuningFor(i);g(i,d).retune({min:f?.min??u.env.min,max:f?.max??u.env.max,inFlightCap:f?.in_flight_cap??u.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){w(`pool tuning refresh failed pool=${d} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let i={appSlug:e.defaultApp};await g(i,b(i)).boot()},async sessionFor(i){let d=await s.resolveTargetFor(i),u=b(d),f=g(d,u);await S(d,u);let h=await f.acquire({timeoutMs:f.requestWaitMs}),y=l.get(h.entry)??[];return y.push(h),l.set(h.entry,y),{app:u,entry:h.entry,identity:se(d)}},async warmFor(i){let d=await s.resolveTargetFor(i);await g(d,b(d)).boot()},end(i){let d=l.get(i)?.shift();d&&(l.get(i)?.length===0&&l.delete(i),d.release())},evict(i){for(let d of m.values())d.evict(i)},markSessionDead(i){for(let d of m.values())d.markSessionDead(i)},reap(){for(let[i,{target:d}]of c)S(d,i).then(()=>{let u=m.get(i);u&&u.reap()})},async pingReady(i){for(let d of m.values())if(await d.pingReady(i))return!0;return!1},stats(){return[...m.entries()].map(([i,d])=>({poolKey:i,...d.stats()}))},async drain(i){await Promise.all([...m.values()].map(d=>d.drain({timeoutMs:i})))},async close(){await Promise.all([...m.values()].map(i=>i.close()))}}}function Re(e){return Le(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?me:Ie:me}async function T(e,s){let a=e.whenLive;if(typeof a!="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 a.call(e,{timeout:Re(e.phase),signal:s})}async function G(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()}function k(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function dn(e,s=X,a,p,m=U,c){let l=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,i=new WeakMap,d=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",f=n=>{let o=N(n);if(!c||!o||o.app!==u)return null;let t=c.entryFor(o.key);if(!t)throw new _(`the lane behind this handle (${o.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:o.key,entry:t}},h=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=l.get(n);if(!o){let t={waiting:0,gone:new AbortController};i.set(n,t),o=(async()=>{if(await T(n.session,t.gone.signal),t.gone.signal.aborted)throw k(t.gone.signal);i.get(n)===t&&i.delete(n);let r=await J(n.session,await s());return Object.assign(r,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{i.get(n)===t&&i.delete(n)},()=>{i.get(n)===t&&i.delete(n)})}return o},F=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:r=>t.appendInputAudio(r),onOutputAudio:r=>t.onOutputAudio(r),sessionId:d(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=i.get(n);throw(l.get(n)===void 0||E!==void 0&&E.waiting===0)&&await G(n.session),k(t)}let r=o(n),P=i.get(n);return P!==void 0&&P.waiting++,t===void 0?r:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&i.get(n)===P&&(P.gone.abort(),i.delete(n),l.delete(n),S.delete(n),G(n.session).catch(()=>{})),v(k(t))};t.addEventListener("abort",O,{once:!0});let K=()=>t.removeEventListener("abort",O);r.then(R=>{K(),E(R)},R=>{K(),v(R)})})},L=async(n,o,t)=>{try{return await t}catch(r){throw(r instanceof _||r instanceof B&&q(r))&&(e.evict(n,o),r instanceof B&&a?.(n,r.kind==="never-live"?"never-live":"create-failed")),r}};return{createResponse:le({sessionFor:c?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return p?p.sessionFor(n):e.sessionFor(n)}:p?n=>p.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>d(n),evict:(n,o)=>{c&&c.owns(o)?c.evict(o):p?p.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{q(t)&&(c&&c.owns(o)?c.evict(o):p?p.markSessionDead(o):e.evict(n,o),a?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await T(n.session);let t=ae(C(await n.responses.responses.create(o),n.gone),m);if(!p&&!c)return t;let r=n;return(async function*(){try{yield*t}catch(E){throw ce(E)&&(c&&c.owns(r)?c.evict(r):p&&(E instanceof _?p.markSessionDead(r):p.evict(r))),E}finally{c&&c.owns(r)?c.release(r):p?.end(r)}})()}catch(t){throw c&&c.owns(n)?c.release(n):p&&p.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),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,o)=>{let{app:t,entry:r}=await e.sessionFor(n);return await L(t,r,I(r,y,o))},openAudioOn:async(n,o,t)=>{let r=f(n);if(r){let v=r.entry.session;return pe(v)}let{app:P,entry:E}=await e.sessionForHandle(n);return await L(P,E,I(E,F,o))},openTurnsOn:async function*(n,o){if(o?.aborted)throw k(o);let t=await h(n);yield*ne(t.session,o)},openVideoOn:async n=>{let o=f(n);if(o)return ue(o.entry.session);let{entry:t}=await e.sessionForHandle(n),r=w.get(t);return r||(r=M(t.session),w.set(t,r)),r},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=M(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=z(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(c){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o),r=d(t.entry);if(r===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return x(u,r)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:t,entry:r}=await e.dedicatedSessionFor(n);return x(t,ye(r))},releaseSessionHandle:n=>{let o=N(n);if(!o)return;if(o.app.startsWith(te)){(async()=>{let r=null;try{r=(await e.sessionForHandle(n)).entry}catch{return}await G(r.session).catch(()=>{}),await e.evict(o.app,r)})();return}if(!c||o.app!==u)return;let t=c.entryFor(o.key);t&&c.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let r=await h(n);await T(r.session);let P=t!==void 0&&f(n)?new D({...r.session,consumerId:t},{sessionTag:t}):r.responses;return C(await P.responses.create(o),r.gone)},onSessionEnd:async(n,o)=>{let t=f(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:r}=await e.sessionForHandle(n),P=r.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!Fe.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{sn as a,rn as b,an as c,cn as d,dn as e};
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-HPUX2H65.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.40";var y=4141,R=g,J={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 P(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 B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(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(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(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=_(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 V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(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 c(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 Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(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 d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}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 N(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 Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(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 k=250;async function A(e,t=k){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:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(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 ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(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 te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
1
+ import{h as m}from"./chunk-HPUX2H65.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.41";var y=4141,R=g,J={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 P(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 B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(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(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(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=_(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 V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(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 c(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 Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(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 d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}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 N(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 Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(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 k=250;async function A(e,t=k){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:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(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 ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(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 te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(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 ie(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}