@urun-sh/openai 0.6.53 → 0.6.54
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-CHD2URWY.js +2 -0
- package/dist/{chunk-7IT4XK2K.js → chunk-J6IDVNKN.js} +2 -2
- package/dist/{chunk-XGAF2NDT.js → chunk-KNWFUWXY.js} +1 -1
- package/dist/{chunk-C452ZIU5.js → chunk-N3Y2GDQK.js} +5 -5
- package/dist/{chunk-5PA6542H.js → chunk-RHIN2745.js} +7 -7
- package/dist/{chunk-ZWDQPTSH.js → chunk-S32BCZSV.js} +1 -1
- package/dist/{chunk-K5TQMHAY.js → chunk-YMMANYDG.js} +2 -2
- package/dist/{composite-4ppY0Kv6.d.cts → composite-C1oeSkNz.d.cts} +19 -0
- package/dist/{composite-BKEde6hP.d.ts → composite-CmDZAzTq.d.ts} +6 -0
- package/dist/hosted/bin.cjs +5 -5
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +5 -5
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/index.cjs +5 -5
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +22 -22
- package/dist/pooler/bin.cjs +12 -12
- package/dist/pooler/bin.js +8 -8
- package/dist/proxy/cli.cjs +4 -4
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +1 -1
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-D7PBMXB6.js +0 -2
package/dist/hosted/bin.cjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
`),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
|
|
4
4
|
`),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function $o(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||Ue(`${r.model_id}-${r.variant}`)===e.appSlug||Ue(r.model_id)===e.appSlug)),n?ic(n.engine_args?.pool):null}function To(t,e,n,r,o){if(!o)throw new he(`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 he(`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 he(`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 Mi(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 he(`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 Ui="shared:",Vt="speech:",yt="realtime:";function gt(t){return t.sharedApp?Ui+t.appSlug:t.appSlug}function En(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 Co(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ue(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ac(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function lc(t){let e=t.map(ac),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var uc={stt:"stt",tts:"tts"};function ht(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:uc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Di(t,e){let n=Co(t,e);return n.length>0?n:Io(t,e)}function Rn(t,e){return Di(t.appSlug,e)}function dc(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 he(`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 sr=6e4,ir=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??sr):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??sr):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??sr):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??sr;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 Be)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
|
`),Sn}let r=_i(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
|
-
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(xo(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(Ui)||o.startsWith(Vt)||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 ie(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=ko(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,a=Ue(s),l=n.endpoints.filter(c=>Ue(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:ko(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=Ue(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(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new ie(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new ie(`model "${n}" maps to app "${u.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 a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===Ue(l.model_id)||o===Ue(`${l.model_id}-${l.variant}`));if(a)throw new ie(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=En(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return $o(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return gt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,gt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return En(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Vt+gt(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,yt+(0,$i.randomUUID)())}async evictHandle(e){let n=Et(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:En(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:xn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:xn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Et(e);if(!n)throw new te(`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(a=>a,()=>null):null;if(i===null)throw new te(`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 te(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Sn;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)
|
|
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(xo(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(Ui)||o.startsWith(Vt)||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 ie(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=ko(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,a=Ue(s),l=n.endpoints.filter(c=>Ue(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:ko(n,d,i)}async resolveTarget(e){let n=await this.dialTargetFor(e);return this.opts.callerOrgId&&(n.callerOrgId=this.opts.callerOrgId),n}async dialTargetFor(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=Ue(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(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new ie(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new ie(`model "${n}" maps to app "${u.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 a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===Ue(l.model_id)||o===Ue(`${l.model_id}-${l.variant}`));if(a)throw new ie(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=En(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return $o(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return gt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,gt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return En(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Vt+gt(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,yt+(0,$i.randomUUID)())}async evictHandle(e){let n=Et(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:En(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:xn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:xn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Et(e);if(!n)throw new te(`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(a=>a,()=>null):null;if(i===null)throw new te(`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 te(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Sn;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
7
|
`);let l=(n?Gt(n):[]).map(u=>{let d=s.filter(x=>x.model_id===u.model_id&&x.variant===u.variant),c=rr(d),f=Wt(d),h=Ao(d),m=bn(u.model_id,u.variant,i),w=Oo(d);return kt({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},...w.published.length>0?{voices:[...w.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>or(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ii(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=To(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Mi(`${r.modelId}:${r.variant}`,s).includes(n)}return Li(Co(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ht(Rn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ht(Rn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ht(Rn(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):Rn(n,r);return dc(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):Rn(n,r);return Oo(o)}async imageModelList(){let e=await this.catalogRows(),n=Sn,r=[];for(let s of await this.availableIds()){let i=Li(Co(s,e));i.length!==0&&r.push(kt({...or(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Gt(o)){let i=To(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Mi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Wt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Sn,r=[];for(let s of await this.availableIds())ht(Di(s,e))==="stt"&&r.push(or(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Gt(o)){let i=To(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ht(i)!=="stt")continue;let a=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Wt(i),owned_by:"urun"});r.push(a)}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("; ")}`)}};function Fi(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 ar(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}var hc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bi(t){let e=t?.code;return typeof e=="string"&&hc.has(e)}function tt(t,e){try{return t.write(e),!0}catch(n){if(Bi(n))return!1;throw n}}function Hi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Bi(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
8
8
|
`)}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)}}}O();var _e=require("@prometheus-io/client"),da=require("http");O();var gc={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function yc(t){return gc[t]??null}var Gi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function wc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function _c(t){return t==="surface"}function vc(t){let e=t?.ledgerFailureReason;return Gi.includes(e)?e:"unknown"}var bc=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ji=["priced","unpriced"],Sc={written:ji,already_written:ji,skipped:bc,failed:Gi},Wi=Object.entries(Sc).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function kc(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Rc(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Ec=256,qi=4096,An=12e4,xc=250,Ac=8e3,lt=[],No=new Set,In=0,Kt=!1;function Ji(){return lt.length}function Vi(t=Date.now()){let e=lt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var lr=new Set;function Ki(){return In===0&<.length===0}function zi(){if(Ki()){Kt=!1;for(let t of[...lr])t()}}async function Yi(t=Qi){return Ki()?!0:await new Promise(e=>{let n,r=()=>{lr.delete(r),clearTimeout(n),e(!0)};lr.add(r),n=setTimeout(()=>{lr.delete(r),e(!1)},t),n.unref?.()})}function Xi(){Kt=!0;let t=[...lt.splice(0,lt.length),...No];for(let e of t)e.settled||At(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Qi}ms drain \u2014 the request was served and answered, and its billing row was never written`});return zi(),t.length}var Qi=5e3;function Zi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
9
9
|
`}function Ic(t){tt(process.stdout,t)}function ea(t,e){try{t(e)}catch{}}function ur(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Ic,o=yc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ea(r,Zi("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let l;if(a.kind==="catalog")l={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Rc(e),completed_at:e.ts,billable_outcome:kc(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(lt.length>=qi){i("queue_full",`${lt.length} ledger writes are already waiting (capacity ${qi}, ${In} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}lt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),In<Ec&&(In+=1,Oc())}async function Oc(){try{for(;;){let t=Tc();if(t===void 0)return;No.add(t);try{await Pc(t)}finally{No.delete(t)}}}finally{In-=1,zi()}}function Tc(){let t=Date.now();for(;;){let e=lt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<An)return e;At(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${An}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Pc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);At(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=wc(o);if(s!==null){At(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=vc(o),a=Date.now()-t.queuedAt;if(Kt){At(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(_c(i)&&a<An){if(await Lc(Cc(t.attempts)),Kt||Date.now()-t.queuedAt>=An){let l=Date.now()-t.queuedAt;At(t,{outcome:"failed",reason:Kt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Kt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${An}ms dwell bound (waited ${l}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}At(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Cc(t){return Math.min(Ac,xc*2**Math.max(0,t-1))}function Lc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function At(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ea(t.report,Zi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}O();O();var cr="/v1/usage/requests",ta=1e4,Mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,wt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},we=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dr=class extends we{constructor(e){super(e),this.name="UsageWithholdingError"}},sa=1024*1024;function Fo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new wt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new wt(`"${e}" must be an array of uuid strings`);if(n.length>ta)throw new wt(`"${e}" carries ${n.length} ids; at most ${ta} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Mc.test(s))throw new wt(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ia(t){return Fo(t,"inference_ids")}var $c=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function zt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is not a non-empty string (got ${Xt(r)})`);return r}function Uo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is neither null nor a non-empty string (got ${Xt(r)})`);return r}function Yt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new we(`${n}: ${e} is not a number (got ${Xt(o)})`);if(r&&!Number.isSafeInteger(s))throw new we(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new we(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Nc=40,na=64,ra=600;function aa(t){let e=Object.keys(t).sort(),r=e.slice(0,Nc).map(o=>o.length>na?`${o.slice(0,na)}\u2026`:o).join(", ");return r.length>ra&&(r=`${r.slice(0,ra)}\u2026`),`${e.length} keys present: [${r}]`}function Xt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Do(t){tt(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
|
|
@@ -22,7 +22,7 @@ Content-Type: text/plain; charset=utf-8\r
|
|
|
22
22
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
23
23
|
\r
|
|
24
24
|
${o}`)}function as(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Hp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{xr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==ss){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){xr(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;xr(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new os(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&xr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=is();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}O();O();var ws=require("@urun-sh/core");O();var tl=require("@urun-sh/core"),Vp={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},Kp={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 Un(t,e){let n=Kp[t.code];return e?`${n} (${e})`:n}function Ar(t){if(t==null)return null;let e=Vp[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 Ir(t){if(t.kind==="create-failed")return Ar(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=tl.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Ar(e?"cold_start_exceeded":"queue_timeout")}var Bn=require("ws");O();var sl=require("@urun-sh/core");O();var rl=require("crypto");function j(t){return`${t}_${(0,rl.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Or=4*1024*1024,ls=8*1024*1024,us=512,sn=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ds(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},zp={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Yp={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Xp={format:!0,voice:!0,speed:!0};function Qp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function on(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function nl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Zp=10;function cs(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Zp})}function Dn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in zp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=on(o.modalities,"modalities"),l=on(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(l==="transcription"&&!n.turns)throw new z('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=on(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Qp(l))throw new z(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=cs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Yp))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&nl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Dn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Dn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Xp))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&nl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Tr(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function ps(t,e){let n=t;if(!n||typeof n!="object")throw new z("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:j("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new z("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new z(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new z("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Pr(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var ef=1001,tf=1011,nf=6e4,rf=3e5,fs=3;var Cr=class extends Error{},Lr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},ms=t=>t.slice(0,120),of=/^[A-Za-z0-9+/=]*$/,sf=2,af=600;function hs(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>sf)return!1;return!0}var Fn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ds();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??nf,this.responseDeadlineMs=e.responseDeadlineMs??rf,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===Lo&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Tr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(ot("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:j("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=j("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Or){this.fail(fe("frame_too_large",`frame exceeds the ${Or}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Cr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
25
|
-
${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Dn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:j("event"),session:Tr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ps(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:j("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:j("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!of.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>sn&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${sn}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${sn} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>sn&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=j("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(le(fe("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,ms("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Cr("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(le({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new Lr),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?on(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?on(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Pr(this.items),x=cs(typeof r.instructions=="string"?r.instructions:this.config.instructions),b=typeof r.temperature=="number"?r.temperature:this.config.temperature,v=r.max_output_tokens??this.config.maxOutputTokens,p=v==="inf"||v===void 0?void 0:v,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...b!==void 0?{temperature:b}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},T={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},_=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Pr(this.items)}let{input:$,sawAudioOnlyItem:N}=E??{input:[],sawAudioOnlyItem:!1},D={...S,input:$,...m?this.compositeTurnAsk(r):{}};N&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(D,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);T.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),T.contentFlowed=!0,T.messageOpen||(this.beginMessageItem(h,T.nextOutputIndex++),T.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(T.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),T.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),T.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${T.nextOutputIndex}`,M=T.tools.get(K);if(!M){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;M={outputIndex:T.nextOutputIndex++,name:ee,args:""},T.tools.set(K,M);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:M.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(M.name=G.name),M.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:M.outputIndex,call_id:K,name:M.name??"",delta:re});continue}if(G.type==="response.completed"){_=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof Lr)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,_)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(T.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=fs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${fs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${fs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(hs(n))return;this.openDuplexResponse()}else if(hs(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=af){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(hs(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:j("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=rt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(Mo,"the organization is out of credits \u2014 top up to continue"),Mo))}failSessionGone(e){if(e instanceof te&&e.reason===Lo){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof sl.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>us&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Pn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Pn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>ls){this.ws.close(ef,ms("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(tf,ms(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ol(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ol(this.id,e)}},gs=[];function ol(t,e){gs.push({id:t,reason:e}),gs.length>256&&gs.shift()}var Hn="/v1/realtime",il="urun.admission",al=t=>t.slice(0,120);function lf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
25
|
+
${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Dn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:j("event"),session:Tr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ps(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:j("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:j("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!of.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>sn&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${sn}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${sn} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>sn&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=j("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(le(fe("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,ms("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Cr("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(le({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new Lr),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?on(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?on(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Pr(this.items),x=cs(typeof r.instructions=="string"?r.instructions:this.config.instructions),b=typeof r.temperature=="number"?r.temperature:this.config.temperature,v=r.max_output_tokens??this.config.maxOutputTokens,p=v==="inf"||v===void 0?void 0:v,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...b!==void 0?{temperature:b}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},T={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},_=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Pr(this.items)}let{input:$,sawAudioOnlyItem:N}=E??{input:[],sawAudioOnlyItem:!1},D={...S,input:$,...m?this.compositeTurnAsk(r):{}};N&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(D,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);T.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),T.contentFlowed=!0,T.messageOpen||(this.beginMessageItem(h,T.nextOutputIndex++),T.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(T.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),T.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),T.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${T.nextOutputIndex}`,M=T.tools.get(K);if(!M){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;M={outputIndex:T.nextOutputIndex++,name:ee,args:""},T.tools.set(K,M);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:M.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(M.name=G.name),M.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:M.outputIndex,call_id:K,name:M.name??"",delta:re});continue}if(G.type==="response.completed"){_=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof Lr)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,_)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(T.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=fs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${fs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${fs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(hs(n))return;this.openDuplexResponse()}else if(hs(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=af){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(hs(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:j("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=rt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(Mo,"the organization is out of credits \u2014 top up to continue"),Mo))}failSessionGone(e){if(e instanceof te&&e.reason===Lo){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof sl.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>us&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Pn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Pn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>ls){this.ws.close(ef,ms("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(tf,ms(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ol(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ol(this.id,e)}},gs=[];function ol(t,e){gs.push({id:t,reason:e}),gs.length>256&&gs.shift()}var Hn="/v1/realtime",il="urun.admission",al=t=>t.slice(0,120);function lf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
26
26
|
Connection: close\r
|
|
27
27
|
Content-Type: text/plain\r
|
|
28
28
|
\r
|
|
@@ -75,20 +75,20 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:y.message}}
|
|
|
75
75
|
|
|
76
76
|
`)),c.end()})}}O();var ct=(t,e)=>Object.assign(new Error(e),{status:t}),Sm='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ts=(t,e,n)=>new te(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Os=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ie?ct(404,n.message):n}};async function ou(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ct(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Sm}`);if(o==="transcription")throw ct(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw ct(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw ct(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(!f)throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(f!=="stt")throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Os(t,n.stt),i=await Os(t,e),a=await Os(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,km({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof te?Ts("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Ps(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Kn=class extends Error{};async function*km(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,w=null,E=[],x=null,b=new Promise((T,_)=>{n&&n.addEventListener("abort",()=>_(new Kn),{once:!0})}),v=()=>h||n?.aborted===!0,p=async T=>{if(v())return;let _;try{_=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:T}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof te?Ts("tts",l.tts,$):$}let C=_[Symbol.asyncIterator]();w=C;try{for(;;){let $=C.next(),N;try{N=await Promise.race([$,b])}catch(q){if($.catch(()=>{}),q instanceof Kn)return;throw q}if(N.done)return;let D=N.value;if(D.type==="error"){let q=D.error&&typeof D.error.message=="string"?D.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${q}`)}if(D.type==="response.completed")return}}finally{w===C&&(w=null)}},g=async()=>{for(;E.length>0&&!v();){let T=E.shift();await p(T)}},y=T=>{if(T===""||v()||(E.push(T),x!==null))return;let _=g();x=_,_.then(()=>{x===_&&(x=null)},C=>{x===_&&(x=null),m??=C})},S=()=>{h=!0,E.length=0;let T=w;if(w=null,T){let _=T.return?.();_&&_.catch(()=>{})}},A=async()=>{for(;E.length>0||x!==null;){let T=x;if(T===null){await p(E.shift());continue}await T}},P=f?new dn({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},T=>y(T)):null,R=null;try{let T;try{T=await o.createResponseOn(s,d)}catch(C){throw C instanceof te?Ts("chat",a,C):C}let _=T[Symbol.asyncIterator]();try{for(;;){let C=_.next(),$;try{$=await Promise.race([C,b])}catch(q){if(C.catch(()=>{}),q instanceof Kn)break;throw q}if($.done)break;let N=$.value;if(v())return;let D=N;if(D.type==="error"){yield N;return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){yield N,P?.push(D.delta);continue}if(D.type==="response.function_call_arguments.delta"){P?.flush(),yield N;continue}if(D.type==="response.completed"){R=N.response;continue}}}finally{Promise.resolve(_.return?.()).catch(()=>{})}P?.flush(),P?.dispose(),f&&await A(),R!==null&&(yield{type:"response.completed",response:R})}finally{P?.dispose(),S();try{if(m instanceof te)throw m}finally{r?.()}}}var We=(t,e)=>Object.assign(new Error(e),{status:t});function iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function lu(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Rm='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function uu(t,e,n,r,o){if(!t.supportsAudio)throw We(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!==null)return await ou(t,e,h,n,r);throw We(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw We(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(i&&!t.openTurnsOn)throw We(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!=="stt")throw We(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw We(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Rm}`);if(r==="transcription"&&!i)throw We(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof Ae?We(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,su.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(f.presence={touch:h=>t.touchSessionPresence?.(a,h),detach:h=>t.detachSessionPresence?.(a,h)}),t.endDedicatedSession&&(f.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(f.onSessionEnd=h=>t.onSessionEnd(a,h)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}O();var Mu=require("@urun-sh/core"),$u=require("@urun-sh/core/internal"),Nu=Ee(require("ws"),1);O();var vu=require("http");O();var mu=require("http");O();function du(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),typeof o.model=="string"&&o.model&&(s.model=o.model),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function zr(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}O();O();function cu(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var pu=require("@urun-sh/core/internal");O();var Em="llm-resp";async function*Yr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield cu(s);return}}}async function*Cs(t,e){let n=`${Em}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Yr(e,t.stream(n).messages())}finally{try{(0,pu.gcRequest)(t.doc("llm"),e)}catch{}}}var xm="/pooler/v1/inference",Ze=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},Am=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Im=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},hu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Om=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await hu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Ze(t.status,e,n,t.retryAfterSeconds)};async function Tm(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${xm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Am(e),firstMessage:Im(e)}});return new Promise((a,l)=>{let u=(0,mu.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var fu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Pm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
77
77
|
|
|
78
|
-
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=fu(s);i!==null&&(yield i)}let n=fu(e);n!==null&&(yield n)}async function gu(t,e,n,r){let o=zr(e,n,r),s=o.model??"";if(s==="")throw new Ze(400,"missing_model","the pooler submit requires a model");let i=await Tm(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Om(i);let a=e.stream===!0?Yr(n,Pm(i)):await Cm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Cm(t,e){let n=await hu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Ze(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Yr(e,(async function*(){yield o})())}O();var Lm=require("@urun-sh/core"),Mm=require("bullmq"),$m=require("crypto");var yu=12e4;var Nm="/pooler/v1/lanes/pick",Um="/pooler/v1/lanes/status",Dm=1e4,Yn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function wu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,vu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Yn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function _u(t,e,n,r){if(t===400&&Fm(e)?.code==="lane_target")return new Nt(n,r);if(t===503)return new Ae(n);let o=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${o}`)}function Fm(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function bu(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),yu),l=await wu(t,"POST",Nm,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Dm);if(l.status!==200)throw _u(l.status,l.json,e,s);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await wu(t,"GET",Um,void 0,5e3);if(e.status!==200)throw _u(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}O();O();O();async function Su(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var ku=require("@urun-sh/core/internal");var Xr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=zr(e,n,this.consumerId);return this.write(r),Cs(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=du(e,n,r,this.consumerId);return this.write(o),Cs(this.session,r)})}cancelTurn(e){try{(0,ku.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await Su(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Ru=0;function Hm(){return Ru+=1,`req_${Date.now().toString(36)}_${Ru.toString(36)}`}var Ht=class{transport;constructor(e,n){this.transport=new Xr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Hm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};O();var pn=Ee(require("yjs"),1),Eu=require("@urun-sh/core/internal"),jm=3e4;function qm(t){return(e,n,r)=>{let o=t(e);pn.applyUpdate(n,pn.encodeStateAsUpdate(o));let s=a=>pn.applyUpdate(o,a),i=a=>pn.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ls(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?qm(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new Eu.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??jm;await new Promise((h,m)=>{let w=setTimeout(()=>{E(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),E=c.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",x),h()}),x=()=>{clearTimeout(w),E(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",x,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}O();var jt=Ee(require("ws"),1),qt=require("@urun-sh/core"),xu="/stream/";function Au(t){if(!t.startsWith(xu))return null;let e=t.slice(xu.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function eo(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Qr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>qt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Zr=class{reassembler=new qt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===qt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},$s=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>Iu&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Iu} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Iu=8*1024*1024,st=new $s;function Ou(t,e){let n=new Zr,r={send(o){st.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Qr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),st.detach(t,e,r)}};return st.attach(t,e,r),r}function Gm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function Tu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new jt.default(r,eo(e)),s=new Zr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Qr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Qr(i),o.readyState!==jt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Ms(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
78
|
+
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=fu(s);i!==null&&(yield i)}let n=fu(e);n!==null&&(yield n)}async function gu(t,e,n,r){let o=zr(e,n,r),s=o.model??"";if(s==="")throw new Ze(400,"missing_model","the pooler submit requires a model");let i=await Tm(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Om(i);let a=e.stream===!0?Yr(n,Pm(i)):await Cm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Cm(t,e){let n=await hu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Ze(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Yr(e,(async function*(){yield o})())}O();var Lm=require("@urun-sh/core"),Mm=require("bullmq"),$m=require("crypto");var yu=12e4;var Nm="/pooler/v1/lanes/pick",Um="/pooler/v1/lanes/status",Dm=1e4,Yn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function wu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,vu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Yn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function _u(t,e,n,r){if(t===400&&Fm(e)?.code==="lane_target")return new Nt(n,r);if(t===503)return new Ae(n);let o=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${o}`)}function Fm(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function bu(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,requestorOrgId:s,model:i,holdMs:a=0}){let l=Math.min(Math.max(Math.trunc(a),0),yu),u=await wu(t,"POST",Nm,{pool:e,app:n,fn:r,model:i,hold_ms:l,...o?{shared_app:!0}:{},...s?{requestor_org_id:s}:{}},l+Dm);if(u.status!==200)throw _u(u.status,u.json,e,i);return(u.json?.lanes??[]).filter(c=>typeof c.lane_id=="string"&&c.lane_id!==""&&typeof c.host=="string"&&c.host!=="").map(c=>({laneId:c.lane_id,host:c.host}))},async status(){let e=await wu(t,"GET",Um,void 0,5e3);if(e.status!==200)throw _u(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}O();O();O();async function Su(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var ku=require("@urun-sh/core/internal");var Xr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=zr(e,n,this.consumerId);return this.write(r),Cs(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=du(e,n,r,this.consumerId);return this.write(o),Cs(this.session,r)})}cancelTurn(e){try{(0,ku.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await Su(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Ru=0;function Hm(){return Ru+=1,`req_${Date.now().toString(36)}_${Ru.toString(36)}`}var Ht=class{transport;constructor(e,n){this.transport=new Xr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Hm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};O();var pn=Ee(require("yjs"),1),Eu=require("@urun-sh/core/internal"),jm=3e4;function qm(t){return(e,n,r)=>{let o=t(e);pn.applyUpdate(n,pn.encodeStateAsUpdate(o));let s=a=>pn.applyUpdate(o,a),i=a=>pn.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ls(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?qm(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new Eu.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??jm;await new Promise((h,m)=>{let w=setTimeout(()=>{E(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),E=c.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",x),h()}),x=()=>{clearTimeout(w),E(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",x,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}O();var jt=Ee(require("ws"),1),qt=require("@urun-sh/core"),xu="/stream/";function Au(t){if(!t.startsWith(xu))return null;let e=t.slice(xu.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function eo(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Qr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>qt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Zr=class{reassembler=new qt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===qt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},$s=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>Iu&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Iu} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Iu=8*1024*1024,st=new $s;function Ou(t,e){let n=new Zr,r={send(o){st.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Qr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),st.detach(t,e,r)}};return st.attach(t,e,r),r}function Gm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function Tu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new jt.default(r,eo(e)),s=new Zr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Qr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Qr(i),o.readyState!==jt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Ms(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
79
79
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
80
80
|
Connection: close\r
|
|
81
81
|
Content-Type: text/plain; charset=utf-8\r
|
|
82
82
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
83
83
|
\r
|
|
84
|
-
${o}`)}function Pu(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new jt.WebSocketServer({noServer:!0,handleProtocols:(m,w)=>{let E=Au(new URL(w.url??"/","http://localhost").pathname);if(!E)return!1;let x=eo(E.name);return m.has(x)?x:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,w,E)=>{r>0&&l.set(m,{at:Date.now(),label:w,reap:E})},d=m=>{let w=l.get(m);w&&(w.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[w,E]of l)m-E.at<r||(l.delete(w),console.warn(`[lane-stream] ${E.label}: lease expired (no data for ${r} ms) \u2014 terminating`),E.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,w,E,x)=>{let b={client:E,upstream:x,laneId:m,name:w};i.add(b);let v=p=>{if(i.delete(b)){l.delete(E),console.warn(`[lane-stream] ${m}/${w}: host-affinity pump torn down (${p})`);for(let g of[E,x])try{(g.readyState===jt.default.OPEN||g.readyState===jt.default.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(u(E,`${m}/${w} pump`,()=>{for(let p of[E,x])try{p.terminate()}catch{}v("lease expired")}),n>0){let p=(g,y)=>{let S=!0,A=()=>{S=!0};g.on("pong",A),g.on("message",A);let P=setInterval(()=>{if(!S){console.warn(`[lane-stream] ${m}/${w}: pong timeout on ${y} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${y} dial never sends a close)`),clearInterval(P);try{g.terminate()}catch{}v(`${y} pong timeout`);return}S=!1;try{g.ping()}catch{}},n);P.unref?.();let R=()=>clearInterval(P);g.once("close",R),g.once("error",R)};p(E,"client"),p(x,"host")}E.on("message",p=>{d(E);try{x.send(p,{binary:!0})}catch(g){v(`upstream send failed: ${String(g)}`)}}),x.on("message",p=>{d(E);try{E.send(p,{binary:!0})}catch(g){v(`client send failed: ${String(g)}`)}}),E.on("close",()=>v("client socket closed")),E.on("error",()=>v("client socket error")),x.on("close",()=>v("host socket closed")),x.on("error",()=>v("host socket error"))},h=(m,w,E)=>{let x;try{x=new URL(m.url??"/","http://localhost")}catch{Ms(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let b=Au(x.pathname);b&&(a||w.destroyed||(async()=>{let v=x.searchParams.get("token")??"",p=null;try{p=v===""?null:await e.verifyToken(v,b.laneId,b.name)}catch{p=null}if(p===null){Ms(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(b.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let y=await e.podToPodDial(b.laneId,b.name,g);o.handleUpgrade(m,w,E,S=>{f(b.laneId,b.name,S,y)});return}catch(y){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${g} failed (${String(y)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,w,E,g=>{let y=Gm(g,()=>d(g));if(s.set(g,y),st.attach(b.laneId,b.name,y),u(g,`${b.laneId}/${b.name}`,()=>g.terminate()),n>0){let A=!0,P=()=>{A=!0};g.on("pong",P),g.on("message",P);let R=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(R),g.terminate();return}A=!1;try{g.ping()}catch{}},n);R.unref?.();let T=()=>clearInterval(R);g.once("close",T),g.once("error",T)}g.on("message",A=>{d(g);let P=new Uint8Array(A);try{Qr(P)}catch(R){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(R)}`);return}st.deliver(b.laneId,b.name,y,P),P[1]===qt.ENVELOPE_KIND.END&&st.detach(b.laneId,b.name,y)});let S=()=>{s.delete(g),l.delete(g),st.detach(b.laneId,b.name,y)};g.on("close",S),g.on("error",S)})})().catch(()=>{w.destroyed||Ms(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),st.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let w of[m.client,m.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}O();var St=require("crypto"),Wm=["sfu","urun-doc"],Lu="runtime:lease",Jm="lane:join",Vm="urun-runtime-key-v1";function Ns(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,St.createHmac)("sha256",t).update(`${Vm}|${e}`).digest("base64url")}var Km=120;function Cu(t){return Buffer.from(t).toString("base64url")}function zm(t,e,n){let r=Cu(JSON.stringify(t)),o=Cu(JSON.stringify(e)),s=(0,St.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Xn(t,e,n=Km,r=Jm,o){let s=o?Ns(e,o):e;return Ym(t,s,n,r,o)}function Ym(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return zm({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,St.randomUUID)()},e)}function Us(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(Ns(n,f)),o&&h.push(Ns(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let v=(0,St.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===v.length&&(0,St.timingSafeEqual)(c,v)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let w=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(w!==void 0&&Wm.some(b=>b===w||Array.isArray(w)&&w.includes(b))))return null;let x=d.session_id??d.sub;return typeof x!="string"||x!==e?null:{sessionId:x,aud:w,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}O();var Xm=3,Qm="llm",Zm=new Set(["paused","error"]);function to(t,e,n){let r=t.doc(Qm),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,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Xm||d(new te(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Zm.has(c.name)&&d(new te(`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),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Ds(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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)}}function eh(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new qe(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var th={"prod-usw2":["us-west1"]};function Uu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,w,E,x,b,v)=>{let p=E?A=>Ou(m,A):A=>Tu(m,A,{hostUrl:`ws://${x}/stream/${m}`,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v)}),g=E?Ls({laneId:m,roomDoc:A=>t.roomDoc(m,A),streamEndpoint:p}):Ls({laneId:m,streamEndpoint:p,connector:(0,$u.createWebsocketDocConnector)({serverUrl:`ws://${x}/doc`,sessionId:m,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v),WebSocketPolyfill:Nu.default})}),y=E?l(m):to(g,`lane:${m}`,{armOnFirstSync:!0}),S={session:g,responses:new Ht(g,{sessionTag:null}),gone:y,goneWatch:y,laneId:m,pool:w,inFlight:0,laneSession:g,self:E,host:x??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,S),y.onGone(()=>u(S)),S},l=m=>{let w=null,E=!1,x=new Set,b=p=>{if(!w){w=p;for(let g of[...x])g(p);x.clear()}},v=t.hostedSignal?.(m,p=>{if(p){E=!0;return}E&&b(new te(`the lane ${m} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>w,onGone(p){return w?(p(w),()=>{}):(x.add(p),()=>x.delete(p))},dispose(){v?.(),x.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),st.forgetLane(m.laneId))},d=m=>{let w=m.laneId;return typeof w=="string"&&n.get(w)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,w)=>{throw t.metrics?.observeLane503Fast(w??""),s.set(m,e()),new Ae(m)},h=async(m,w)=>{let E=eh(w);o.add(E);let x=e();try{let b=await t.laneWarmWaitMsFor?.(m,w)??t.laneColdWakeDefaultMs??0,v;try{v=await t.plane.pick({pool:E,app:w.appSlug,fn:w.fnName??"",model:m,holdMs:b,...w.sharedApp?{sharedApp:!0}:{}})}catch(P){throw P instanceof Yn?new Mu.SessionAllocationError(`lane pick hold expired for ${E}: ${P.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):P}t.metrics?.observeLaneReady(m??"",v.length);let p=await t.currentReleaseOf?.(w)??null,g=new Set(v.map(P=>P.laneId));for(let P of i)g.has(P)||i.delete(P);let S=v.filter(P=>{let R=n.get(P.laneId);return R!==void 0&&p!==null&&R.mintedRelease!==""&&R.mintedRelease!==p&&(R.retireWhenIdle=!0,R.inFlight===0)?(c(R),!1):!i.has(P.laneId)}).map(P=>({laneId:P.laneId,self:P.host===t.selfAddress,host:P.host,region:P.region})).sort((P,R)=>{let T=th[t.seatRegion??""]??[],_=new Map(T.map((N,D)=>[N,D])),C=T.length===0?0:(P.region!==void 0?_.get(P.region):void 0)??T.length,$=T.length===0?0:(R.region!==void 0?_.get(R.region):void 0)??T.length;return C!==$?C-$:P.self!==R.self?P.self?-1:1:(r.get(P.laneId)??0)-(r.get(R.laneId)??0)})[0];S||f(E,m);let A=n.get(S.laneId);return A?.goneWatch?.gone()&&(u(A),A=void 0),A&&(A.pool!==E||A.self!==S.self||A.host!==S.host)&&(u(A),A=void 0),A||(A=a(S.laneId,E,S.self,S.host,p,w.sharedOrgId??void 0)),A.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:A,identity:{kind:"catalog",model_id:w.modelId??m??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-x)}};return{sessionFor(m,w){return h(m,w)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(x=>x.pool)])].sort(),w=await t.plane.status().catch(()=>[]),E=new Map(nh(w));return Promise.all(m.map(async x=>{let b=E.get(x)??{pool:x,lanes:[],lastDemandAt:null};return{pool:x,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(v=>v.pool===x).map(v=>({laneId:v.laneId,inFlight:v.inFlight,self:v.self,host:v.host})),lastRefusalAt:s.get(x)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function nh(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}O();var rh="urun:node-scheduler:apps:v1";function oh(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Du(t){return async e=>{let n=oh(e);if(n===null)return null;try{let r=await t.hget(rh,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}O();var Wu=require("ws");O();var Bu=Ee(require("yjs"),1),hn=Ee(require("y-protocols/sync"),1),pt=Ee(require("y-protocols/awareness"),1),ye=Ee(require("lib0/encoding"),1),gn=Ee(require("lib0/decoding"),1),Hu=Ee(require("lib0/map"),1),ju=Ee(require("lodash.debounce"),1);O();var Fu=()=>{};var ih=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,ah=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,lh=0,uh=1;var dh=process.env.GC!=="false"&&process.env.GC!=="0",ch=process.env.YPERSISTENCE,no=null;if(typeof ch=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var mn=new Map,ro=0,Bs=1,ph=(t,e,n)=>{let r=ye.createEncoder();ye.writeVarUint(r,ro),hn.writeUpdate(r,t);let o=ye.toUint8Array(r);n.conns.forEach((s,i)=>Qn(n,i,o))},Fs=class extends Bu.Doc{constructor(e){super({gc:dh}),this.name=e,this.conns=new Map,this.awareness=new pt.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=ye.createEncoder();ye.writeVarUint(l,Bs),ye.writeVarUint8Array(l,pt.encodeAwarenessUpdate(this.awareness,a));let u=ye.toUint8Array(l);this.conns.forEach((d,c)=>{Qn(this,c,u)})};this.awareness.on("update",n),this.on("update",ph),!1}},Hs=(t,e=!0)=>Hu.setIfUndefined(mn,t,()=>{let n=new Fs(t);return n.gc=e,no!==null&&no.bindState(t,n),mn.set(t,n),n}),fh=(t,e,n)=>{try{let r=ye.createEncoder(),o=gn.createDecoder(n);switch(gn.readVarUint(o)){case ro:ye.writeVarUint(r,ro),hn.readSyncMessage(o,r,e,t),ye.length(r)>1&&Qn(e,t,ye.toUint8Array(r));break;case Bs:{pt.applyAwarenessUpdate(e.awareness,gn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},fn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),pt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&no!==null&&(no.writeState(t.name,t).then(()=>{t.destroy()}),mn.delete(t.name))}e.close()},Qn=(t,e,n)=>{e.readyState!==lh&&e.readyState!==uh&&fn(t,e);try{e.send(n,r=>{r!=null&&fn(t,e)})}catch{fn(t,e)}},mh=3e4,qu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Hs(n,r);o.conns.set(t,new Set),t.on("message",a=>fh(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&fn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{fn(o,t),clearInterval(i)}}},mh);t.on("close",()=>{fn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ye.createEncoder();ye.writeVarUint(a,ro),hn.writeSyncStep1(a,o),Qn(o,t,ye.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ye.createEncoder();ye.writeVarUint(u,Bs),ye.writeVarUint8Array(u,pt.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Qn(o,t,ye.toUint8Array(u))}}};var js="/doc/",Ju=30,hh=1e4,Gu="llm";function gh(t){if(!t.startsWith(js))return null;let e=t.slice(js.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function yn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
84
|
+
${o}`)}function Pu(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new jt.WebSocketServer({noServer:!0,handleProtocols:(m,w)=>{let E=Au(new URL(w.url??"/","http://localhost").pathname);if(!E)return!1;let x=eo(E.name);return m.has(x)?x:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,w,E)=>{r>0&&l.set(m,{at:Date.now(),label:w,reap:E})},d=m=>{let w=l.get(m);w&&(w.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[w,E]of l)m-E.at<r||(l.delete(w),console.warn(`[lane-stream] ${E.label}: lease expired (no data for ${r} ms) \u2014 terminating`),E.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,w,E,x)=>{let b={client:E,upstream:x,laneId:m,name:w};i.add(b);let v=p=>{if(i.delete(b)){l.delete(E),console.warn(`[lane-stream] ${m}/${w}: host-affinity pump torn down (${p})`);for(let g of[E,x])try{(g.readyState===jt.default.OPEN||g.readyState===jt.default.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(u(E,`${m}/${w} pump`,()=>{for(let p of[E,x])try{p.terminate()}catch{}v("lease expired")}),n>0){let p=(g,y)=>{let S=!0,A=()=>{S=!0};g.on("pong",A),g.on("message",A);let P=setInterval(()=>{if(!S){console.warn(`[lane-stream] ${m}/${w}: pong timeout on ${y} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${y} dial never sends a close)`),clearInterval(P);try{g.terminate()}catch{}v(`${y} pong timeout`);return}S=!1;try{g.ping()}catch{}},n);P.unref?.();let R=()=>clearInterval(P);g.once("close",R),g.once("error",R)};p(E,"client"),p(x,"host")}E.on("message",p=>{d(E);try{x.send(p,{binary:!0})}catch(g){v(`upstream send failed: ${String(g)}`)}}),x.on("message",p=>{d(E);try{E.send(p,{binary:!0})}catch(g){v(`client send failed: ${String(g)}`)}}),E.on("close",()=>v("client socket closed")),E.on("error",()=>v("client socket error")),x.on("close",()=>v("host socket closed")),x.on("error",()=>v("host socket error"))},h=(m,w,E)=>{let x;try{x=new URL(m.url??"/","http://localhost")}catch{Ms(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let b=Au(x.pathname);b&&(a||w.destroyed||(async()=>{let v=x.searchParams.get("token")??"",p=null;try{p=v===""?null:await e.verifyToken(v,b.laneId,b.name)}catch{p=null}if(p===null){Ms(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(b.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let y=await e.podToPodDial(b.laneId,b.name,g);o.handleUpgrade(m,w,E,S=>{f(b.laneId,b.name,S,y)});return}catch(y){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${g} failed (${String(y)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,w,E,g=>{let y=Gm(g,()=>d(g));if(s.set(g,y),st.attach(b.laneId,b.name,y),u(g,`${b.laneId}/${b.name}`,()=>g.terminate()),n>0){let A=!0,P=()=>{A=!0};g.on("pong",P),g.on("message",P);let R=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(R),g.terminate();return}A=!1;try{g.ping()}catch{}},n);R.unref?.();let T=()=>clearInterval(R);g.once("close",T),g.once("error",T)}g.on("message",A=>{d(g);let P=new Uint8Array(A);try{Qr(P)}catch(R){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(R)}`);return}st.deliver(b.laneId,b.name,y,P),P[1]===qt.ENVELOPE_KIND.END&&st.detach(b.laneId,b.name,y)});let S=()=>{s.delete(g),l.delete(g),st.detach(b.laneId,b.name,y)};g.on("close",S),g.on("error",S)})})().catch(()=>{w.destroyed||Ms(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),st.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let w of[m.client,m.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}O();var St=require("crypto"),Wm=["sfu","urun-doc"],Lu="runtime:lease",Jm="lane:join",Vm="urun-runtime-key-v1";function Ns(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,St.createHmac)("sha256",t).update(`${Vm}|${e}`).digest("base64url")}var Km=120;function Cu(t){return Buffer.from(t).toString("base64url")}function zm(t,e,n){let r=Cu(JSON.stringify(t)),o=Cu(JSON.stringify(e)),s=(0,St.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Xn(t,e,n=Km,r=Jm,o){let s=o?Ns(e,o):e;return Ym(t,s,n,r,o)}function Ym(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return zm({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,St.randomUUID)()},e)}function Us(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(Ns(n,f)),o&&h.push(Ns(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let v=(0,St.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===v.length&&(0,St.timingSafeEqual)(c,v)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let w=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(w!==void 0&&Wm.some(b=>b===w||Array.isArray(w)&&w.includes(b))))return null;let x=d.session_id??d.sub;return typeof x!="string"||x!==e?null:{sessionId:x,aud:w,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}O();var Xm=3,Qm="llm",Zm=new Set(["paused","error"]);function to(t,e,n){let r=t.doc(Qm),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,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Xm||d(new te(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Zm.has(c.name)&&d(new te(`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),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Ds(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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)}}function eh(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new qe(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var th={"prod-usw2":["us-west1"]};function Uu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,w,E,x,b,v)=>{let p=E?A=>Ou(m,A):A=>Tu(m,A,{hostUrl:`ws://${x}/stream/${m}`,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v)}),g=E?Ls({laneId:m,roomDoc:A=>t.roomDoc(m,A),streamEndpoint:p}):Ls({laneId:m,streamEndpoint:p,connector:(0,$u.createWebsocketDocConnector)({serverUrl:`ws://${x}/doc`,sessionId:m,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v),WebSocketPolyfill:Nu.default})}),y=E?l(m):to(g,`lane:${m}`,{armOnFirstSync:!0}),S={session:g,responses:new Ht(g,{sessionTag:null}),gone:y,goneWatch:y,laneId:m,pool:w,inFlight:0,laneSession:g,self:E,host:x??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,S),y.onGone(()=>u(S)),S},l=m=>{let w=null,E=!1,x=new Set,b=p=>{if(!w){w=p;for(let g of[...x])g(p);x.clear()}},v=t.hostedSignal?.(m,p=>{if(p){E=!0;return}E&&b(new te(`the lane ${m} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>w,onGone(p){return w?(p(w),()=>{}):(x.add(p),()=>x.delete(p))},dispose(){v?.(),x.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),st.forgetLane(m.laneId))},d=m=>{let w=m.laneId;return typeof w=="string"&&n.get(w)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,w)=>{throw t.metrics?.observeLane503Fast(w??""),s.set(m,e()),new Ae(m)},h=async(m,w)=>{let E=eh(w);o.add(E);let x=e();try{let b=await t.laneWarmWaitMsFor?.(m,w)??t.laneColdWakeDefaultMs??0,v;try{v=await t.plane.pick({pool:E,app:w.appSlug,fn:w.fnName??"",model:m,holdMs:b,...w.sharedApp?{sharedApp:!0}:{},...w.sharedApp&&w.callerOrgId?{requestorOrgId:w.callerOrgId}:{}})}catch(P){throw P instanceof Yn?new Mu.SessionAllocationError(`lane pick hold expired for ${E}: ${P.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):P}t.metrics?.observeLaneReady(m??"",v.length);let p=await t.currentReleaseOf?.(w)??null,g=new Set(v.map(P=>P.laneId));for(let P of i)g.has(P)||i.delete(P);let S=v.filter(P=>{let R=n.get(P.laneId);return R!==void 0&&p!==null&&R.mintedRelease!==""&&R.mintedRelease!==p&&(R.retireWhenIdle=!0,R.inFlight===0)?(c(R),!1):!i.has(P.laneId)}).map(P=>({laneId:P.laneId,self:P.host===t.selfAddress,host:P.host,region:P.region})).sort((P,R)=>{let T=th[t.seatRegion??""]??[],_=new Map(T.map((N,D)=>[N,D])),C=T.length===0?0:(P.region!==void 0?_.get(P.region):void 0)??T.length,$=T.length===0?0:(R.region!==void 0?_.get(R.region):void 0)??T.length;return C!==$?C-$:P.self!==R.self?P.self?-1:1:(r.get(P.laneId)??0)-(r.get(R.laneId)??0)})[0];S||f(E,m);let A=n.get(S.laneId);return A?.goneWatch?.gone()&&(u(A),A=void 0),A&&(A.pool!==E||A.self!==S.self||A.host!==S.host)&&(u(A),A=void 0),A||(A=a(S.laneId,E,S.self,S.host,p,w.sharedOrgId??void 0)),A.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:A,identity:{kind:"catalog",model_id:w.modelId??m??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-x)}};return{sessionFor(m,w){return h(m,w)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(x=>x.pool)])].sort(),w=await t.plane.status().catch(()=>[]),E=new Map(nh(w));return Promise.all(m.map(async x=>{let b=E.get(x)??{pool:x,lanes:[],lastDemandAt:null};return{pool:x,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(v=>v.pool===x).map(v=>({laneId:v.laneId,inFlight:v.inFlight,self:v.self,host:v.host})),lastRefusalAt:s.get(x)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function nh(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}O();var rh="urun:node-scheduler:apps:v1";function oh(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Du(t){return async e=>{let n=oh(e);if(n===null)return null;try{let r=await t.hget(rh,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}O();var Wu=require("ws");O();var Bu=Ee(require("yjs"),1),hn=Ee(require("y-protocols/sync"),1),pt=Ee(require("y-protocols/awareness"),1),ye=Ee(require("lib0/encoding"),1),gn=Ee(require("lib0/decoding"),1),Hu=Ee(require("lib0/map"),1),ju=Ee(require("lodash.debounce"),1);O();var Fu=()=>{};var ih=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,ah=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,lh=0,uh=1;var dh=process.env.GC!=="false"&&process.env.GC!=="0",ch=process.env.YPERSISTENCE,no=null;if(typeof ch=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var mn=new Map,ro=0,Bs=1,ph=(t,e,n)=>{let r=ye.createEncoder();ye.writeVarUint(r,ro),hn.writeUpdate(r,t);let o=ye.toUint8Array(r);n.conns.forEach((s,i)=>Qn(n,i,o))},Fs=class extends Bu.Doc{constructor(e){super({gc:dh}),this.name=e,this.conns=new Map,this.awareness=new pt.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=ye.createEncoder();ye.writeVarUint(l,Bs),ye.writeVarUint8Array(l,pt.encodeAwarenessUpdate(this.awareness,a));let u=ye.toUint8Array(l);this.conns.forEach((d,c)=>{Qn(this,c,u)})};this.awareness.on("update",n),this.on("update",ph),!1}},Hs=(t,e=!0)=>Hu.setIfUndefined(mn,t,()=>{let n=new Fs(t);return n.gc=e,no!==null&&no.bindState(t,n),mn.set(t,n),n}),fh=(t,e,n)=>{try{let r=ye.createEncoder(),o=gn.createDecoder(n);switch(gn.readVarUint(o)){case ro:ye.writeVarUint(r,ro),hn.readSyncMessage(o,r,e,t),ye.length(r)>1&&Qn(e,t,ye.toUint8Array(r));break;case Bs:{pt.applyAwarenessUpdate(e.awareness,gn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},fn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),pt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&no!==null&&(no.writeState(t.name,t).then(()=>{t.destroy()}),mn.delete(t.name))}e.close()},Qn=(t,e,n)=>{e.readyState!==lh&&e.readyState!==uh&&fn(t,e);try{e.send(n,r=>{r!=null&&fn(t,e)})}catch{fn(t,e)}},mh=3e4,qu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Hs(n,r);o.conns.set(t,new Set),t.on("message",a=>fh(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&fn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{fn(o,t),clearInterval(i)}}},mh);t.on("close",()=>{fn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ye.createEncoder();ye.writeVarUint(a,ro),hn.writeSyncStep1(a,o),Qn(o,t,ye.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ye.createEncoder();ye.writeVarUint(u,Bs),ye.writeVarUint8Array(u,pt.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Qn(o,t,ye.toUint8Array(u))}}};var js="/doc/",Ju=30,hh=1e4,Gu="llm";function gh(t){if(!t.startsWith(js))return null;let e=t.slice(js.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function yn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
85
85
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
86
86
|
Connection: close\r
|
|
87
87
|
Content-Type: text/plain; charset=utf-8\r
|
|
88
88
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
89
89
|
\r
|
|
90
90
|
${o}`)}function Vu(t,e){let n=new Wu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=p=>o.get(`${p}/${Gu}`)??0,a=p=>s.get(p)??0,l=new Map,u=new Map,d=new Set,c=new Set,f=new Map,h=new Map,m=4096,w=!1,E=(p,g,y)=>{let S=i(p)>0,A=a(p),P=A>0,R=`${p}/${g}`,T=o.get(R)??0;y>0?o.set(R,y):o.delete(R);let _=A+y-T;_>0?s.set(p,_):s.delete(p);let C=i(p)>0,$=_>0;if(S!==C){C?x(p):b(p);for(let N of l.get(p)??[])N(C)}P&&!$&&queueMicrotask(()=>{let N=`${p}/`;for(let[D,q]of[...mn.entries()])!D.startsWith(N)||q.conns.size>0||(mn.delete(D),q.destroy())})},x=p=>{if(!e.hostRegistry||u.has(p))return;let g=()=>{e.hostRegistry?.setHost(p,e.selfAddress).catch(()=>{})};g();let y=setInterval(g,hh);y.unref?.(),u.set(p,y)},b=p=>{let g=u.get(p);g&&(clearInterval(g),u.delete(p)),e.hostRegistry&&e.hostRegistry.delHost(p,e.selfAddress).catch(()=>{})},v=(p,g,y)=>{let S;try{S=new URL(p.url??"/","http://localhost")}catch{yn(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>c.delete(g));let A=gh(S.pathname);if(!A){if(S.pathname.startsWith(js)){yn(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(g);return}d.add(g);let P=!1;(async()=>{if(h.has(A.laneId)){yn(g,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let R=S.searchParams.get("token")??"",T=null;try{T=R===""?null:await e.verifyToken(R,A.laneId,A.docName)}catch{T=null}if(T===null){yn(g,401,"invalid or missing lane doc token");return}let _=T;if(_.tenant!==void 0&&e.laneTenantOf){let C=null;try{C=await e.laneTenantOf(A.laneId)}catch{C=null}if(C==null||C==="")e.onLaneTenantMissing?.();else if(_.tenant!==C){yn(g,403,"lane doc token org does not match the lane record");return}}w||g.destroyed||(P=!0,n.handleUpgrade(p,g,y,C=>{d.delete(g),r.add(C),C.on("close",()=>r.delete(C));let $=f.get(A.laneId);$||($=new Set,f.set(A.laneId,$)),$.add(C),C.on("close",()=>{$.delete(C),$.size===0&&f.delete(A.laneId)});let N=_.scope===Lu||_.scope===void 0&&typeof _.app=="string"&&typeof _.fn=="string"&&_.aud==="sfu";if(N){let q=`${A.laneId}/${A.docName}`,X=(o.get(q)??0)+1;E(A.laneId,A.docName,X),X>1&&A.docName===Gu&&e.hostRegistry?.setHost(A.laneId,e.selfAddress).catch(()=>{})}C.on("close",()=>{if(!N)return;let q=`${A.laneId}/${A.docName}`;E(A.laneId,A.docName,Math.max(0,(o.get(q)??1)-1))}),qu(C,p,{docName:`${A.laneId}/${A.docName}`,gc:!0})}))})().catch(()=>{!P&&!g.destroyed&&yn(g,500,"lane doc upgrade failed")}).finally(()=>d.delete(g))};return t.on("upgrade",v),{async close(){w=!0,t.off("upgrade",v);for(let g of[...u.keys()])b(g);await new Promise(g=>{if(r.size===0&&d.size===0){g();return}let y=r.size+d.size,S=()=>{y-=1,y<=0&&g()};for(let A of r)A.once("close",S);for(let A of d)A.once("close",S);for(let A of r)A.close(1001,"lane doc host shutting down");for(let A of d)A.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(p,g){return Hs(`${p}/${g}`,!0)},isHosted(p){return i(p)>0},onHostedChange(p,g){let y=l.get(p);return y||(y=new Set,l.set(p,y)),y.add(g),g(i(p)>0),()=>{y.delete(g)}},closeLane(p){if(h.set(p,!0),h.size>m){let g=h.keys().next().value;g!==void 0&&h.delete(g)}b(p);for(let g of f.get(p)??[])g.close(1001,`lane ${p} retired \u2014 the app's release moved`)}}}var gd=Ee(require("ws"),1);O();var yh="urun:catalog:v1";function Ku(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(yh),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
91
|
-
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var yd=Ee(require("ioredis"),1);O();var er=require("@urun-sh/core"),ao=require("crypto"),zu="urun-session-gateway",wh="machine",_h=3e5;function Xu(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},wn=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},ft=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function lo(t){let e=(t??"").trim();if(e==="")throw new ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var vh=60,bh=6e4,Sh=4096;function kh(t){return t===401||t===403}var tr=class{constructor(e){this.opts=e;this.mint=e.mint??er.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ae("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<bh)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:vh});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof er.ClientTokenError&&i.status===402?(this.cache.delete(e),new wn(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof er.ClientTokenError&&kh(i.status)?(this.cache.delete(e),new ae(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ft(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new ft(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=Sh){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function Zn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Yu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var oo=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof ft?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<_h)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s))),o}};function Qu(t,e,n){try{let r=(0,ao.createPublicKey)({key:n,format:"jwk"});return(0,ao.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var so=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,e.now??Date.now,n=>new ft("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed machine token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed machine token")}if(s.alg!=="RS256")throw new ae(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==zu)throw new ae(`machine token audience must be ${zu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==wh)throw new ae(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new ae(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},Rh="https://api.workos.com/sso/jwks/";function Eh(t){return`${Rh}${t.slice(t.lastIndexOf("/")+1)}`}var qs=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,this.now,n=>new ft("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Xu(e))return!1;try{let n=Zn(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed user token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed user token")}if(s.alg!=="RS256")throw new ae(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(Eh(l),a);if(c===void 0)throw new ae(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},io=class{verifier;bindings;constructor(e){this.verifier=new qs({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new tr({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new ae("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Gs(t,e,n,r){if(Xu(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}O();var nr=require("crypto");O();var xe=require("@urun-sh/core");O();async function Zu(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}O();var ed=require("@urun-sh/core"),Ws=2;function xh(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ah(t){let e=t?.type;return e==="response.completed"||e==="error"}function td(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Ws;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(Ah(h)&&(d=!0),xh(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof ed.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Ws&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Ws&&!c){await t.evict(a,l);continue}return}})()}}var Ks=require("crypto");O();var Js=require("@urun-sh/core"),Ih="audio";function nd(t){let e=t.streamEndpoint(Ih);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,Js.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,Js.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}O();var rd=require("@urun-sh/core"),Oh="rt-video-in";function od(t){let e=t.streamEndpoint(Oh);return{sendInputFrame:async n=>{e.send((0,rd.encodeStreamEnvelope)(n))}}}var Ph=0,Ch=4,Lh=4;function id(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Ph;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,Ch));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Lh),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Vs(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 ad(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u={...e.sharedApp?{sharedApp:!0}:{},...l,...r,presenceIdleMs:3e4},d=w=>({session:w,responses:new Ht(w),gone:to(w,n)});if(i.lane==="jwt"){let w=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Vs(w,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let w=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:E}=i,x=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),b=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(w,{baseUrl:E,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:x,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),m=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(m,e.appSlug,a,u))}function ld(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 zs(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 Mh=new Set(["error","paused"]);function Ys(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=ad(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new ir({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"?()=>Ni({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Zu(n):null),listPrices:n?()=>vi(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return mi(i)}:e.lane==="api-key"?()=>hi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:ld});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},gt({appSlug:t.defaultApp}))),s}function ud(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,a=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
91
|
+
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var yd=Ee(require("ioredis"),1);O();var er=require("@urun-sh/core"),ao=require("crypto"),zu="urun-session-gateway",wh="machine",_h=3e5;function Xu(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},wn=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},ft=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function lo(t){let e=(t??"").trim();if(e==="")throw new ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var vh=60,bh=6e4,Sh=4096;function kh(t){return t===401||t===403}var tr=class{constructor(e){this.opts=e;this.mint=e.mint??er.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ae("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<bh)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:vh});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof er.ClientTokenError&&i.status===402?(this.cache.delete(e),new wn(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof er.ClientTokenError&&kh(i.status)?(this.cache.delete(e),new ae(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ft(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new ft(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=Sh){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function Zn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Yu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var oo=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof ft?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<_h)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s))),o}};function Qu(t,e,n){try{let r=(0,ao.createPublicKey)({key:n,format:"jwk"});return(0,ao.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var so=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,e.now??Date.now,n=>new ft("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed machine token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed machine token")}if(s.alg!=="RS256")throw new ae(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==zu)throw new ae(`machine token audience must be ${zu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==wh)throw new ae(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new ae(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},Rh="https://api.workos.com/sso/jwks/";function Eh(t){return`${Rh}${t.slice(t.lastIndexOf("/")+1)}`}var qs=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,this.now,n=>new ft("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Xu(e))return!1;try{let n=Zn(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed user token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed user token")}if(s.alg!=="RS256")throw new ae(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(Eh(l),a);if(c===void 0)throw new ae(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},io=class{verifier;bindings;constructor(e){this.verifier=new qs({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new tr({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new ae("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Gs(t,e,n,r){if(Xu(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}O();var nr=require("crypto");O();var xe=require("@urun-sh/core");O();async function Zu(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}O();var ed=require("@urun-sh/core"),Ws=2;function xh(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ah(t){let e=t?.type;return e==="response.completed"||e==="error"}function td(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Ws;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(Ah(h)&&(d=!0),xh(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof ed.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Ws&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Ws&&!c){await t.evict(a,l);continue}return}})()}}var Ks=require("crypto");O();var Js=require("@urun-sh/core"),Ih="audio";function nd(t){let e=t.streamEndpoint(Ih);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,Js.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,Js.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}O();var rd=require("@urun-sh/core"),Oh="rt-video-in";function od(t){let e=t.streamEndpoint(Oh);return{sendInputFrame:async n=>{e.send((0,rd.encodeStreamEnvelope)(n))}}}var Ph=0,Ch=4,Lh=4;function id(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Ph;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,Ch));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Lh),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Vs(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 ad(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u={...e.sharedApp?{sharedApp:!0}:{},...l,...r,presenceIdleMs:3e4},d=w=>({session:w,responses:new Ht(w),gone:to(w,n)});if(i.lane==="jwt"){let w=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Vs(w,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let w=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:E}=i,x=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),b=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(w,{baseUrl:E,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:x,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),m=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(m,e.appSlug,a,u))}function ld(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 zs(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 Mh=new Set(["error","paused"]);function Ys(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=ad(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new ir({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,callerOrgId:t.orgId,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"?()=>Ni({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Zu(n):null),listPrices:n?()=>vi(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return mi(i)}:e.lane==="api-key"?()=>hi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:ld});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},gt({appSlug:t.defaultApp}))),s}function ud(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,a=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
92
92
|
`)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new Rr({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:m=>m.session.activity?.(),openSlot:async m=>{let w=ad(t,d,c,{concurrencyKey:m.concurrencyKey});return w.gone.onGone(E=>E.bindingLost?h.evict(w):h.markSessionDead(w)),await co(w.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,w)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${w}`),terminalOpenFailure:m=>m instanceof xe.SessionFailedError&&zs(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,gt(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=gt(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),w=i.get(m.entry)??[];return w.push(m),i.set(m.entry,w),{app:f,entry:m.entry,identity:En(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,gt(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 $h(t){return(0,xe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:xe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function co(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:$h(t.phase),signal:e})}async function Nh(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 sd(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 uo(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Xs(t,e=_a,n,r,o=ns,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new Map,c=new WeakMap,f=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},h="lane",m=p=>{let g=Et(p);if(!s||!g||g.app!==h)return null;let y=s.entryFor(g.key);if(!y)throw new te(`the lane behind this handle (${g.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:g.key,entry:y}},w=async p=>m(p)?.entry??(await t.sessionForHandle(p)).entry,E=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};c.set(p,y),g=(async()=>{if(await co(p.session,y.gone.signal),y.gone.signal.aborted)throw uo(y.gone.signal);c.get(p)===y&&c.delete(p);let S=await wa(p.session,await e());return Object.assign(S,{sessionId:p.session.id})})(),i.set(p,g),g.then(S=>{i.get(p)===g&&(p.audioDispose=()=>S.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{c.get(p)===y&&c.delete(p)},()=>{c.get(p)===y&&c.delete(p)})}return g},x=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await E(p);return{appendInputAudio:(S,A)=>y.appendInputAudio(S,A),onOutputAudio:S=>y.onOutputAudio(S),sessionId:f(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},b=async(p,g,y,S=!1)=>{let A=()=>S?sd(p.session):Nh(p.session);if(y?.aborted){let T=c.get(p);throw(i.get(p)===void 0||T!==void 0&&T.waiting===0)&&await A().catch(()=>{}),uo(y)}let P=g(p),R=c.get(p);return R!==void 0&&R.waiting++,y===void 0?P:new Promise((T,_)=>{let C=()=>{R!==void 0&&--R.waiting===0&&c.get(p)===R&&(R.gone.abort(),c.delete(p),i.delete(p),u.delete(p),A().catch(()=>{})),_(uo(y))};y.addEventListener("abort",C,{once:!0});let $=()=>y.removeEventListener("abort",C);P.then(N=>{$(),T(N)},N=>{$(),_(N)})})},v=async(p,g,y)=>{try{return await y}catch(S){throw(S instanceof te||S instanceof xe.SessionFailedError&&zs(S))&&(t.evict(p,g),S instanceof xe.SessionFailedError&&n?.(p,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:td({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp)try{let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Nt)return r?r.sessionFor(p):t.sessionFor(p);if(y instanceof Ze)return console.error(`[pooler-fallback] pooler channel failed for ${p} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(p):t.sessionFor(p);throw y}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>f(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{zs(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await co(p.session);let y=Ya(Ds(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let S=p;return(async function*(){try{yield*y}catch(P){throw Xa(P)&&(s&&s.owns(S)?s.evict(S):r&&(P instanceof te&&!P.bindingLost?r.markSessionDead(S):r.evict(S))),P}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,g)=>{let{app:y,entry:S}=await t.sessionFor(p);return await v(y,S,b(S,E,g))},openAudioOn:async(p,g,y,S)=>{let A=m(p);if(A){let _=A.entry.session;return nd(_)}let{app:P,entry:R}=await t.sessionForHandle(p);if(S&&R.session.phase?.name!=="live"){let _=R.session.phase?.name;S({status:_==="queued"||_==="waiting_for_capacity"?_:"pending",reason:`the dial's session is ${_??"not yet admitted"} \u2014 the connection waits for admission`})}let T=Et(p)?.app.startsWith(yt)??!1;return await v(P,R,b(R,x,g,T))},openTurnsOn:async function*(p,g){if(g?.aborted)throw uo(g);let y=await w(p);yield*Ci(y.session,g)},openVideoOn:async p=>{let g=m(p);if(g)return od(g.entry.session);let{entry:y}=await t.sessionForHandle(p),S=a.get(y);return S||(S=Jo(y.session),a.set(y,S)),S},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=Jo(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=ba(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),S=f(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return xn(h,S)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(p);return xn(y,ld(S))},touchSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);y||(y=new Map,d.set(p,y)),y.set(g,Date.now());let S=null;try{S=await w(p)}catch{return}S.session.activity?.()})()},detachSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);if(y?.delete(g),y&&y.size===0&&d.delete(p),y&&y.size>0)return;let S=null;try{S=await w(p)}catch{return}S.session.presenceDetach?.()})()},releaseSessionHandle:p=>{let g=Et(p);if(!g)return;if(g.app.startsWith(yt)){(async()=>{let S=null;try{S=(await t.sessionForHandle(p)).entry}catch{return}await sd(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==h)return;let y=s.entryFor(g.key);y&&s.release(y)},endDedicatedSession:async p=>{let g=Et(p);if(!g||!g.app.startsWith(yt))return;let y=null;try{y=(await t.sessionForHandle(p)).entry}catch{return}if(typeof y.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 S=await y.session.end();return await t.evict(g.app,y),S},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let S=await w(p);await co(S.session);let A=y!==void 0&&m(p)?new Ht({...S.session,consumerId:y},{sessionTag:y}):S.responses;return Ds(await A.responses.create(g),S.gone)},onSessionEnd:async(p,g)=>{let y=m(p);if(y)return y.entry.gone.onGone(R=>g({timeLeftMs:null,reason:R.message}));let{entry:S}=await t.sessionForHandle(p),A=S.session;if(typeof A.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let P=!1;return A.onPhase(R=>{if(P||!Mh.has(R.name))return;P=!0;let T=A.endsAt??null;g({timeLeftMs:T?Math.max(0,T.getTime()-Date.now()):null,reason:R.reason??`session ${R.name}`})})}}}var Uh=512;function po(t){return`urun-inference-proxy-${(0,nr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var fo=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,nr.randomUUID)()}`;return gu(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:qo,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:id(process.env,process.env.HOSTNAME)??void 0},r=Ys(n),o=n.decisionPool?ud(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Xs(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Uh;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},dd=512,Dh=1024,Qs=class extends Error{constructor(){super(`conversation capacity reached (${dd} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Fh(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Vt))return{concurrencyKey:e};if(n.startsWith(Vt)||n.startsWith(yt))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Vt)||n.startsWith(yt)||t.set(n,r)}}}function Bh(t,e,n,r,o){let s=Ys({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:qo,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Fh(r,o)});return{clients:Xs(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var mo=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${po(e.apiKey)}:live`:`${po(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Bh(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=dd;){let e=!1;for(let[n,r]of this.byCaller){for(let[o,s]of r)if(!(s.attachments>0)){r.delete(o),this.dropHandleIndexFor(n,o),s.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Qs}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,nr.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),endDedicatedSession:a=>s().backhaul.clients.endDedicatedSession?.(a),touchSessionPresence:(a,l)=>s().backhaul.clients.touchSessionPresence?.(a,l),detachSessionPresence:(a,l)=>s().backhaul.clients.detachSessionPresence?.(a,l),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Dh;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new te("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};O();var ho="/inference-usage",cd=25e3;var Hh=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function pd(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Hh.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var go=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ho}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(cd)})}catch(i){throw new we(`the uRun usage surface (POST ${ho}) could not be reached within ${cd}ms: ${pd(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new we(`the uRun usage surface (POST ${ho}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new we(`the uRun usage surface (POST ${ho}) answered HTTP ${o.status} with a body that is not JSON: ${pd(i)}`)}return la(s,this.opts.onRejectedRow)}};O();var jh="/inference-ledger",qh=1e4,yo=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},ti=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Te=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},ni=class extends ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ri=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Gh=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Zs],["output_minutes",Zs],["cost_nano_usd",Zs],["price_version",t=>t===null||typeof t=="string"]];function Wh(t){for(let[e,n]of Gh){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Jh(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Wh(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Zs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ei(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Vh(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function fd(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Kh(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&fd(t.started_at,n.started_at)&&fd(t.completed_at,n.completed_at)&&ei(t.prompt_tokens,n.prompt_tokens)&&ei(t.completion_tokens,n.completion_tokens)&&ei(t.output_units,n.output_units)&&Vh(t.output_minutes,n.output_minutes)}function zh(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
93
93
|
`)}async function Yh(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(zh(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Xh(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Te(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new Te(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Te(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new Te(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new Te(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new Te(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Te(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new Te(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!l&&(i!==null||a===null))throw new Te(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var wo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${jh}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Yh(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new Te(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(qh)})}catch(u){throw new Te(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Jh(u);throw d.status==="found"&&Kh(n,d.row)?new ti(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new yo(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new yo(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new ni("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new ri(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new Te(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new Te(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new Te(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Xh(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new Te(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Qh=5e3,Zh=1e3,eg=1500,tg=3e3,ng="/api/client-tokens";function _o(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function md(t,e,n,r){_o(t,e,{error:{message:n,type:r}})}async function rg(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ng}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(tg)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function wd(t){let e=t.resolver??new tr({gatewayUrl:t.baseUrl}),n=t.machine?new so({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new io({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new gr(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let _=new yd.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),C=Ku({redis:_});return{registry:Uu({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:bu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(N,D)=>s?.onHostedChange(N,D)??(()=>()=>{}),roomDoc:(N,D)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(N,D)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(N,D)=>C.rows().then(q=>{let X=$o(q,D);return X?.warm_wait_s!==void 0?X.warm_wait_s*1e3:void 0}),currentReleaseOf:Du(_),closeLane:N=>s?.closeLane(N)}),catalog:C,redis:_}})(),l=t.registry??new fo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>rg(t.baseUrl)),d=async()=>{let _=null;for(let N of l.decisionPools()){_=N;break}if(!_)return null;let C=_.stats();if(C.some(N=>N.draining))return{ok:!1,detail:"decision pool draining"};if(C.every(N=>N.attached===0&&N.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let $=await _.pingReady(eg);return{ok:$,detail:$?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new go({apiUrl:t.apiUrl}),f=t.ledgerClient??new wo({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(Kr)}catch(_){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(_ instanceof Error?_.message:_)}
|
|
94
94
|
`)}})();let w=async _=>Gs(lo(_.headers.authorization),e,n,r),E=async _=>{let C=await w(_);if(C.billingAudience==="platform"&&C.creditsAdmissionOk===!1){let $=C.creditsRefusalReason;throw new wn($==="spend_cap_reached"||$==="insufficient_credits"?$:void 0)}return C},x=_=>_ instanceof ae?{status:_.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:_ instanceof wn?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",..._.code!==void 0?{code:_.code}:{}}:_ instanceof ft?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:_.detail}:null,b={write:(_,C)=>f.write(lo(_.headers.authorization),C),observe:_=>o.observeLedger(_),...t.ledgerLog?{report:t.ledgerLog}:{}},v=ru({clients:async _=>l.clientsFor(await E(_)),usage:{authorize:_=>lo(_.headers.authorization),lookup:(_,C)=>c.lookup(_,C)},statusOf:x,...t.requestLog?{requestLog:t.requestLog}:{},observe:_=>o.observe(_),ledger:b}),p=fl({authorize:async _=>{await E(_)},...t.lane?{secret:t.lane.tokenSecret}:{}}),g=null,y=null,S=(0,hd.createServer)((_,C)=>{let $=new URL(_.url??"/","http://localhost");(async()=>{if(_.method==="GET"&&$.pathname==="/healthz"){_o(C,200,{ok:!0});return}if(_.method==="GET"&&$.pathname==="/readyz"){let q=Date.now();if((!g||q-g.at>=Qh)&&(g={at:q,...await u()}),!y||q-y.at>=Zh){let re=await d();y=re===null?{at:q,ok:!0,detail:null}:{at:q,ok:re.ok,detail:re.detail}}let X=(g?.ready??!1)&&y.ok,G=y.detail===null?g?.detail??"control plane not yet probed":`${g?.detail??"control plane not yet probed"}; ${y.detail}`;_o(C,X?200:503,{ok:X,control_plane:G});return}if(_.method==="GET"&&$.pathname==="/lanez"){_o(C,200,{pools:a?await a.registry.status():null});return}let N=$.pathname==="/v1"||$.pathname.startsWith("/v1/"),D=$.pathname.startsWith("/partners/");if(!N&&!D){md(C,404,`no route for ${_.method} ${$.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}await p(_,C)||v(_,C)})().catch(N=>{if(!C.headersSent){md(C,500,String(N instanceof Error?N.message:N),"proxy_error");return}C.end()})}),A=t.conversations??new mo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),P=new WeakMap,R=[Yo(S,{authenticate:async _=>{let C=await Gs(_,e,n,r),$=A.connectionFor(C);return{clients:$.clients,scope:po(C.apiKey),onBindResumeHandle:$.bindResumeHandle,clientsForResume:$.clientsForResume,release:$.release}}}),as(S,{clients:async _=>l.clientsFor(await E(_)),statusOf:x}).close,Mr(S,{resolver:{resolve:async(_,C,$)=>{let N=await E(_),D=A.connectionFor(N,lu(_)),q;try{q=await uu(Ps(D.clients,t.realtimeCompanions),iu(_),C,au(_),$)}catch(re){throw D.release().catch(()=>{}),re}let X=q.release,G={...q,release:async()=>{await X?.(),await D.release()}};return P.set(G,N.orgId),G}},onSessionEnded:_=>{ur({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:Pt(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:_.binding.model??null,stream:null,org:P.get(_.binding)??null,duration_ms:_.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:_.connected_ms/1e3,session_id:_.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:_.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:_.req})}})];if(t.lane&&a){let _=t.lane,C=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=Vu(S,{verifyToken:(N,D)=>Us(N,D,_.tokenSecret,void 0,C),selfAddress:_.selfAddress,laneTenantOf:N=>a.redis.get(`lane_tenant:${N}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:C,hostRegistry:{setHost:(N,D)=>a.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${N}`,D,String(Ju)),delHost:N=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${N}`,_.selfAddress)}}),i=Pu(S,{verifyToken:(N,D)=>Us(N,D,_.tokenSecret,void 0,C),selfAddress:_.selfAddress,hostOf:async N=>{let D=await a.redis.get(`lane_hosts:${N}`);return D&&D.trim()!==""?D.trim():null},podToPodDial:(N,D,q)=>new Promise((X,G)=>{(async()=>{let re=await a.redis.get(`lane_tenant:${N}`),K=Xn(N,_.tokenSecret,void 0,void 0,re||void 0),M=`ws://${q}/stream/${encodeURIComponent(N)}/${encodeURIComponent(D)}?token=${encodeURIComponent(K)}`,ee=new gd.default(M,eo(D));ee.once("open",()=>X(ee)),ee.once("error",G)})().catch(G)})});let $=a;R.push(async()=>{await s.close(),await i.close(),await $.registry.close(),$.redis.quit().catch(()=>{})})}S.on("upgrade",(_,C)=>{let $=new URL(_.url??"/","http://localhost");$.pathname===Sr||$.pathname===ss||$.pathname===Hn||s!==null&&$.pathname.startsWith("/doc/")||i!==null&&$.pathname.startsWith("/stream/")||C.destroyed||(C.write(`HTTP/1.1 404 Not Found\r
|