@urun-sh/openai 0.6.37 → 0.6.39

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{a as Dn,c as Un,d as $e,e as It,f as te,g as Bn,h as jn,i as Hn,j as Jn,k as Gn,l as Wn,m as Vn,n as zn,r as Kn,t as Xn,u as Yn,v as Qn,w as Zn,x as er}from"./chunk-3JWYIKHM.js";import{a as rn}from"./chunk-6M5JK4YC.js";import{s as Oe}from"./chunk-LLFROK6B.js";import{a as qn,e as ut,f as Nn,i as U,j as Q}from"./chunk-6K7NOPD5.js";import{c as P}from"./chunk-YSFSRI3D.js";P();import{randomUUID as Ts}from"crypto";import{WebSocketServer as Ps}from"ws";var Cs=256,Et=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Cs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Ms="local",lt=n=>n.slice(0,120),Ot=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof U){this.ws.close(Un,lt(e.message));return}if(e instanceof Q){this.ws.close(It,lt(e.message));return}if(e instanceof te){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close($e,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Bn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new te(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=zn(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Xn(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:Kn);return}this.transcript.push(...Yn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new te("setup may only be sent once, as the first client message");let t=Gn(e),r=t.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new te("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",It);if(o.model!==t.model)throw new te(`sessionResumption.handle was issued for model "${o.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new te("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==o.proxyHandle)throw new te(`sessionResumption.handle named pooled session "${o.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,It);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(l=>this.send(Jn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[jn]=Hn(i.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new te("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new te("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",$e);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Zn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new te("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new te("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",$e);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new te(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new te("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new te("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=Ts();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Vn(e.timeLeftMs)),this.ws.close($e,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,o=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new te(`upstream error: ${JSON.stringify(l)}`,$e);if(l.type==="response.completed"){s=l.response,o=!0;continue}let d=Qn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new te("upstream produced no response.completed event",$e);let{messages:i,assistantItems:a}=er(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Fe=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Ls(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let o=n.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Fe(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&i!==void 0&&i!=="")throw new Fe(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new Fe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function tr(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Ps({noServer:!0}),s=new Et;n.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=Ls(i,l,t),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Fe(401,"invalid local proxy api key");c={clients:e.clients,scope:Ms}}r.handleUpgrade(i,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Fe||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Dn,c as Un,d as $e,e as It,f as te,g as Bn,h as jn,i as Hn,j as Jn,k as Gn,l as Wn,m as Vn,n as zn,r as Kn,t as Xn,u as Yn,v as Qn,w as Zn,x as er}from"./chunk-3JWYIKHM.js";import{a as rn}from"./chunk-6M5JK4YC.js";import{s as Oe}from"./chunk-USLITFIB.js";import{a as qn,e as ut,f as Nn,i as U,j as Q}from"./chunk-7AI75MPZ.js";import{c as P}from"./chunk-YSFSRI3D.js";P();import{randomUUID as Ts}from"crypto";import{WebSocketServer as Ps}from"ws";var Cs=256,Et=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Cs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Ms="local",lt=n=>n.slice(0,120),Ot=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof U){this.ws.close(Un,lt(e.message));return}if(e instanceof Q){this.ws.close(It,lt(e.message));return}if(e instanceof te){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close($e,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Bn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new te(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=zn(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Xn(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:Kn);return}this.transcript.push(...Yn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new te("setup may only be sent once, as the first client message");let t=Gn(e),r=t.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new te("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",It);if(o.model!==t.model)throw new te(`sessionResumption.handle was issued for model "${o.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new te("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==o.proxyHandle)throw new te(`sessionResumption.handle named pooled session "${o.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,It);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(l=>this.send(Jn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[jn]=Hn(i.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new te("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new te("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",$e);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Zn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new te("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new te("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",$e);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new te(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new te("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new te("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=Ts();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Vn(e.timeLeftMs)),this.ws.close($e,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,o=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new te(`upstream error: ${JSON.stringify(l)}`,$e);if(l.type==="response.completed"){s=l.response,o=!0;continue}let d=Qn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new te("upstream produced no response.completed event",$e);let{messages:i,assistantItems:a}=er(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Fe=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Ls(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let o=n.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Fe(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&i!==void 0&&i!=="")throw new Fe(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new Fe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function tr(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Ps({noServer:!0}),s=new Et;n.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=Ls(i,l,t),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Fe(401,"invalid local proxy api key");c={clients:e.clients,scope:Ms}}r.handleUpgrade(i,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Fe||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
2
  Connection: close\r
3
3
  \r
4
4
  ${f}\r
@@ -61,4 +61,4 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:A.message}}
61
61
 
62
62
  `):c.write(`data: ${JSON.stringify({error:{message:A.message,type:"upstream_error",code:v}})}
63
63
 
64
- `)),c.end()})}}function Fl(n){let{clients:e,apiKey:t}=n,r=Oi(Qi(n)),s=wr(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),o=mn(r,{resolver:xs(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),tr(r,{clients:e,apiKey:t}),r}P();var Ie=(n,e)=>Object.assign(new Error(e),{status:n}),ta='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ln=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Mn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof U?Ie(404,t.message):t}};async function Es(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ie(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ta}`);if(s==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let o=await Mn(n,t.stt),i=await Mn(n,e),a=await Mn(n,t.tts),u=await n.openAudioOn(o,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,na({clients:n,chatHandle:i,ttsHandle:a,chatModel:e,companions:t},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(o,p)}catch(f){throw f instanceof Q?Ln("stt",t.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Os(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var tn=class extends Error{};async function*na(n,e,t,r){let{clients:s,chatHandle:o,ttsHandle:i,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,S=[],y=null,g=new Promise((I,w)=>{t&&t.addEventListener("abort",()=>w(new tn),{once:!0})}),h=()=>f||t?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await s.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(N){throw N instanceof Q?Ln("tts",u.tts,N):N}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let N=C.next(),q;try{q=await Promise.race([N,g])}catch(B){if(N.catch(()=>{}),B instanceof tn)return;throw B}if(q.done)return;let K=q.value;if(K.type==="error"){let B=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${B}`)}if(K.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;S.length>0&&!h();){let I=S.shift();await _(I)}},A=I=>{if(I===""||h()||(S.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),m??=C})},b=()=>{f=!0,S.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},R=async()=>{for(;S.length>0||y!==null;){let I=y;if(I===null){await _(S.shift());continue}await I}},O=p?new it({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>A(I)):null,x=null;try{let I;try{I=await s.createResponseOn(o,d)}catch(w){throw w instanceof Q?Ln("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}O?.flush(),O?.dispose(),p&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),b();try{if(m instanceof Q)throw m}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function sa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function oa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var ia='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function aa(n,e,t,r){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await n.supportsAudio(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(!s){let d=null;if(n.realtimeCompanionsFor)try{d=await n.realtimeCompanionsFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!==null)return await Es(n,e,d,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ia}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await n.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let a=`conn_${ra()}`,u={audio:await n.openAudioOn(i,t,a)},l={clients:{createResponse:async d=>await n.createResponseOn(i,d,a)},voice:s,audioSession:u};return o&&(l.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),n.releaseSessionHandle&&(l.release=()=>n.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function xs(n,e,t){let r=Os(n,t);return{resolve:async(s,o)=>{if(e!==void 0){let i=s.headers.authorization,a=typeof i=="string"?i.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw ce(401,"invalid local proxy api key")}return aa(r,sa(s),o,oa(s))}}}export{Et as a,tr as b,pa as c,ke as d,le as e,nr as f,$s as g,ba as h,ka as i,_o as j,wr as k,pt as l,pn as m,mn as n,Os as o,sa as p,oa as q,aa as r,xs as s,os as t,ee as u,zu as v,Rn as w,tl as x,nl as y,rl as z,sl as A,ol as B,As as C,Qi as D,Fl as E};
64
+ `)),c.end()})}}function Fl(n){let{clients:e,apiKey:t}=n,r=Oi(Qi(n)),s=wr(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),o=mn(r,{resolver:xs(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),tr(r,{clients:e,apiKey:t}),r}P();var Ie=(n,e)=>Object.assign(new Error(e),{status:n}),ta='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ln=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Mn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof U?Ie(404,t.message):t}};async function Es(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ie(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ta}`);if(s==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let o=await Mn(n,t.stt),i=await Mn(n,e),a=await Mn(n,t.tts),u=await n.openAudioOn(o,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,na({clients:n,chatHandle:i,ttsHandle:a,chatModel:e,companions:t},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(o,p)}catch(f){throw f instanceof Q?Ln("stt",t.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Os(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var tn=class extends Error{};async function*na(n,e,t,r){let{clients:s,chatHandle:o,ttsHandle:i,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,S=[],y=null,g=new Promise((I,w)=>{t&&t.addEventListener("abort",()=>w(new tn),{once:!0})}),h=()=>f||t?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await s.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(N){throw N instanceof Q?Ln("tts",u.tts,N):N}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let N=C.next(),q;try{q=await Promise.race([N,g])}catch(B){if(N.catch(()=>{}),B instanceof tn)return;throw B}if(q.done)return;let K=q.value;if(K.type==="error"){let B=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${B}`)}if(K.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;S.length>0&&!h();){let I=S.shift();await _(I)}},A=I=>{if(I===""||h()||(S.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),m??=C})},b=()=>{f=!0,S.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},R=async()=>{for(;S.length>0||y!==null;){let I=y;if(I===null){await _(S.shift());continue}await I}},O=p?new it({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>A(I)):null,x=null;try{let I;try{I=await s.createResponseOn(o,d)}catch(w){throw w instanceof Q?Ln("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}O?.flush(),O?.dispose(),p&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),b();try{if(m instanceof Q)throw m}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function sa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function oa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var ia='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function aa(n,e,t,r){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await n.supportsAudio(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(!s){let d=null;if(n.realtimeCompanionsFor)try{d=await n.realtimeCompanionsFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!==null)return await Es(n,e,d,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ia}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let a=`conn_${ra()}`,u={audio:await n.openAudioOn(i,t,a)},l={clients:{createResponse:async d=>await n.createResponseOn(i,d,a)},voice:s,audioSession:u};return o&&(l.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),n.releaseSessionHandle&&(l.release=()=>n.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function xs(n,e,t){let r=Os(n,t);return{resolve:async(s,o)=>{if(e!==void 0){let i=s.headers.authorization,a=typeof i=="string"?i.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw ce(401,"invalid local proxy api key")}return aa(r,sa(s),o,oa(s))}}}export{Et as a,tr as b,pa as c,ke as d,le as e,nr as f,$s as g,ba as h,ka as i,_o as j,wr as k,pt as l,pn as m,mn as n,Os as o,sa as p,oa as q,aa as r,xs as s,os as t,ee as u,zu as v,Rn as w,tl as x,nl as y,rl as z,sl as A,ol as B,As as C,Qi as D,Fl as E};
@@ -0,0 +1,2 @@
1
+ import{a as V}from"./chunk-CAR4AEQJ.js";import{f as ne,g as N,h as oe,i as te}from"./chunk-7IWRLQOZ.js";import{c as j,f as G,g as B,p as q}from"./chunk-6M5JK4YC.js";import{a as se,b as U}from"./chunk-5MH6NSR2.js";import{a as T}from"./chunk-4NMMWAKD.js";import{b as K,c as J,d as X,g as Q,j as R,k as M,l as D,m as z,p as Y,q as b,r as Z,s as ee}from"./chunk-7AI75MPZ.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as x,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ee,DEFAULT_WHEN_LIVE_TIMEOUT_MS as le,isWakingPhase as ve,SessionFailedError as Ae}from"@urun-sh/core";A();import{SessionFailedError as ge}from"@urun-sh/core";var C=2;function we(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function ye(e){let i=e?.type;return i==="response.completed"||i==="error"}function ae(e){return async function(c,l){let f=await e.sessionFor(c.model);return(async function*(){for(let d=1;d<=C;d++){let{app:w,entry:g,identity:S}=d===1?f:await e.sessionFor(c.model);l?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let s=!1,a=!1;try{let u=await e.createStream(g,c);for await(let m of u){if(ye(m)&&(s=!0),we(m)){if(d>1)continue}else a=!0;yield m}}catch(u){if(u instanceof ge&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(d<C&&!a){await e.evict(w,g);continue}throw u}if(s)return;if(d<C&&!a){await e.evict(w,g);continue}return}})()}}import{randomUUID as pe}from"crypto";A();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Se="audio";function ce(e){let i=e.streamEndpoint(Se);return{sessionId:e.id,appendInputAudio(c){let l=Buffer.from(c,"base64");l.byteLength!==0&&i.send(he(new Uint8Array(l)))},onOutputAudio(){return()=>{}}}}var Oe=0,be=4,Ie=4;function Qe(e,i){let c=(d,w)=>{let g=(e[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(e[d])})`);return S},l=(e.URUN_DECISION_POOL_MIN??"").trim();if(l==="0")return null;let f=l?Number.parseInt(l,10):Oe;if(!Number.isInteger(f)||f<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=c("URUN_DECISION_POOL_MAX",Math.max(f,be));return{min:f,max:r,idleGraceMs:3e4,inFlightCap:c("URUN_DECISION_POOL_INFLIGHT_CAP",Ie),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function ze(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return N;let c=Number.parseInt(i,10);if(!Number.isInteger(c)||c<=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 c*1e3}function $(e,i,c,l){let f=e[c];if(typeof f!="function")throw new Error(`app "${i}" has no function "${c}" (set URUN_FUNCTION)`);let r=l?f(void 0,l):f();if(typeof r.end!="function")throw new Error(`app "${i}" function "${c}" returned a session without end()`);return r}function ue(e,i,c,l){let{baseUrl:f,orgId:r,auth:d}=e,w=i.fnName??e.fnName,g=e.sessionStartOptions?.(c),S=l||g||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...g,...l}:void 0,s=y=>({session:y,responses:new T(y),gone:se(y,c)});if(d.lane==="jwt"){let y=x(i.appSlug,{baseUrl:f,orgId:r,jwt:d.jwt});return s($(y,i.appSlug,w,S))}if(d.lane==="machine"){let{machineToken:y,gatewayUrl:k}=d,I=(typeof e.subject=="function"?e.subject():e.subject)??pe(),n=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(n,i.appSlug,w,S))}let{apiKey:a,gatewayUrl:u}=d,m=(typeof e.subject=="function"?e.subject():e.subject)??pe(),h=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(a,{baseUrl:u,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:m,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(h,i.appSlug,w,S))}function fe(e){let i=e.session.id;if(typeof i!="string"||i.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 i}function me(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,c=e.status.error?.code;return i===410||i===409&&(c==="cancelled"||c==="expired")?!0:c==="client_ended"}var _e=new Set(["error","paused"]);function Ye(e){let{auth:i,catalog:c}=e,l=null,f=(d,w)=>{let g=ue(e,d,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{l?.evict(w,g)}),g},r=new ee({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:f,closeSession:async d=>{if(d.gone.dispose(),e.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:i.lane==="api-key"?()=>z({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(c?()=>V(c):null),listPrices:c?()=>X(c):null,shared:i.lane==="api-key"?()=>J({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let d=await e.catalogRows();return K(d)}:null,sessionKey:fe});return l=r,e.defaultApp!==null&&r.seed(e.defaultApp,f({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Ze(e,i){let c=e.decisionPool;if(!c)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let l=c.replicaId??"proxy",f=new Map,r=new Map,d=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
2
+ `)},g=(s,a)=>{let u=f.get(a);if(u)return u;let m=new ne({min:c.min,max:c.max,idleGraceMs:c.idleGraceMs,inFlightCap:c.inFlightCap,replicaId:l,openSlot:async h=>{let y=ue(e,s,a,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>m.markSessionDead(y)),await L(y.session),w(`slot attached pool=${a} 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=${a} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof Ae&&me(h)});return r.set(a,{target:s,env:c}),f.set(a,m),m},S=async(s,a)=>{let u=r.get(a);if(u)try{let m=await i.poolTuningFor(s);g(s,a).retune({min:m?.min??u.env.min,max:m?.max??u.env.max,inFlightCap:m?.in_flight_cap??u.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){w(`pool tuning refresh failed pool=${a} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await g(s,b(s)).boot()},async sessionFor(s){let a=await i.resolveTargetFor(s),u=b(a),m=g(a,u);await S(a,u);let h=await m.acquire({timeoutMs:m.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:u,entry:h.entry,identity:Z(a)}},async warmFor(s){let a=await i.resolveTargetFor(s);await g(a,b(a)).boot()},end(s){let a=d.get(s)?.shift();a&&(d.get(s)?.length===0&&d.delete(s),a.release())},evict(s){for(let a of f.values())a.evict(s)},markSessionDead(s){for(let a of f.values())a.markSessionDead(s)},reap(){for(let[s,{target:a}]of r)S(a,s).then(()=>{let u=f.get(s);u&&u.reap()})},async pingReady(s){for(let a of f.values())if(await a.pingReady(s))return!0;return!1},stats(){return[...f.entries()].map(([s,a])=>({poolKey:s,...a.stats()}))},async drain(s){await Promise.all([...f.values()].map(a=>a.drain({timeoutMs:s})))},async close(){await Promise.all([...f.values()].map(s=>s.close()))}}}function Le(e){return ve(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le:Ee:le}async function L(e,i){let c=e.whenLive;if(typeof c!="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 c.call(e,{timeout:Le(e.phase),signal:i})}async function H(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 _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function en(e,i=B,c,l,f=N,r){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,s=new WeakMap,a=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",m=n=>{let o=D(n);if(!r||!o||o.app!==u)return null;let t=r.entryFor(o.key);if(!t)throw new R(`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=>m(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=d.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let p=await j(n.session,await i());return Object.assign(p,{sessionId:n.session.id})})(),d.set(n,o),o.catch(()=>{d.get(n)===o&&d.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:p=>t.appendInputAudio(p),onOutputAudio:p=>t.onOutputAudio(p),sessionId:a(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=s.get(n);throw(d.get(n)===void 0||E!==void 0&&E.waiting===0)&&await H(n.session),_(t)}let p=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?p:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),d.delete(n),S.delete(n),H(n.session).catch(()=>{})),v(_(t))};t.addEventListener("abort",O,{once:!0});let W=()=>t.removeEventListener("abort",O);p.then(F=>{W(),E(F)},F=>{W(),v(F)})})};return{createResponse:ae({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return l?l.sessionFor(n):e.sessionFor(n)}:l?n=>l.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>a(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):l?l.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{me(t)&&(r&&r.owns(o)?r.evict(o):l?l.markSessionDead(o):e.evict(n,o),c?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=oe(U(await n.responses.responses.create(o),n.gone),f);if(!l&&!r)return t;let p=n;return(async function*(){try{yield*t}catch(E){throw te(E)&&(r&&r.owns(p)?r.evict(p):l&&(E instanceof R?l.markSessionDead(p):l.evict(p))),E}finally{r&&r.owns(p)?r.release(p):l?.end(p)}})()}catch(t){throw r&&r.owns(n)?r.release(n):l&&l.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{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let p=m(n);if(p){let E=p.entry.session;return ce(E)}let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await h(n);yield*Q(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=G(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=q(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),p=a(t.entry);if(p===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return M(u,p)}}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:p}=await e.dedicatedSessionFor(n);return M(t,fe(p))},releaseSessionHandle:n=>{let o=D(n);if(!o)return;if(o.app.startsWith(Y)){(async()=>{let p=null;try{p=(await e.sessionForHandle(n)).entry}catch{return}await H(p.session).catch(()=>{}),await e.evict(o.app,p)})();return}if(!r||o.app!==u)return;let t=r.entryFor(o.key);t&&r.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 p=await h(n);await L(p.session);let P=t!==void 0&&m(n)?new T({...p.session,consumerId:t},{sessionTag:t}):p.responses;return U(await P.responses.create(o),p.gone)},onSessionEnd:async(n,o)=>{let t=m(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:p}=await e.sessionForHandle(n),P=p.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||!_e.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{Qe as a,ze as b,Ye as c,Ze as d,en as e};
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-6K7NOPD5.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.37";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-7AI75MPZ.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.39";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}
@@ -306,6 +306,14 @@ declare class ModelRouter<S> {
306
306
  identity: TurnCatalogIdentity;
307
307
  }>;
308
308
 
309
+ dedicatedSessionFor(model: string | undefined): Promise<{
310
+ app: string;
311
+ entry: S;
312
+ identity: TurnCatalogIdentity;
313
+ }>;
314
+
315
+ evictHandle(handle: string): Promise<void>;
316
+
309
317
  private acquire;
310
318
  private keyOf;
311
319
 
@@ -602,6 +610,8 @@ interface ProxyClients {
602
610
 
603
611
  releaseSessionHandle?(handle: string): void;
604
612
 
613
+ dedicatedSessionHandle?(model: string | undefined): Promise<string>;
614
+
605
615
  speechSessionHandle?(model: string | undefined): Promise<string>;
606
616
 
607
617
  evictSpeechSession?(handle: string): Promise<void>;
@@ -443,62 +443,6 @@ interface SharedCatalogBlock {
443
443
  } | null;
444
444
  }
445
445
 
446
- /**
447
- * Per-model → per-app routing for the compat proxy (owner directive
448
- * 2026-08-07): swapping the model in a coding harness routes the request to
449
- * the org's DEPLOYED app for that model. v1 is deployed-only — a uRun model
450
- * that is not deployed gets a loud 404 naming `urun serve <id>`; a later
451
- * phase (explicitly out of scope here; urun-infra#1490 shared-endpoints)
452
- * auto-creates from the model catalog on first request.
453
- *
454
- * MODEL-ID SURFACE (the documented mapping): a model may be named by
455
- * - the app slug itself ("qwen3-6-27b-bf16"), or
456
- * - the catalog id ("qwen3.6-27b"), or
457
- * - the catalog id:variant ("qwen3.6-27b:bf16"),
458
- * where slugification mirrors urun-cli `serve.py _default_app_name` exactly:
459
- * lowercase, every non-alphanumeric-non-dash character becomes "-", leading/
460
- * trailing dashes stripped (catalog id "qwen3.6-27b" + variant "bf16" → app
461
- * "qwen3-6-27b-bf16"). COLLISION RULE (within one namespace): an exact slug
462
- * match always wins over the catalog-id (prefix) interpretation. ACROSS
463
- * namespaces the SHARED catalog wins: a raw id that names a catalog `shared`
464
- * model resolves to the shared lane even when the caller's own org deploys an
465
- * app with a colliding slug (see rule 2).
466
- *
467
- * RESOLUTION ORDER (one canonical path, documented end to end):
468
- * 1. model absent / "urun" / an alias of the startup app → DEFAULT app.
469
- * 2. the raw id names a catalog `shared` model — exact id, `id:variant`, or
470
- * the slugified-equal id form → the SHARED org's app (`sharedApp: true`,
471
- * the cross-org dial). THIS OUTRANKS the caller-org slug match below:
472
- * the shared block is the platform namespace every surface advertises, so
473
- * a caller-org app whose slug collides with a shared model must not
474
- * shadow it (the pre-2026-10-06 rule let it). ELSEWISE, an exact slug
475
- * match on a deployed app that declares serves="openai" → that app.
476
- * 3. catalog-id form matching exactly one deployed app → that app
477
- * (two or more candidates → loud ambiguity error naming them).
478
- * 4. the name maps to an org app that has NO function declaring the
479
- * serve protocol (`serves="openai"`) → loud 404
480
- * naming `urun serve <model>` and the available models.
481
- * 5. the name matches a catalog row but no deployed app → loud 404
482
- * naming `urun serve <id>` (deployed-only v1).
483
- * 6. anything else — a model name outside the uRun namespace entirely
484
- * (e.g. the harness's own upstream default, "claude-*"/"gpt-*") →
485
- * DEFAULT app. This IS today's single-app contract, kept deliberately
486
- * so `urun compat <agent>` with the agent's stock model keeps working
487
- * with zero new env; the per-model /stats table records every such
488
- * mapping so it is visible, never silent. Models the proxy ADVERTISES
489
- * on /v1/models can never land here — they resolve (2/3) or fail loud
490
- * (4/5) above.
491
- *
492
- * NO-DEFAULT MODE (`defaultApp: null`) — the HOSTED multi-tenant lane
493
- * (`src/hosted/`): a shared endpoint serving every org has no "the app this
494
- * proxy was started for", so rules 1 and 6 have nothing to fall back TO.
495
- * Rather than inventing one (picking "some" app for a caller would be the
496
- * worst kind of silent divergence), both rules become the SAME loud
497
- * {@link UnknownModelError} that rules 4/5 already raise: name a deployed
498
- * model, here is the list. Rules 2–5 are byte-for-byte the local behavior —
499
- * one router, one resolution order, two configurations.
500
- */
501
-
502
446
  /** One org app row from `GET {orgApi}/apps` (urun-cli `ApiClient.list_apps`). */
503
447
  interface DeployedApp {
504
448
  app_slug: string;
@@ -1075,6 +1019,32 @@ declare class ModelRouter<S> {
1075
1019
  entry: S;
1076
1020
  identity: TurnCatalogIdentity;
1077
1021
  }>;
1022
+ /**
1023
+ * A DEDICATED pooled session for one caller's exclusive use (owner ruling
1024
+ * 2026-10-27: "realtime ticks should be getting an isolated session, chats
1025
+ * only share with each other") — the realtime binding's session seam. The
1026
+ * SAME acquisition path every other pool slot rides ({@link openSession}
1027
+ * — shared targets mint the shared-app-constrained token and start the
1028
+ * session with `shared_app: true`), under a UNIQUE `realtime:<uuid>` pool
1029
+ * key minted per call: two calls NEVER share an entry, and no other lane
1030
+ * (chat included) can resolve the slot. Lifecycle is the pool's own — the
1031
+ * `openSession` wiring's gone-watch evicts a dead entry, and the realtime
1032
+ * binding's connection release rides {@link evictHandle} (native detach
1033
+ * underneath, the named session stays live per session semantics).
1034
+ */
1035
+ dedicatedSessionFor(model: string | undefined): Promise<{
1036
+ app: string;
1037
+ entry: S;
1038
+ identity: TurnCatalogIdentity;
1039
+ }>;
1040
+ /**
1041
+ * Release the pooled session a handle names WITHOUT touching anything
1042
+ * shared: the dedicated slot's pool entry is dropped and the native
1043
+ * session is detached (never `end()`). Malformed/unknown/gone handles are
1044
+ * a NO-OP — the release's goal is already true — never a throw on the
1045
+ * connection's teardown path.
1046
+ */
1047
+ evictHandle(handle: string): Promise<void>;
1078
1048
  /**
1079
1049
  * The ONE acquisition path both lanes ride — opened lazily under exactly
1080
1050
  * `key`, reused afterwards. A failed open never poisons the slot.
@@ -2517,6 +2487,19 @@ interface ProxyClients {
2517
2487
  sessionHandle(model: string | undefined): Promise<string>;
2518
2488
  /** Release the lease {@link sessionHandle} took on a lane; a no-op for a pooled handle. */
2519
2489
  releaseSessionHandle?(handle: string): void;
2490
+ /**
2491
+ * THE REALTIME ISOLATION SEAM (owner ruling 2026-10-27): the session handle
2492
+ * a REALTIME connection rides — its OWN dedicated session, never the shared
2493
+ * lane chat serves from. On a SHARED target this mints a per-connection
2494
+ * native uRun session (its own dispatch demand ⇒ its own seat while
2495
+ * attached; released on connection close through the native detach — the
2496
+ * platform's pause/park, never an end). On a NON-SHARED target the pooled
2497
+ * handle is already the caller's own slot and is answered unchanged.
2498
+ * Optional at the seam: a composition that wires none keeps
2499
+ * {@link sessionHandle} (the realtime binding falls back), so the local
2500
+ * compat proxy and existing test doubles are untouched.
2501
+ */
2502
+ dedicatedSessionHandle?(model: string | undefined): Promise<string>;
2520
2503
  /**
2521
2504
  * THE SPEECH LANE'S OWN HANDLE (greptile urun-ts#500): the opaque handle
2522
2505
  * for the SPEECH-SCOPED pooled session (`speech:<pool key>` — routing.ts