@urun-sh/openai 0.6.47 → 0.6.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-VRNM6ZKU.js → chunk-2KMMXZLV.js} +1 -1
- package/dist/{chunk-5D7TVOAX.js → chunk-3JZAWWVV.js} +1 -1
- package/dist/{chunk-2KN45E7P.js → chunk-ELH2AYM6.js} +1 -1
- package/dist/{chunk-LROCLDDN.js → chunk-NZ5EWOMJ.js} +1 -1
- package/dist/{chunk-P2YVKUSQ.js → chunk-X23WP5HQ.js} +2 -2
- package/dist/hosted/bin.cjs +1 -1
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +36 -33
- package/dist/pooler/bin.cjs +5 -5
- package/dist/pooler/bin.js +9 -9
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
package/dist/proxy/cli.cjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function ku(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||pe(`${r.model_id}-${r.variant}`)===e.appSlug||pe(r.model_id)===e.appSlug)),n?Su(n.engine_args?.pool):null}function ar(t,e,n,r,o){if(!o)throw new ee(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new ee(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new ee(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Vo(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new ee(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Yo="shared:",Jo="speech:",Mt="realtime:";function Ue(t){return t.sharedApp?Yo+t.appSlug:t.appSlug}function Pt(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function lr(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>pe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function xu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ru(t){let e=t.map(xu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Eu={stt:"stt",tts:"tts"};function Ne(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:Eu[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Xo(t,e){let n=lr(t,e);return n.length>0?n:sr(t,e)}function Ot(t,e){return Xo(t.appSlug,e)}function Au(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new ee(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var un=6e4,ln=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??un):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??un):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??un):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??un;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ge)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
5
5
|
`),At}let r=Co(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
|
|
6
6
|
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(nr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Yo)||o.startsWith(Jo)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new J(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=rr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,u=pe(s),a=n.endpoints.filter(c=>pe(c.model_id)===u&&(i===void 0||c.variant===i)),l=new Set(a.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:rr(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};n=n.replace(/^urun\//i,"");let o=pe(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),u=this.servable(i);if(u.includes(o))return{appSlug:o};let a=u.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new J(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new J(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let u=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===pe(a.model_id)||o===pe(`${a.model_id}-${a.variant}`));if(u)throw new J(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${u.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Pt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return ku(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ue(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ue(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Pt(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Jo+Ue(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Mt+(0,Wo.randomUUID)())}async evictHandle(e){let n=Ve(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Pt(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Ct(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Ct(n,this.keyOf(r))}}async sessionForHandle(e){let n=Ve(e);if(!n)throw new W(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(u=>u,()=>null):null;if(i===null)throw new W(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o&&this.mintedIds.get(i)!==o)throw new W(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:At;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
7
|
-
`);let a=(n?it(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=sn(d),p=at(d),m=or(d),g=Et(l.model_id,l.variant,i),v=ir(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>an(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ho(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=ar(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Vo(`${r.modelId}:${r.variant}`,s).includes(n)}return Go(lr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ne(Ot(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ne(Ot(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ne(Ot(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return Au(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return ir(o)}async imageModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds()){let i=Go(lr(s,e));i.length!==0&&r.push(Ge({...an(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Vo(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds())Ne(Xo(s,e))==="stt"&&r.push(an(s,e,n));let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ne(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var De=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},$t=class extends De{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},pr=class extends De{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},dn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new $t;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let a=r+n-Date.now();if(a<=0)throw new pr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var fr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},pn=33e4;function Qo(t,e=pn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new cn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof W||l instanceof fr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof cn?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var cn=class extends Error{constructor(){super("stream idle timeout")}};function Zo(t){return t instanceof Se?!1:t instanceof W?!0:t instanceof fr.SessionFailedError?t.kind==="transport-failed":!1}var Iu=require("http");var fn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var mr=require("@urun-sh/core"),Tu="audio";function es(t){let e=t.streamEndpoint(Tu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,mr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,mr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var ts=require("@urun-sh/core"),Ou="rt-video-in";function ns(t){let e=t.streamEndpoint(Ou);return{sendInputFrame:async n=>{e.send((0,ts.encodeStreamEnvelope)(n))}}}var Pu=3,Cu="llm",Mu=new Set(["paused","error"]);function rs(t,e,n){let r=t.doc(Cu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Pu||d(new W(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Mu.has(c.name)&&d(new W(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*gr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Lu=0,Nu=4,Uu=4;function ss(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Lu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Nu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Uu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function is(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return pn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function hr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function as(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new kt(v),gone:rs(v,n)});if(i.lane==="jwt"){let v=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:k}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),_=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(v,{baseUrl:k,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(_,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),g=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(g,e.appSlug,u,l))}function us(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function wr(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Du=new Set(["error","paused"]);function ls(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=as(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new ln({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>vo(n):null),listPrices:n?()=>Mo(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return $o(i)}:e.lane==="api-key"?()=>Lo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:us});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ue({appSlug:t.defaultApp}))),s}function ds(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
7
|
+
`);let a=(n?it(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=sn(d),p=at(d),m=or(d),g=Et(l.model_id,l.variant,i),v=ir(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>an(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ho(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=ar(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Vo(`${r.modelId}:${r.variant}`,s).includes(n)}return Go(lr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ne(Ot(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ne(Ot(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ne(Ot(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return Au(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return ir(o)}async imageModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds()){let i=Go(lr(s,e));i.length!==0&&r.push(Ge({...an(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Vo(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds())Ne(Xo(s,e))==="stt"&&r.push(an(s,e,n));let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ne(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var De=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},$t=class extends De{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},pr=class extends De{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},dn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new $t;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let a=r+n-Date.now();if(a<=0)throw new pr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var fr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},pn=33e4;function Qo(t,e=pn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new cn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof W||l instanceof fr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof cn?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var cn=class extends Error{constructor(){super("stream idle timeout")}};function Zo(t){return t instanceof Se?!1:t instanceof W?!0:t instanceof fr.SessionFailedError?t.kind==="transport-failed":!1}var Iu=require("http");var fn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var mr=require("@urun-sh/core"),Tu="audio";function es(t){let e=t.streamEndpoint(Tu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,mr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,mr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var ts=require("@urun-sh/core"),Ou="rt-video-in";function ns(t){let e=t.streamEndpoint(Ou);return{sendInputFrame:async n=>{e.send((0,ts.encodeStreamEnvelope)(n))}}}var Pu=3,Cu="llm",Mu=new Set(["paused","error"]);function rs(t,e,n){let r=t.doc(Cu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Pu||d(new W(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Mu.has(c.name)&&d(new W(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*gr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Lu=0,Nu=4,Uu=4;function ss(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Lu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Nu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Uu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function is(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return pn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function hr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function as(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new kt(v),gone:rs(v,n)});if(i.lane==="jwt"){let v=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:k}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),_=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(v,{baseUrl:k,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(_,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),g=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(g,e.appSlug,u,l))}function us(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function wr(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Du=new Set(["error","paused"]);function ls(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=as(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new ln({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>vo(n):null),listPrices:n?()=>Mo(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return $o(i)}:e.lane==="api-key"?()=>Lo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:us});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ue({appSlug:t.defaultApp}))),s}function ds(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
8
8
|
`)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new dn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let v=as(t,d,c,{concurrencyKey:g.concurrencyKey});return v.gone.onGone(k=>k.bindingLost?m.evict(v):m.markSessionDead(v)),await gn(v.session),u(`slot attached pool=${c} slot=${g.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async g=>{g.gone.dispose(),g.audioDispose?.(),await g.session.end()},onDetach:(g,v)=>u(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${v}`),terminalOpenFailure:g=>g instanceof oe.SessionFailedError&&wr(g)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ue(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ue(c),m=a(c,p);await l(c,p);let g=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(g.entry)??[];return v.push(g),i.set(g.entry,v),{app:p,entry:g.entry,identity:Pt(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ue(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Fu(t){return(0,oe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:oe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function gn(t,e){let n=t.whenLive;if(typeof n!="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 n.call(t,{timeout:Fu(t.phase),signal:e})}async function Bu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.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");t.detach()}async function os(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function mn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function cs(t,e=rn,n,r,o=pn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let h=f.session.id;return typeof h=="string"&&h.length>0?h:null},p="lane",m=f=>{let h=Ve(f);if(!s||!h||h.app!==p)return null;let w=s.entryFor(h.key);if(!w)throw new W(`the lane behind this handle (${h.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:h.key,entry:w}},g=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let h=i.get(f);if(!h){let w={waiting:0,gone:new AbortController};d.set(f,w),h=(async()=>{if(await gn(f.session,w.gone.signal),w.gone.signal.aborted)throw mn(w.gone.signal);d.get(f)===w&&d.delete(f);let b=await _o(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,h),h.then(b=>{i.get(f)===h&&(f.audioDispose=()=>b.dispose())},()=>{}),h.catch(()=>{i.get(f)===h&&i.delete(f)}),h.then(()=>{d.get(f)===w&&d.delete(f)},()=>{d.get(f)===w&&d.delete(f)})}return h},k=f=>{let h=l.get(f);return h||(h=(async()=>{let w=await v(f);return{appendInputAudio:(b,R)=>w.appendInputAudio(b,R),onOutputAudio:b=>w.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,h),h.catch(()=>{l.get(f)===h&&l.delete(f)})),h},S=async(f,h,w,b=!1)=>{let R=()=>b?os(f.session):Bu(f.session);if(w?.aborted){let y=d.get(f);throw(i.get(f)===void 0||y!==void 0&&y.waiting===0)&&await R().catch(()=>{}),mn(w)}let E=h(f),A=d.get(f);return A!==void 0&&A.waiting++,w===void 0?E:new Promise((y,x)=>{let T=()=>{A!==void 0&&--A.waiting===0&&d.get(f)===A&&(A.gone.abort(),d.delete(f),i.delete(f),l.delete(f),R().catch(()=>{})),x(mn(w))};w.addEventListener("abort",T,{once:!0});let C=()=>w.removeEventListener("abort",T);E.then(B=>{C(),y(B)},B=>{C(),x(B)})})},_=async(f,h,w)=>{try{return await w}catch(b){throw(b instanceof W||b instanceof oe.SessionFailedError&&wr(b))&&(t.evict(f,h),b instanceof oe.SessionFailedError&&n?.(f,b.kind==="never-live"?"never-live":"create-failed")),b}};return{createResponse:Io({sessionFor:s?async f=>{let h=await t.resolveTargetFor(f);if(h.sharedApp)try{let w=await s.sessionFor(f,h);return{app:w.app,entry:w.entry,identity:w.identity}}catch(w){if(w instanceof en)return r?r.sessionFor(f):t.sessionFor(f);if(w instanceof fn)return console.error(`[pooler-fallback] pooler channel failed for ${f} (${w.name} ${w.code}: ${w.message}) \u2014 serving via the per-request path`),r?r.sessionFor(f):t.sessionFor(f);throw w}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,h)=>{s&&s.owns(h)?s.evict(h):r?r.evict(h):t.evict(f,h)},onAdmissionVerdict:(f,h,w)=>{wr(w)&&(s&&s.owns(h)?s.evict(h):r?r.markSessionDead(h):t.evict(f,h),n?.(f,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,h)=>{try{await gn(f.session);let w=Qo(gr(await f.responses.responses.create(h),f.gone),o);if(!r&&!s)return w;let b=f;return(async function*(){try{yield*w}catch(E){throw Zo(E)&&(s&&s.owns(b)?s.evict(b):r&&(E instanceof W&&!E.bindingLost?r.markSessionDead(b):r.evict(b))),E}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(w){throw s&&s.owns(f)?s.release(f):r&&r.end(f),w}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,h)=>t.supportsImages(f,h),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,h)=>{let{app:w,entry:b}=await t.sessionFor(f);return await _(w,b,S(b,v,h))},openAudioOn:async(f,h,w,b)=>{let R=m(f);if(R){let x=R.entry.session;return es(x)}let{app:E,entry:A}=await t.sessionForHandle(f);if(b&&A.session.phase?.name!=="live"){let x=A.session.phase?.name;b({status:x==="queued"||x==="waiting_for_capacity"?x:"pending",reason:`the dial's session is ${x??"not yet admitted"} \u2014 the connection waits for admission`})}let y=Ve(f)?.app.startsWith(Mt)??!1;return await _(E,A,S(A,k,h,y))},openTurnsOn:async function*(f,h){if(h?.aborted)throw mn(h);let w=await g(f);yield*Eo(w.session,h)},openVideoOn:async f=>{let h=m(f);if(h)return ns(h.entry.session);let{entry:w}=await t.sessionForHandle(f),b=u.get(w);return b||(b=Xn(w.session),u.set(w,b)),b},openVideo:async f=>{let{entry:h}=await t.sessionFor(f),w=u.get(h);return w||(w=Xn(h.session),u.set(h,w)),w},openVideoOut:async f=>{let{entry:h}=await t.sessionFor(f),w=a.get(h);return w||(w=So(h.session),a.set(h,w)),w},sessionHandle:async f=>{if(s){let h=await t.resolveTargetFor(f);if(h.sharedApp){let w=await s.sessionFor(f,h),b=c(w.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Ct(p,b)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:w,entry:b}=await t.dedicatedSessionFor(f);return Ct(w,us(b))},releaseSessionHandle:f=>{let h=Ve(f);if(!h)return;if(h.app.startsWith(Mt)){(async()=>{let b=null;try{b=(await t.sessionForHandle(f)).entry}catch{return}await os(b.session).catch(()=>{}),await t.evict(h.app,b)})();return}if(!s||h.app!==p)return;let w=s.entryFor(h.key);w&&s.release(w)},endDedicatedSession:async f=>{let h=Ve(f);if(!h||!h.app.startsWith(Mt))return;let w=null;try{w=(await t.sessionForHandle(f)).entry}catch{return}if(typeof w.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let b=await w.session.end();return await t.evict(h.app,w),b},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:h,entry:w}=await t.sessionForHandle(f);await t.evict(h,w)},createResponseOn:async(f,h,w)=>{let b=await g(f);await gn(b.session);let R=w!==void 0&&m(f)?new kt({...b.session,consumerId:w},{sessionTag:w}):b.responses;return gr(await R.responses.create(h),b.gone)},onSessionEnd:async(f,h)=>{let w=m(f);if(w)return w.entry.gone.onGone(A=>h({timeLeftMs:null,reason:A.message}));let{entry:b}=await t.sessionForHandle(f),R=b.session;if(typeof R.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return R.onPhase(A=>{if(E||!Du.has(A.name))return;E=!0;let y=R.endsAt??null;h({timeLeftMs:y?Math.max(0,y.getTime()-Date.now()):null,reason:A.reason??`session ${A.name}`})})}}}var ba=require("http");var Os=require("crypto"),Ps=require("ws");var fs="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",qu=1007,ms=1008,Pe=1011,_n=1008,I=class extends Error{constructor(n,r=qu){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,hn=["setup","clientContent","realtimeInput","toolResponse"];function gs(t){let e;try{e=JSON.parse(t)}catch{throw new I("client message is not valid JSON")}let n=re(e);if(!n)throw new I("client message must be a JSON object");let r=hn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!hn.includes(u));if(o.length>0)throw new I(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${hn.join(", ")}`);if(r.length!==1)throw new I(`client message must contain exactly one of ${hn.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new I(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function hs(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new I(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=re(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new I(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new I(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new I(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
9
9
|
`)}var ju={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},We="urun.videoOut";function ys(t){return{framing:bo,codec:t}}function ws(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[We]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Hu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Gu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",We],ps=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Vu(t){let e=re(t);if(!e)throw new I("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new I(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=re(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new I("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new I(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new I("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!ps.includes(e.activityHandling))throw new I(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ps.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Ju=["temperature","maxOutputTokens","responseModalities"];function _s(t){for(let[c,p]of Object.entries(Hu))if(t[c]!==void 0)throw new I(p);for(let c of Object.keys(t))if(!Gu.includes(c))throw new I(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new I('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=re(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new I("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Ju.includes(c))throw new I(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new I("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new I("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new I(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:hs(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new I("setup.tools must be an array");u=[];for(let c of t.tools){let p=re(c);if(!p)throw new I("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new I(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new I("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=re(m);if(!g||typeof g.name!="string")throw new I("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=re(t.sessionResumption);if(!c)throw new I("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new I(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new I("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?ju:Vu(t.realtimeInputConfig),d=!1;if(t[We]!==void 0){if(!re(t[We]))throw new I(`setup["${We}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function vs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function bs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ss(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new I(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new I("clientContent.turns must be an array");let n=[];for(let r of e){let o=re(r);if(!o)throw new I("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new I(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:hs(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var yn=16e3,ks=24e3,Wu=`audio/pcm;rate=${ks}`,xs=Buffer.alloc(960).toString("base64");function Ku(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function zu(t){let e=re(t);if(!e)throw new I("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new I("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Yu(t){let e=re(t);if(!e)throw new I("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==yn)throw new I(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${yn} Hz (audio/pcm;rate=${yn})`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new I(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Ku(o,yn,ks);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Rs(t){if(t.mediaChunks!==void 0)throw new I('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new I("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=re(t[o]);if(!s||Object.keys(s).length!==0)throw new I(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new I(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new I(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Yu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:zu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new I("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new I("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Es(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new I(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new I("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=re(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new I("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function As(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Is(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Wu,data:t}}]}}}}function Ts(t){let e=re(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=re(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=re(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=re(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new I(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Pe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new I(`upstream function_call arguments are not valid JSON: ${c}`,Pe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=re(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var Xu=256,_r=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Xu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Qu="local",Lt=t=>t.slice(0,120),vr=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),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 J){this.ws.close(ms,Lt(e.message));return}if(e instanceof W){this.ws.close(_n,Lt(e.message));return}if(e instanceof I){this.ws.close(e.closeCode,Lt(e.message));return}this.ws.close(Pe,Lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=gs(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new I(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Ss(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Rs(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:xs);return}this.transcript.push(...Es(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new I("setup may only be sent once, as the first client message");let n=_s(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new I("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",_n);if(s.model!==n.model)throw new I(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new I("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(n.model),this.proxyHandle!==s.proxyHandle)throw new I(`sessionResumption.handle named pooled session "${s.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`,_n);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),u=i.onOutputFrame(l=>this.send(ws(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[We]=ys(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new I("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new I("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Pe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Is(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new I("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new I("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Pe);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new I(`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 I("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new I("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(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Os.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(vs(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(bs(e.timeLeftMs)),this.ws.close(Pe,Lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;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}),o,s=!1;for await(let a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new I(`upstream error: ${JSON.stringify(l)}`,Pe);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=As(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new I("upstream produced no response.completed event",Pe);let{messages:i,assistantItems:u}=Ts(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ke=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Zu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Ke(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(n&&i!==void 0&&i!=="")throw new Ke(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 u;for(let a of r)u=a;if(u===void 0&&n)throw new Ke(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function Cs(t,e){let n=e.authenticate!==void 0;if(n&&(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(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Ps.WebSocketServer({noServer:!0}),o=new _r;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===fs&&(u.on("error",()=>{}),(async()=>{let d=Zu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ke(401,"invalid local proxy api key");c={clients:e.clients,scope:Qu}}r.handleUpgrade(i,u,a,p=>{new vr(p,c,o)})})().catch(d=>{let c=502;(d instanceof Ke||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",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
|
|
10
10
|
Connection: close\r
|
|
@@ -17,7 +17,7 @@ Connection: close\r
|
|
|
17
17
|
Content-Type: text/plain; charset=utf-8\r
|
|
18
18
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
19
19
|
\r
|
|
20
|
-
${o}`)}function Vs(t,e){let n=new Be.WebSocketServer({noServer:!0,maxPayload:fl}),r=new ze,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{vn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==pl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){vn(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(k){let S=e.statusOf?.(k)??null;vn(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new Rr(k,v,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&vn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Er();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Be.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var jr=require("@urun-sh/core");var Js=require("@urun-sh/core"),_l={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},vl={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Bt(t,e){let n=vl[t.code];return e?`${n} (${e})`:n}function bn(t){if(t==null)return null;let e=_l[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Sn(t){if(t.kind==="create-failed")return bn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Js.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return bn(e?"cold_start_exceeded":"queue_timeout")}var Ks=ot(require("os"),1),zs=ot(require("path"),1),Ys=require("url"),Xs=require("util");var Ws="0.6.
|
|
20
|
+
${o}`)}function Vs(t,e){let n=new Be.WebSocketServer({noServer:!0,maxPayload:fl}),r=new ze,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{vn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==pl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){vn(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(k){let S=e.statusOf?.(k)??null;vn(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new Rr(k,v,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&vn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Er();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Be.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var jr=require("@urun-sh/core");var Js=require("@urun-sh/core"),_l={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},vl={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Bt(t,e){let n=vl[t.code];return e?`${n} (${e})`:n}function bn(t){if(t==null)return null;let e=_l[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Sn(t){if(t.kind==="create-failed")return bn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Js.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return bn(e?"cold_start_exceeded":"queue_timeout")}var Ks=ot(require("os"),1),zs=ot(require("path"),1),Ys=require("url"),Xs=require("util");var Ws="0.6.49";var Qs=4141,Sl=Ws,xn={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 Tr(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function Zs(t,e,n){let r={...t,...Tr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ei(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function ti(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ni(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ri(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=(0,Ys.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function oi(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function si(t){if(t[0]!=="--port")return null;let e=oi(t[1]);return t.splice(0,2),e}function Or(t){let e=t.indexOf("--port");if(e===-1)return Qs;let n=oi(t[e+1]);return t.splice(e,2),n}function ii(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function Ar(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function mt(t){let e=kl(Ar(t,"URUN_BASE_URL")),n=Ar(t,"URUN_ORG_ID"),r=Ar(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?kn(s,"URUN_API_URL"):Ko,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?kn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function kl(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function kn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function Pr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Sl}}function xl(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var Rl=250;async function Cr(t,e=Rl){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var ai=2e3;async function El(t,e=ai){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ui(t,e,n=Qs,r=ai){if(t!=null)return{mode:"spawn",port:t};let o=await Cr(n);if(o!==null&&xl(o,e)){let s=await El(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 Mr(t,e=Ks.default.homedir()){return zs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Ir=["log","info","warn","error","debug","trace"];function li(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Ir.map(u=>[u,n[u]]));for(let u of Ir)n[u]=(...a)=>{t.write(`${(0,Xs.format)(...a)}
|
|
21
21
|
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Ir)n[u]=i[u]}}var Al=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function di(t){let e=t?.code;return typeof e=="string"&&Al.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(di(n))return!1;throw n}}function ci(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{di(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
22
22
|
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function pi(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
23
23
|
`)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
|
package/dist/proxy/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-
|
|
2
|
+
import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-NZ5EWOMJ.js";import"../chunk-CAR4AEQJ.js";import{F as K}from"../chunk-X23WP5HQ.js";import"../chunk-X5BLQXHK.js";import{g as R}from"../chunk-64VO62LW.js";import"../chunk-XGAF2NDT.js";import{d as v,e as $,f as C,g as U,h as I,i as L,j as N,k as O,l as x,m as _,n as g,p as G,q as P,r as D,s as M,t as A,u as W,v as b,w as B,x as j,y as F}from"../chunk-3JZAWWVV.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
|
|
3
3
|
`),null):{catalogUrl:l,anonKey:s}}function me(e){let i={baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:fe(n.env,l=>n.stderr.write(l)),decisionPool:J(n.env,n.env.HOSTNAME)??void 0},t=H(i);return{router:t,decision:i.decisionPool?Y(i,t):null}}async function Q(e,i,t){let l=ee(e,i,{stdio:"inherit",env:t});return new Promise(s=>{l.once("exit",r=>s(r??1)),l.once("error",r=>{n.stderr.write(`failed to launch ${e}: ${String(r)}
|
|
4
4
|
`),s(127)})})}function X(){return N(n.env,import.meta.url,pe)}function te(e){for(let[i,t]of Object.entries($(e)))n.stdout.write(`export ${i}=${t}
|
|
5
5
|
`)}async function Z(e,i){let t=g(n.env),l=i?P(t):void 0,{router:s,decision:r}=me(t);r&&(r.boot().then(()=>r.reap()).catch(u=>n.stderr.write(`[decision-pool] boot FAILED: ${String(u instanceof Error?u.message:u)}
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-
|
|
1
|
+
import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-X23WP5HQ.js";import{a as o,h as t}from"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-3JZAWWVV.js";import{i as r,j as i}from"../chunk-C452ZIU5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.49",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.6.
|
|
73
|
+
"@urun-sh/core": "^0.6.49"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"@prometheus-io/client": "^0.16.1",
|