@urun-sh/openai 0.6.29 → 0.6.30

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.
@@ -2,7 +2,7 @@ import{c as Je,e as yn,f as D,g as se}from"./chunk-CUDFHFNX.js";import{a as wn,c
2
2
  Connection: close\r
3
3
  \r
4
4
  ${p}\r
5
- `),i.destroy())}))});let o=null;return()=>(o??=(async()=>{for(let a of r.clients)a.close(1001,"server closing");await new Promise((a,i)=>r.close(u=>u===void 0?a():i(u)))})(),o)}function ji(n,e,t=new ct){new pt(n,e,t)}A();import ms from"os";import fs from"path";import{fileURLToPath as hs}from"url";import{format as gs}from"util";var $n="0.6.29";var Fn=4141,_s=$n,Qi={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ys(n,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${n}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${n}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Zi(n,e,t){let r={...n,...ys(e,t)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ea(n,e,t){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${n}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],s=t.indexOf("--"),o=s===-1?t:t.slice(0,s),a=o.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),i=t[0]==="exec",u=o.includes("--skip-git-repo-check"),d=i&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...r,...a?[]:["-m",e],...d]}function ta(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",n,...e]}function na(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${n}`,...e]}function ra(n,e,t){let r=(n.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!t(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let s=hs(new URL("../pi-extension/standalone.cjs",e));if(!t(s))throw new Error(`pi extension entry not found at ${s} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return s}function Dn(n){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${n}`);return e}function sa(n){if(n[0]!=="--port")return null;let e=Dn(n[1]);return n.splice(0,2),e}function oa(n){let e=n.indexOf("--port");if(e===-1)return Fn;let t=Dn(n[e+1]);return n.splice(e,2),t}function ia(n){if(n===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return n}function Ft(n,e){let t=(n[e]??"").trim();if(!t)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function aa(n){let e=ws(Ft(n,"URUN_BASE_URL")),t=Ft(n,"URUN_ORG_ID"),r=Ft(n,"URUN_APP"),s=(n.URUN_FUNCTION??"serve").trim()||"serve",o=(n.URUN_API_URL??"").trim(),a=o?Nn(o,"URUN_API_URL"):yn,i=(n.URUN_JWT??"").trim();if(i)return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(n.URUN_API_KEY??"").trim();if(u){let d=(n.URUN_GATEWAY_URL??"").trim(),l=d?Nn(d):void 0;return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function ws(n,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(n).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${n} \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 n}function Nn(n,e="URUN_GATEWAY_URL"){let t=new URL(n),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${n}) \u2014 the org API key rides the request's Authorization header`);return n}function ua(n){return{app:n.appId,org:n.orgId,fn:n.fnName,base_url:n.baseUrl,proxy_version:_s}}function vs(n,e){return n.app===e.app&&n.org===e.org&&n.fn===e.fn&&n.base_url===e.base_url&&n.proxy_version===e.proxy_version}var bs=250;async function xs(n,e=bs){try{let t=await fetch(`http://127.0.0.1:${n}/stats`,{signal:AbortSignal.timeout(e)});if(!t.ok)return null;let r=(await t.json()).identity;if(r==null||typeof r!="object")return null;let{app:s,org:o,fn:a,base_url:i,proxy_version:u}=r;return typeof s!="string"||typeof o!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:s,org:o,fn:a,base_url:i,proxy_version:u}}catch{return null}}var qn=2e3;async function ks(n,e=qn){try{let t=await fetch(`http://127.0.0.1:${n}/v1/models`,{signal:AbortSignal.timeout(e)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function da(n,e,t=Fn,r=qn){if(n!=null)return{mode:"spawn",port:n};let s=await xs(t);if(s!==null&&vs(s,e)){let o=await ks(t,r);return o===null?{mode:"reuse",port:t,identity:s}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${o}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function la(n,e=ms.homedir()){return fs.join(e,".urun","logs",`compat-proxy-${n}.log`)}var Dt=["log","info","warn","error","debug","trace"];function ca(n,e=process,t=console){let r=e.stdout.write,s=e.stderr.write,o=(i,...u)=>n.write(i,...u);e.stdout.write=o,e.stderr.write=o;let a=Object.fromEntries(Dt.map(i=>[i,t[i]]));for(let i of Dt)t[i]=(...u)=>{n.write(`${gs(...u)}
5
+ `),i.destroy())}))});let o=null;return()=>(o??=(async()=>{for(let a of r.clients)a.close(1001,"server closing");await new Promise((a,i)=>r.close(u=>u===void 0?a():i(u)))})(),o)}function ji(n,e,t=new ct){new pt(n,e,t)}A();import ms from"os";import fs from"path";import{fileURLToPath as hs}from"url";import{format as gs}from"util";var $n="0.6.30";var Fn=4141,_s=$n,Qi={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ys(n,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${n}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${n}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Zi(n,e,t){let r={...n,...ys(e,t)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ea(n,e,t){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${n}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],s=t.indexOf("--"),o=s===-1?t:t.slice(0,s),a=o.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),i=t[0]==="exec",u=o.includes("--skip-git-repo-check"),d=i&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...r,...a?[]:["-m",e],...d]}function ta(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",n,...e]}function na(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${n}`,...e]}function ra(n,e,t){let r=(n.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!t(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let s=hs(new URL("../pi-extension/standalone.cjs",e));if(!t(s))throw new Error(`pi extension entry not found at ${s} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return s}function Dn(n){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${n}`);return e}function sa(n){if(n[0]!=="--port")return null;let e=Dn(n[1]);return n.splice(0,2),e}function oa(n){let e=n.indexOf("--port");if(e===-1)return Fn;let t=Dn(n[e+1]);return n.splice(e,2),t}function ia(n){if(n===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return n}function Ft(n,e){let t=(n[e]??"").trim();if(!t)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function aa(n){let e=ws(Ft(n,"URUN_BASE_URL")),t=Ft(n,"URUN_ORG_ID"),r=Ft(n,"URUN_APP"),s=(n.URUN_FUNCTION??"serve").trim()||"serve",o=(n.URUN_API_URL??"").trim(),a=o?Nn(o,"URUN_API_URL"):yn,i=(n.URUN_JWT??"").trim();if(i)return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(n.URUN_API_KEY??"").trim();if(u){let d=(n.URUN_GATEWAY_URL??"").trim(),l=d?Nn(d):void 0;return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function ws(n,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(n).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${n} \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 n}function Nn(n,e="URUN_GATEWAY_URL"){let t=new URL(n),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${n}) \u2014 the org API key rides the request's Authorization header`);return n}function ua(n){return{app:n.appId,org:n.orgId,fn:n.fnName,base_url:n.baseUrl,proxy_version:_s}}function vs(n,e){return n.app===e.app&&n.org===e.org&&n.fn===e.fn&&n.base_url===e.base_url&&n.proxy_version===e.proxy_version}var bs=250;async function xs(n,e=bs){try{let t=await fetch(`http://127.0.0.1:${n}/stats`,{signal:AbortSignal.timeout(e)});if(!t.ok)return null;let r=(await t.json()).identity;if(r==null||typeof r!="object")return null;let{app:s,org:o,fn:a,base_url:i,proxy_version:u}=r;return typeof s!="string"||typeof o!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:s,org:o,fn:a,base_url:i,proxy_version:u}}catch{return null}}var qn=2e3;async function ks(n,e=qn){try{let t=await fetch(`http://127.0.0.1:${n}/v1/models`,{signal:AbortSignal.timeout(e)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function da(n,e,t=Fn,r=qn){if(n!=null)return{mode:"spawn",port:n};let s=await xs(t);if(s!==null&&vs(s,e)){let o=await ks(t,r);return o===null?{mode:"reuse",port:t,identity:s}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${o}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function la(n,e=ms.homedir()){return fs.join(e,".urun","logs",`compat-proxy-${n}.log`)}var Dt=["log","info","warn","error","debug","trace"];function ca(n,e=process,t=console){let r=e.stdout.write,s=e.stderr.write,o=(i,...u)=>n.write(i,...u);e.stdout.write=o,e.stderr.write=o;let a=Object.fromEntries(Dt.map(i=>[i,t[i]]));for(let i of Dt)t[i]=(...u)=>{n.write(`${gs(...u)}
6
6
  `)};return()=>{e.stdout.write=r,e.stderr.write=s;for(let i of Dt)t[i]=a[i]}}var Ss=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bn(n){let e=n?.code;return typeof e=="string"&&Ss.has(e)}function _e(n,e){try{return n.write(e),!0}catch(t){if(Bn(t))return!1;throw t}}function pa(n){let e={stdout:!1,stderr:!1},t=[];for(let r of["stdout","stderr"]){let s=n.streams[r],o=a=>{Bn(a)&&(e[r]=!0);let i=a?.code;try{n.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
7
7
  `)}catch{}};s.on("error",o),t.push([s,o])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,s]of t)r.off("error",s)}}}function ma(n){let e=t=>{let r=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{n.appendSync(n.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
8
8
  `)}catch{}n.restore();try{n.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${n.logPath}
@@ -1,2 +1,2 @@
1
- import{a as M}from"./chunk-K23AZPI4.js";import{I as j,J as B,N as _,O as K,P as q}from"./chunk-RUJPI6BV.js";import{a as F}from"./chunk-76BZLCGT.js";import{a as x,b as G,d as $,g as A,h as W,j as E,k as H,l as V}from"./chunk-CUDFHFNX.js";import{c as R,f as D,g as N,p as U}from"./chunk-6M5JK4YC.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as z,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as ue,DEFAULT_WHEN_LIVE_TIMEOUT_MS as Z,isWakingPhase as pe}from"@urun-sh/core";v();import{SessionFailedError as te}from"@urun-sh/core";var L=2;function se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function ie(e){let s=e?.type;return s==="response.completed"||s==="error"}function Q(e){return async function(a,d){return(async function*(){for(let l=1;l<=L;l++){let{app:p,entry:f,identity:t}=await e.sessionFor(a.model);d?.({sessionId:e.sessionIdOf?.(f)??null,identity:t});let i=!1,c=!1;try{let m=await e.createStream(f,a);for await(let g of m){if(ie(g)&&(i=!0),se(g)){if(l>1)continue}else c=!0;yield g}}catch(m){if(m instanceof te&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(p,f,m)}catch{}throw m}if(l<L&&!c){await e.evict(p,f);continue}throw m}if(i)return;if(l<L&&!c){await e.evict(p,f);continue}return}})()}}import{randomUUID as fe}from"crypto";v();var re=3,ae="llm",le=new Set(["paused","error"]);function Y(e,s){let a=e.doc(ae),d=typeof a.onConnectionState=="function",u=typeof e.onPhase=="function";if(!d&&!u)throw new Error(`session for app "${s}" 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 l=null,p=!1,f=new Set,t=[],i=c=>{if(!l){l=c;for(let m of[...f])m(c);f.clear()}};return d&&t.push(a.onConnectionState(c=>{p&&(c.consecutiveFailures<re||i(new A(`the pooled session for app "${s}" 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.`)))})),u&&t.push(e.onPhase(c=>{if(c.name==="live"){p=!0;return}p&&le.has(c.name)&&i(new A(`the pooled session for app "${s}" 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.`))})),{gone:()=>l,onGone(c){return l?(c(l),()=>{}):(f.add(c),()=>f.delete(c))},dispose(){f.clear();for(let c of t.splice(0))c()}}}async function*C(e,s){let a=s.gone();if(a)throw a;let d=e[Symbol.asyncIterator](),u,l=new Promise((p,f)=>{u=s.onGone(t=>f(t))});l.catch(()=>{});try{for(;;){let p=await Promise.race([d.next(),l]);if(p.done)return;yield p.value}}finally{u?.(),d.return?.(void 0)}}var me=1,ge=4,he=4;function He(e,s){let a=(p,f)=>{let t=(e[p]??"").trim();if(!t)return f;let i=Number.parseInt(t,10);if(!Number.isInteger(i)||i<1)throw new Error(`${p} must be a positive integer (got ${JSON.stringify(e[p])})`);return i},d=(e.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let u=d?Number.parseInt(d,10):me;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let l=a("URUN_DECISION_POOL_MAX",Math.max(u,ge));return{min:u,max:l,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",he),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function Ve(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return _;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function ee(e,s,a,d){let u=e[a];if(typeof u!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let l=d?u(void 0,d):u();if(typeof l.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return l}function oe(e,s,a,d){let{baseUrl:u,orgId:l,auth:p}=e,f=s.fnName??e.fnName,t=e.sessionStartOptions?.(a),i=d||t||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...t,...d}:void 0,c=o=>({session:o,responses:new F(o),gone:Y(o,a)});if(p.lane==="jwt"){let o=z(s.appSlug,{baseUrl:u,orgId:l,jwt:p.jwt});return c(ee(o,s.appSlug,f,i))}let{apiKey:m,gatewayUrl:g}=p,w=(typeof e.subject=="function"?e.subject():e.subject)??fe(),n=z(s.appSlug,{baseUrl:u,orgId:l,getAccessToken:async()=>(await de(m,{baseUrl:g,expiresIn:300,allowedFunctions:[`${s.appSlug}/${f}`],subject:w,...s.sharedApp?{sharedApp:!0}:{}})).token});return c(ee(n,s.appSlug,f,i))}function we(e){let s=e.session.id;if(typeof s!="string"||s.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return s}function Se(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var ye=new Set(["error","paused"]);function je(e){let{auth:s,catalog:a}=e,d=null,u=(p,f)=>{let t=oe(e,p,f);return e.onSessionOpen&&typeof t.session.id=="string"&&t.session.id!==""&&e.onSessionOpen(f,t.session.id),t.gone.onGone(()=>{d?.evict(f,t)}),t},l=new V({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async p=>{if(p.gone.dispose(),e.release==="detach"){if(typeof p.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');p.session.detach();return}await p.session.end()},listApps:s.lane==="api-key"?()=>W({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:a?()=>M(a):null,listPrices:a?()=>G(a):null,shared:s.lane==="api-key"?()=>x({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,sessionKey:we});return d=l,e.defaultApp!==null&&l.seed(e.defaultApp,u({appSlug:e.defaultApp},E({appSlug:e.defaultApp}))),l}function Be(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",u=new Map,l=new Map,p=t=>{process.stderr.write(`[decision-pool] ${t}
1
+ import{a as M}from"./chunk-K23AZPI4.js";import{I as j,J as B,N as _,O as K,P as q}from"./chunk-55LV3IXW.js";import{a as F}from"./chunk-76BZLCGT.js";import{a as x,b as G,d as $,g as A,h as W,j as E,k as H,l as V}from"./chunk-CUDFHFNX.js";import{c as R,f as D,g as N,p as U}from"./chunk-6M5JK4YC.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as z,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as ue,DEFAULT_WHEN_LIVE_TIMEOUT_MS as Z,isWakingPhase as pe}from"@urun-sh/core";v();import{SessionFailedError as te}from"@urun-sh/core";var L=2;function se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function ie(e){let s=e?.type;return s==="response.completed"||s==="error"}function Q(e){return async function(a,d){return(async function*(){for(let l=1;l<=L;l++){let{app:p,entry:f,identity:t}=await e.sessionFor(a.model);d?.({sessionId:e.sessionIdOf?.(f)??null,identity:t});let i=!1,c=!1;try{let m=await e.createStream(f,a);for await(let g of m){if(ie(g)&&(i=!0),se(g)){if(l>1)continue}else c=!0;yield g}}catch(m){if(m instanceof te&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(p,f,m)}catch{}throw m}if(l<L&&!c){await e.evict(p,f);continue}throw m}if(i)return;if(l<L&&!c){await e.evict(p,f);continue}return}})()}}import{randomUUID as fe}from"crypto";v();var re=3,ae="llm",le=new Set(["paused","error"]);function Y(e,s){let a=e.doc(ae),d=typeof a.onConnectionState=="function",u=typeof e.onPhase=="function";if(!d&&!u)throw new Error(`session for app "${s}" 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 l=null,p=!1,f=new Set,t=[],i=c=>{if(!l){l=c;for(let m of[...f])m(c);f.clear()}};return d&&t.push(a.onConnectionState(c=>{p&&(c.consecutiveFailures<re||i(new A(`the pooled session for app "${s}" 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.`)))})),u&&t.push(e.onPhase(c=>{if(c.name==="live"){p=!0;return}p&&le.has(c.name)&&i(new A(`the pooled session for app "${s}" 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.`))})),{gone:()=>l,onGone(c){return l?(c(l),()=>{}):(f.add(c),()=>f.delete(c))},dispose(){f.clear();for(let c of t.splice(0))c()}}}async function*C(e,s){let a=s.gone();if(a)throw a;let d=e[Symbol.asyncIterator](),u,l=new Promise((p,f)=>{u=s.onGone(t=>f(t))});l.catch(()=>{});try{for(;;){let p=await Promise.race([d.next(),l]);if(p.done)return;yield p.value}}finally{u?.(),d.return?.(void 0)}}var me=1,ge=4,he=4;function He(e,s){let a=(p,f)=>{let t=(e[p]??"").trim();if(!t)return f;let i=Number.parseInt(t,10);if(!Number.isInteger(i)||i<1)throw new Error(`${p} must be a positive integer (got ${JSON.stringify(e[p])})`);return i},d=(e.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let u=d?Number.parseInt(d,10):me;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let l=a("URUN_DECISION_POOL_MAX",Math.max(u,ge));return{min:u,max:l,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",he),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function Ve(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return _;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function ee(e,s,a,d){let u=e[a];if(typeof u!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let l=d?u(void 0,d):u();if(typeof l.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return l}function oe(e,s,a,d){let{baseUrl:u,orgId:l,auth:p}=e,f=s.fnName??e.fnName,t=e.sessionStartOptions?.(a),i=d||t||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...t,...d}:void 0,c=o=>({session:o,responses:new F(o),gone:Y(o,a)});if(p.lane==="jwt"){let o=z(s.appSlug,{baseUrl:u,orgId:l,jwt:p.jwt});return c(ee(o,s.appSlug,f,i))}let{apiKey:m,gatewayUrl:g}=p,w=(typeof e.subject=="function"?e.subject():e.subject)??fe(),n=z(s.appSlug,{baseUrl:u,orgId:l,getAccessToken:async()=>(await de(m,{baseUrl:g,expiresIn:300,allowedFunctions:[`${s.appSlug}/${f}`],subject:w,...s.sharedApp?{sharedApp:!0}:{}})).token});return c(ee(n,s.appSlug,f,i))}function we(e){let s=e.session.id;if(typeof s!="string"||s.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return s}function Se(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var ye=new Set(["error","paused"]);function je(e){let{auth:s,catalog:a}=e,d=null,u=(p,f)=>{let t=oe(e,p,f);return e.onSessionOpen&&typeof t.session.id=="string"&&t.session.id!==""&&e.onSessionOpen(f,t.session.id),t.gone.onGone(()=>{d?.evict(f,t)}),t},l=new V({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async p=>{if(p.gone.dispose(),e.release==="detach"){if(typeof p.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');p.session.detach();return}await p.session.end()},listApps:s.lane==="api-key"?()=>W({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:a?()=>M(a):null,listPrices:a?()=>G(a):null,shared:s.lane==="api-key"?()=>x({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,sessionKey:we});return d=l,e.defaultApp!==null&&l.seed(e.defaultApp,u({appSlug:e.defaultApp},E({appSlug:e.defaultApp}))),l}function Be(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",u=new Map,l=new Map,p=t=>{process.stderr.write(`[decision-pool] ${t}
2
2
  `)},f=(t,i)=>{let c=u.get(i);if(c)return c;let m=new B({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:d,openSlot:async g=>{let w=oe(e,t,i,{concurrencyKey:g.concurrencyKey});return w.gone.onGone(()=>m.evict(w)),await b(w.session),p(`slot attached pool=${i} slot=${g.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async g=>{g.gone.dispose(),await g.session.end()},onDetach:(g,w)=>p(`slot detached pool=${i} slot=${g.concurrencyKey} reason=${w}`)});return u.set(i,m),m};return{async boot(){if(e.defaultApp===null)return;let t={appSlug:e.defaultApp};await f(t,E(t)).boot()},async sessionFor(t){let i=await s.resolveTargetFor(t),c=E(i),m=f(i,c).tryAcquireReady();if(!m)throw new j(f(i,c).stats().lastMissAgeMs);let g=l.get(m.entry)??[];return g.push(m),l.set(m.entry,g),{app:c,entry:m.entry,identity:H(i)}},async warmFor(t){let i=await s.resolveTargetFor(t);await f(i,E(i)).boot()},end(t){let i=l.get(t)?.shift();i&&(l.get(t)?.length===0&&l.delete(t),i.release())},evict(t){for(let i of u.values())i.evict(t)},reap(){for(let t of u.values())t.reap()},async pingReady(t){for(let i of u.values())if(await i.pingReady(t))return!0;return!1},stats(){return[...u.entries()].map(([t,i])=>({poolKey:t,...i.stats()}))},async drain(t){await Promise.all([...u.values()].map(i=>i.drain({timeoutMs:t})))},async close(){await Promise.all([...u.values()].map(t=>t.close()))}}}function ve(e){return pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Z:ue:Z}async function b(e,s){let a=e.whenLive;if(typeof a!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await a.call(e,{timeout:ve(e.phase),signal:s})}async function ne(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function O(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Ke(e,s=N,a,d,u=_){let l=new WeakMap,p=new WeakMap,f=new WeakMap,t=new WeakMap,i=new WeakMap,c=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},m=n=>{let o=l.get(n);if(!o){let r={waiting:0,gone:new AbortController};i.set(n,r),o=(async()=>{if(await b(n.session,r.gone.signal),r.gone.signal.aborted)throw O(r.gone.signal);i.get(n)===r&&i.delete(n);let h=await R(n.session,await s());return Object.assign(h,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{i.get(n)===r&&i.delete(n)},()=>{i.get(n)===r&&i.delete(n)})}return o},g=n=>{let o=t.get(n);return o||(o=(async()=>{let r=await m(n);return{appendInputAudio:h=>r.appendInputAudio(h),onOutputAudio:h=>r.onOutputAudio(h),sessionId:c(n)}})(),t.set(n,o),o.catch(()=>{t.get(n)===o&&t.delete(n)})),o},w=async(n,o,r)=>{if(r?.aborted){let S=i.get(n);throw(l.get(n)===void 0||S!==void 0&&S.waiting===0)&&await ne(n.session),O(r)}let h=o(n),y=i.get(n);return y!==void 0&&y.waiting++,r===void 0?h:new Promise((S,P)=>{let T=()=>{y!==void 0&&--y.waiting===0&&i.get(n)===y&&(y.gone.abort(),i.delete(n),l.delete(n),t.delete(n),ne(n.session).catch(()=>{})),P(O(r))};r.addEventListener("abort",T,{once:!0});let k=()=>r.removeEventListener("abort",T);h.then(I=>{k(),S(I)},I=>{k(),P(I)})})};return{createResponse:Q({sessionFor:d?n=>d.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>c(n),evict:(n,o)=>{d?d.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,r)=>{Se(r)&&(d?d.evict(o):e.evict(n,o),a?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await b(n.session);let r=K(C(await n.responses.responses.create(o),n.gone),u);if(!d)return r;let h=n;return(async function*(){try{yield*r}catch(S){throw q(S)&&d.evict(h),S}finally{d.end(h)}})()}catch(r){throw d&&d.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:r}=await e.sessionFor(n);return await w(r,m,o)},openAudioOn:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n);return await w(r,g,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw O(o);let{entry:r}=await e.sessionForHandle(n);yield*$(r.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),r=p.get(o);return r||(r=D(o.session),p.set(o,r)),r},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),r=f.get(o);return r||(r=U(o.session),f.set(o,r)),r},sessionHandle:async n=>(await e.handleFor(n)).handle,speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:r}=await e.sessionForHandle(n);await e.evict(o,r)},createResponseOn:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n);return await b(r.session),C(await r.responses.responses.create(o),r.gone)},onSessionEnd:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n),h=r.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let y=!1;return h.onPhase(S=>{if(y||!ye.has(S.name))return;y=!0;let P=h.endsAt??null;o({timeLeftMs:P?Math.max(0,P.getTime()-Date.now()):null,reason:S.reason??`session ${S.name}`})})}}}export{He as a,Ve as b,je as c,Be as d,Ke as e};
@@ -1,4 +1,4 @@
1
- import{a as ke,c as W,d as xe,e as J}from"./chunk-7E2KNW2C.js";import{C as ue,D as de,E as he,F as pe,G as ge,K as fe,L as T,M as me,Q as ye,R as we,S as be,T as _e,U as ve,V as Ee,W as Se,X as Re,b as ie,d as ae,e as le,q as ce,r as O}from"./chunk-RUJPI6BV.js";import{c as re,g as oe,i as j}from"./chunk-CUDFHFNX.js";import{a as se}from"./chunk-3JWYIKHM.js";import{c as m}from"./chunk-YSFSRI3D.js";m();import{Counter as I,Gauge as Ie,Histogram as Ce,Registry as Ke,collectDefaultMetrics as Be}from"@prometheus-io/client";import{createServer as ze}from"http";var jt=9464,Ne="/metrics",A="(other)",je="(none)",We=64,Je=128,Ye=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",fe,ye,re],Ve=new Set(Ye);function qe(t){return Ve.has(t)?t:A}function Qe(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var P=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?je:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,A):(this.admitted.add(e),e):A}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},U=class{registry=new Ke;modelLabel=new P(We);orgLabel=new P(Je);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new I({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new Ce({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new Ce({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new I({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new I({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new I({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of we)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Ie({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},be()),this.ledgerQueue.set({measure:"oldest_age_seconds"},_e()/1e3)}}),this.labelCardinality=new Ie({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new I({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&Be({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=qe(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,a=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?A:e.method,status_class:Qe(e.status),stream:u,model:a,org:s}),this.duration.observe({lane:n,stream:u,model:a,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:a,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:a}),e.delivered||this.undelivered.inc({lane:n,model:a})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Oe(t){return ze((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ne){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ne}
1
+ import{a as ke,c as W,d as xe,e as J}from"./chunk-OPMTYD3Z.js";import{C as ue,D as de,E as he,F as pe,G as ge,K as fe,L as T,M as me,Q as ye,R as we,S as be,T as _e,U as ve,V as Ee,W as Se,X as Re,b as ie,d as ae,e as le,q as ce,r as O}from"./chunk-55LV3IXW.js";import{c as re,g as oe,i as j}from"./chunk-CUDFHFNX.js";import{a as se}from"./chunk-3JWYIKHM.js";import{c as m}from"./chunk-YSFSRI3D.js";m();import{Counter as I,Gauge as Ie,Histogram as Ce,Registry as Ke,collectDefaultMetrics as Be}from"@prometheus-io/client";import{createServer as ze}from"http";var jt=9464,Ne="/metrics",A="(other)",je="(none)",We=64,Je=128,Ye=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",fe,ye,re],Ve=new Set(Ye);function qe(t){return Ve.has(t)?t:A}function Qe(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var P=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?je:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,A):(this.admitted.add(e),e):A}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},U=class{registry=new Ke;modelLabel=new P(We);orgLabel=new P(Je);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new I({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new Ce({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new Ce({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new I({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new I({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new I({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of we)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Ie({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},be()),this.ledgerQueue.set({measure:"oldest_age_seconds"},_e()/1e3)}}),this.labelCardinality=new Ie({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new I({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&Be({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=qe(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,a=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?A:e.method,status_class:Qe(e.status),stream:u,model:a,org:s}),this.duration.observe({lane:n,stream:u,model:a,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:a,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:a}),e.delivered||this.undelivered.inc({lane:n,model:a})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Oe(t){return ze((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ne){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ne}
2
2
  `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
3
  `);return}n.end()})})}m();import{createHash as Ae}from"crypto";import{createServer as Xe}from"http";var qt=9465,Ze="x-urun-key-id",et="x-urun-key-fingerprint",tt="urun-ratelimit-bucket:",nt="urun-ratelimit-tier:",Te="anonymous",rt=/^urun_sk_[A-Za-z0-9_-]{43}$/;function ot(t){return Ae("sha256").update(`${tt}${t}`).digest("hex")}function st(t){return Ae("sha256").update(`${nt}${t}`).digest("hex")}function it(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return rt.test(n)?n:null}function Pe(){return Xe((t,e)=>{let n=it(t.headers.authorization);e.setHeader(Ze,n===null?Te:ot(n)),e.setHeader(et,n===null?Te:st(n)),e.writeHead(200),e.end()})}m();import{createClientToken as at,ClientTokenError as lt}from"@urun-sh/core";var w=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},k=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function C(t){let e=(t??"").trim();if(e==="")throw new w("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 w("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var ct=60,ut=6e4,dt=4096;function ht(t){return t===401||t===403}var L=class{constructor(e){this.opts=e;this.mint=e.mint??at,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new w("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<ut)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:ct})).orgId}catch(o){throw o instanceof lt&&ht(o.status)?(this.cache.delete(e),new w("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new k(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new k("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=dt){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};m();var pt=8080,Y="serve",rn="0.0.0.0";function gt(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function on(t=process.env){let e=(t.PORT??"").trim(),n=e===""?pt:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=ce(O(gt(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),a=o?O(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!i)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=s?{catalogUrl:O(s,"URUN_CATALOG_URL"),anonKey:i}:null,c=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),h=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!h)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");return{port:n,baseUrl:r,apiUrl:a,catalog:u,ledgerSigning:c?{keyId:h,key:c}:void 0}}m();import{createHash as ft,randomUUID as mt}from"crypto";var yt=512;function V(t){return`urun-inference-proxy-${ft("sha256").update(t).digest("hex").slice(0,32)}`}var $=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return a.decision&&this.ensureDecisionReaper(),{router:a.router,clients:this.label(a.clients,e),decision:a.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Y,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ke(process.env,process.env.HOSTNAME)??void 0},r=W(n),o=n.decisionPool?xe(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(J(r,void 0,void 0,o??void 0),e),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>=yt;){let o=this.tenants.entries().next();if(o.done)break;let[a,s]=o.value;this.tenants.delete(a),s.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(a=>{n.push(String(a instanceof Error?a.message:a))})];r.decision&&o.push(r.decision.close().catch(a=>{n.push(String(a instanceof Error?a.message:a))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ue=512,wt=1024,H=class extends Error{constructor(){super(`conversation capacity reached (${Ue} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function bt(t){return{sessionStartOptions:e=>{if(e.startsWith(j))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(j)||t.set(e,n)}}}function _t(t,e,n,r){let o=W({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Y,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...bt(r)});return{clients:J(o),release:async()=>{await o.closeAll()}}}var D=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${V(e.apiKey)}:live:${n}`},o=new Map,a=this.opts.build?this.opts.build(e,r):_t(this.opts,e,r,o);return{id:n,backhaul:a,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let a=this.build(e,n);return a.attachments=1,r.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Ue;){let e=this.byCaller.keys().next();if(e.done)throw new H;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[a,s]of r)if(!(s.attachments>0)){r.delete(a),this.dropHandleIndexFor(n,a),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new H;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,mt())),n),a={createResponse:(s,i)=>o().backhaul.clients.createResponse(s,i),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let i=o().backhaul.clients.servingAppSlug;if(i===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 i(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),createResponseOn:(s,i)=>o().backhaul.clients.createResponseOn(s,i),onSessionEnd:(s,i)=>o().backhaul.clients.onSessionEnd(s,i)};return a.openAudio=async(s,i)=>{let u=o().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(s,i)},a.openVideo=async s=>{let i=o().backhaul.clients.openVideo;if(i===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return i(s)},a.openVideoOut=async s=>{let i=o().backhaul.clients.openVideoOut;if(i===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return i(s)},a.supportsAudio=async s=>{let i=o().backhaul.clients.supportsAudio;if(i===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return i(s)},a.supportsSpeech=async s=>{let i=o().backhaul.clients.supportsSpeech;if(i===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return i(s)},a.speechVoices=async s=>{let i=o().backhaul.clients.speechVoices;if(i===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 i(s)},a.speechSessionHandle=async s=>{let i=o().backhaul.clients.speechSessionHandle;if(i===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 i(s)},a.openAudioOn=async(s,i)=>{let u=o().backhaul.clients.openAudioOn;if(u===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 u(s,i)},a.openTurnsOn=(s,i)=>{let u=o().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(s,i)},a.evictSpeechSession=async s=>{let i=o().backhaul.clients.evictSpeechSession;if(i===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 i(s)},a.supportsTranscription=async s=>{let i=o().backhaul.clients.supportsTranscription;if(i===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return i(s)},a.transcriptStreamFor=async s=>{let i=o().backhaul.clients.transcriptStreamFor;if(i===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 i(s)},a.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===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 s()},{clients:a,bindResumeHandle:s=>{let i=n;if(i===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=wt;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:i.id})},clientsForResume:async s=>{let i=this.byHandle.get(s),u=i===void 0?void 0:this.byCaller.get(i.apiKey),c=i===void 0||u===void 0?void 0:u.get(i.conversationId);if(i===void 0||c===void 0||i.apiKey!==e.apiKey)throw new oe("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 n=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.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("; ")}`)}};m();var vt="/inference-ledger",Et=1e4,M=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},X=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},g=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Z=class extends w{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ee=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},St=[["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",q],["output_minutes",q],["cost_nano_usd",q],["price_version",t=>t===null||typeof t=="string"]];function Rt(t){for(let[e,n]of St){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function kt(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"}:Rt(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function q(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Q(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function xt(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Le(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 It(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&&Le(t.started_at,n.started_at)&&Le(t.completed_at,n.completed_at)&&Q(t.prompt_tokens,n.prompt_tokens)&&Q(t.completion_tokens,n.completion_tokens)&&Q(t.output_units,n.output_units)&&xt(t.output_minutes,n.output_minutes)}function Ct(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v1",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(n),t.started_at,t.completed_at].join(`
4
4
  `)}async function Nt(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(Ct(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Ot(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new g(`${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 g(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new g(`${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 g(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let a=c=>{if(!(c in n))throw new g(`${e} answered a row with no ${c} field: ${JSON.stringify(t)}`);let h=n[c];if(h===null)return null;if(typeof h!="string")throw new g(`${e} answered a non-string ${c}: ${JSON.stringify(h)}`);if(!/[^\s]/.test(h))throw new g(`${e} answered a BLANK ${c} (${JSON.stringify(h)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return h},s=a("price_version"),i=a("unpriced_reason"),u=o!=null;if(u&&(s===null||i!==null))throw new g(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}`);if(!u&&(s!==null||i===null))throw new g(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}. 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:s,unpriced_reason:i}}var G=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${vt}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Nt(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new g(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let a;try{a=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Et)})}catch(c){throw new g(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(a.status===409){let c=await a.text().catch(()=>""),h=kt(c);throw h.status==="found"&&It(n,h.row)?new X(h.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.`):h.status==="not_in_this_org"?new M(`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 M(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${h.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). ${c.slice(0,400)}`)}if(a.status===401||a.status===403)throw await a.text().catch(()=>{}),new Z("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(!a.ok){let c=await a.text().catch(y=>`<body unreadable: ${y instanceof Error?y.message:String(y)}>`),h;try{let y=JSON.parse(c);if(y!==null&&typeof y=="object"&&"error"in y){let E=y.error;E!==null&&typeof E=="object"&&"code"in E&&(h=E.code)}}catch{}throw h==="ledger_signature_invalid"?new ee(`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: `+c.slice(0,400)):new g(`the uRun ledger surface at ${r} answered HTTP ${a.status}: ${c.slice(0,400)}`)}let s;try{s=await a.json()}catch(c){throw new g(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let i=s?.recorded;if(i===void 0)throw new g(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=Ot(i,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new g(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};m();import{createServer as At}from"http";m();var F="/inference-usage",$e=25e3;var Tt=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function He(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Tt.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 K=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${F}`,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($e)})}catch(s){throw new T(`the uRun usage surface (POST ${F}) could not be reached within ${$e}ms: ${He(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new w("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 s=await o.text().catch(()=>null),i=s===null?"body unreadable":`${s.length}-character body`;throw new T(`the uRun usage surface (POST ${F}) answered HTTP ${o.status} (${i})`)}let a;try{a=await o.json()}catch(s){throw new T(`the uRun usage surface (POST ${F}) answered HTTP ${o.status} with a body that is not JSON: ${He(s)}`)}return me(a,this.opts.onRejectedRow)}};var Pt=5e3,Ut=1e3,Lt=1500,$t=3e3,Ht="/api/client-tokens";function te(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function De(t,e,n,r){te(t,e,{error:{message:n,type:r}})}async function Dt(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Ht}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout($t)});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 Ln(t){let e=t.resolver??new L({gatewayUrl:t.baseUrl}),n=t.registry??new $({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Dt(t.baseUrl)),o=async()=>{let l=null;for(let f of n.decisionPools()){l=f;break}if(!l)return null;let d=l.stats();if(d.some(f=>f.draining))return{ok:!1,detail:"decision pool draining"};if(d.every(f=>f.attached===0&&f.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let p=await l.pingReady(Lt);return{ok:p,detail:p?"a decision slot answered its session ping":"no decision slot answered its session ping"}},a=t.usageClient??new K({apiUrl:t.apiUrl}),s=t.ledgerClient??new G({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),i=process.env.URUN_SHARED_ORG_ID?.trim(),u=process.env.URUN_SHARED_ORG_API_KEY?.trim();i&&u&&(async()=>{try{await n.decisionWarmerFor({orgId:i,apiKey:u})?.warmFor(Se)}catch(l){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(l instanceof Error?l.message:l)}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{D as S,E as ve,U as ye,V as we,a as L,b as he,l as Z}from"../chunk-LCW3OUIV.js";import"../chunk-7E2KNW2C.js";import"../chunk-K23AZPI4.js";import{x as de,y as le}from"../chunk-RUJPI6BV.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{a as ze,b as Le,c as F}from"../chunk-YSFSRI3D.js";var _e=ze(()=>{"use strict";F();var pe;(function(_){(function(M){var w=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:m(),O=P(_);typeof w.Reflect<"u"&&(O=P(w.Reflect,O)),M(O,w),typeof w.Reflect>"u"&&(w.Reflect=_);function P(g,C){return function(I,D){Object.defineProperty(g,I,{configurable:!0,writable:!0,value:D}),C&&C(I,D)}}function x(){try{return Function("return this;")()}catch{}}function E(){try{return(0,eval)("(function() { return this; })()")}catch{}}function m(){return x()||E()}})(function(M,w){var O=Object.prototype.hasOwnProperty,P=typeof Symbol=="function",x=P&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=P&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",m=typeof Object.create=="function",g={__proto__:[]}instanceof Array,C=!m&&!g,I={create:m?function(){return z(Object.create(null))}:g?function(){return z({__proto__:null})}:function(){return z({})},has:C?function(e,t){return O.call(e,t)}:function(e,t){return t in e},get:C?function(e,t){return O.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},D=Object.getPrototypeOf(Function),A=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ue(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:We(),W=typeof WeakMap=="function"?WeakMap:Ne(),R=P?Symbol.for("@reflect-metadata:registry"):void 0,H=$e(),q=He(H);function Me(e,t,r,n){if(s(r)){if(!ne(e))throw new TypeError;if(!ae(t))throw new TypeError;return Se(e,t)}else{if(!ne(e))throw new TypeError;if(!h(t))throw new TypeError;if(!h(n)&&!s(n)&&!G(n))throw new TypeError;return G(n)&&(n=void 0),r=k(r),Re(e,t,r,n)}}M("decorate",Me);function ge(e,t){function r(n,f){if(!h(n))throw new TypeError;if(!s(f)&&!De(f))throw new TypeError;X(e,t,n,f)}return r}M("metadata",ge);function me(e,t,r,n){if(!h(r))throw new TypeError;return s(n)||(n=k(n)),X(e,t,r,n)}M("defineMetadata",me);function Oe(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),Y(e,t,r)}M("hasMetadata",Oe);function be(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),N(e,t,r)}M("hasOwnMetadata",be);function ke(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),J(e,t,r)}M("getMetadata",ke);function Te(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),Q(e,t,r)}M("getOwnMetadata",Te);function Ee(e,t){if(!h(e))throw new TypeError;return s(t)||(t=k(t)),K(e,t)}M("getMetadataKeys",Ee);function Pe(e,t){if(!h(e))throw new TypeError;return s(t)||(t=k(t)),ee(e,t)}M("getOwnMetadataKeys",Pe);function Ie(e,t,r){if(!h(t))throw new TypeError;if(s(r)||(r=k(r)),!h(t))throw new TypeError;s(r)||(r=k(r));var n=$(t,r,!1);return s(n)?!1:n.OrdinaryDeleteMetadata(e,t,r)}M("deleteMetadata",Ie);function Se(e,t){for(var r=e.length-1;r>=0;--r){var n=e[r],f=n(t);if(!s(f)&&!G(f)){if(!ae(f))throw new TypeError;t=f}}return t}function Re(e,t,r,n){for(var f=e.length-1;f>=0;--f){var v=e[f],p=v(t,r,n);if(!s(p)&&!G(p)){if(!h(p))throw new TypeError;n=p}}return n}function Y(e,t,r){var n=N(e,t,r);if(n)return!0;var f=B(t);return G(f)?!1:Y(e,f,r)}function N(e,t,r){var n=$(t,r,!1);return s(n)?!1:re(n.OrdinaryHasOwnMetadata(e,t,r))}function J(e,t,r){var n=N(e,t,r);if(n)return Q(e,t,r);var f=B(t);if(!G(f))return J(e,f,r)}function Q(e,t,r){var n=$(t,r,!1);if(!s(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function X(e,t,r,n){var f=$(r,n,!0);f.OrdinaryDefineOwnMetadata(e,t,r,n)}function K(e,t){var r=ee(e,t),n=B(e);if(n===null)return r;var f=K(n,t);if(f.length<=0)return r;if(r.length<=0)return f;for(var v=new U,p=[],c=0,a=r;c<a.length;c++){var i=a[c],o=v.has(i);o||(v.add(i),p.push(i))}for(var u=0,d=f;u<d.length;u++){var i=d[u],o=v.has(i);o||(v.add(i),p.push(i))}return p}function ee(e,t){var r=$(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function te(e){if(e===null)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return e===null?1:6;default:return 6}}function s(e){return e===void 0}function G(e){return e===null}function Ge(e){return typeof e=="symbol"}function h(e){return typeof e=="object"?e!==null:typeof e=="function"}function je(e,t){switch(te(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var r=t===3?"string":t===5?"number":"default",n=ie(e,x);if(n!==void 0){var f=n.call(e,r);if(h(f))throw new TypeError;return f}return xe(e,r==="default"?"number":r)}function xe(e,t){if(t==="string"){var r=e.toString;if(j(r)){var n=r.call(e);if(!h(n))return n}var f=e.valueOf;if(j(f)){var n=f.call(e);if(!h(n))return n}}else{var f=e.valueOf;if(j(f)){var n=f.call(e);if(!h(n))return n}var v=e.toString;if(j(v)){var n=v.call(e);if(!h(n))return n}}throw new TypeError}function re(e){return!!e}function Ce(e){return""+e}function k(e){var t=je(e,3);return Ge(t)?t:Ce(t)}function ne(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)==="[object Array]"}function j(e){return typeof e=="function"}function ae(e){return typeof e=="function"}function De(e){switch(te(e)){case 3:return!0;case 4:return!0;default:return!1}}function V(e,t){return e===t||e!==e&&t!==t}function ie(e,t){var r=e[t];if(r!=null){if(!j(r))throw new TypeError;return r}}function oe(e){var t=ie(e,E);if(!j(t))throw new TypeError;var r=t.call(e);if(!h(r))throw new TypeError;return r}function ue(e){return e.value}function fe(e){var t=e.next();return t.done?!1:t}function se(e){var t=e.return;t&&t.call(e)}function B(e){var t=Object.getPrototypeOf(e);if(typeof e!="function"||e===D||t!==D)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(n==null||n===Object.prototype)return t;var f=n.constructor;return typeof f!="function"||f===e?t:f}function Ae(){var e;!s(R)&&typeof w.Reflect<"u"&&!(R in w.Reflect)&&typeof w.Reflect.defineMetadata=="function"&&(e=Fe(w.Reflect));var t,r,n,f=new W,v={registerProvider:p,getProvider:a,setProvider:o};return v;function p(u){if(!Object.isExtensible(v))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===u:break;case s(t):t=u;break;case t===u:break;case s(r):r=u;break;case r===u:break;default:n===void 0&&(n=new U),n.add(u);break}}function c(u,d){if(!s(t)){if(t.isProviderFor(u,d))return t;if(!s(r)){if(r.isProviderFor(u,d))return t;if(!s(n))for(var l=oe(n);;){var y=fe(l);if(!y)return;var b=ue(y);if(b.isProviderFor(u,d))return se(l),b}}}if(!s(e)&&e.isProviderFor(u,d))return e}function a(u,d){var l=f.get(u),y;return s(l)||(y=l.get(d)),s(y)&&(y=c(u,d),s(y)||(s(l)&&(l=new A,f.set(u,l)),l.set(d,y))),y}function i(u){if(s(u))throw new TypeError;return t===u||r===u||!s(n)&&n.has(u)}function o(u,d,l){if(!i(l))throw new Error("Metadata provider not registered.");var y=a(u,d);if(y!==l){if(!s(y))return!1;var b=f.get(u);s(b)&&(b=new A,f.set(u,b)),b.set(d,l)}return!0}}function $e(){var e;return!s(R)&&h(w.Reflect)&&Object.isExtensible(w.Reflect)&&(e=w.Reflect[R]),s(e)&&(e=Ae()),!s(R)&&h(w.Reflect)&&Object.isExtensible(w.Reflect)&&Object.defineProperty(w.Reflect,R,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function He(e){var t=new W,r={isProviderFor:function(i,o){var u=t.get(i);return s(u)?!1:u.has(o)},OrdinaryDefineOwnMetadata:p,OrdinaryHasOwnMetadata:f,OrdinaryGetOwnMetadata:v,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:a};return H.registerProvider(r),r;function n(i,o,u){var d=t.get(i),l=!1;if(s(d)){if(!u)return;d=new A,t.set(i,d),l=!0}var y=d.get(o);if(s(y)){if(!u)return;if(y=new A,d.set(o,y),!e.setProvider(i,o,r))throw d.delete(o),l&&t.delete(i),new Error("Wrong provider for target.")}return y}function f(i,o,u){var d=n(o,u,!1);return s(d)?!1:re(d.has(i))}function v(i,o,u){var d=n(o,u,!1);if(!s(d))return d.get(i)}function p(i,o,u,d){var l=n(u,d,!0);l.set(i,o)}function c(i,o){var u=[],d=n(i,o,!1);if(s(d))return u;for(var l=d.keys(),y=oe(l),b=0;;){var ce=fe(y);if(!ce)return u.length=b,u;var Ve=ue(ce);try{u[b]=Ve}catch(Be){try{se(y)}finally{throw Be}}b++}}function a(i,o,u){var d=n(o,u,!1);if(s(d)||!d.delete(i))return!1;if(d.size===0){var l=t.get(o);s(l)||(l.delete(u),l.size===0&&t.delete(l))}return!0}}function Fe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,f=e.getOwnMetadataKeys,v=e.deleteMetadata,p=new W,c={isProviderFor:function(a,i){var o=p.get(a);return!s(o)&&o.has(i)?!0:f(a,i).length?(s(o)&&(o=new U,p.set(a,o)),o.add(i),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:f,OrdinaryDeleteMetadata:v};return c}function $(e,t,r){var n=H.getProvider(e,t);if(!s(n))return n;if(r){if(H.setProvider(e,t,q))return q;throw new Error("Illegal state.")}}function Ue(){var e={},t=[],r=(function(){function c(a,i,o){this._index=0,this._keys=a,this._values=i,this._selector=o}return c.prototype["@@iterator"]=function(){return this},c.prototype[E]=function(){return this},c.prototype.next=function(){var a=this._index;if(a>=0&&a<this._keys.length){var i=this._selector(this._keys[a],this._values[a]);return a+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(a){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),a},c.prototype.return=function(a){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:a,done:!0}},c})(),n=(function(){function c(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(a){return this._find(a,!1)>=0},c.prototype.get=function(a){var i=this._find(a,!1);return i>=0?this._values[i]:void 0},c.prototype.set=function(a,i){var o=this._find(a,!0);return this._values[o]=i,this},c.prototype.delete=function(a){var i=this._find(a,!1);if(i>=0){for(var o=this._keys.length,u=i+1;u<o;u++)this._keys[u-1]=this._keys[u],this._values[u-1]=this._values[u];return this._keys.length--,this._values.length--,V(a,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},c.prototype.keys=function(){return new r(this._keys,this._values,f)},c.prototype.values=function(){return new r(this._keys,this._values,v)},c.prototype.entries=function(){return new r(this._keys,this._values,p)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[E]=function(){return this.entries()},c.prototype._find=function(a,i){if(!V(this._cacheKey,a)){this._cacheIndex=-1;for(var o=0;o<this._keys.length;o++)if(V(this._keys[o],a)){this._cacheIndex=o;break}}return this._cacheIndex<0&&i&&(this._cacheIndex=this._keys.length,this._keys.push(a),this._values.push(void 0)),this._cacheIndex},c})();return n;function f(c,a){return c}function v(c,a){return a}function p(c,a){return[c,a]}}function We(){var e=(function(){function t(){this._map=new A}return Object.defineProperty(t.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),t.prototype.has=function(r){return this._map.has(r)},t.prototype.add=function(r){return this._map.set(r,r),this},t.prototype.delete=function(r){return this._map.delete(r)},t.prototype.clear=function(){this._map.clear()},t.prototype.keys=function(){return this._map.keys()},t.prototype.values=function(){return this._map.keys()},t.prototype.entries=function(){return this._map.entries()},t.prototype["@@iterator"]=function(){return this.keys()},t.prototype[E]=function(){return this.keys()},t})();return e}function Ne(){var e=16,t=I.create(),r=n();return(function(){function a(){this._key=n()}return a.prototype.has=function(i){var o=f(i,!1);return o!==void 0?I.has(o,this._key):!1},a.prototype.get=function(i){var o=f(i,!1);return o!==void 0?I.get(o,this._key):void 0},a.prototype.set=function(i,o){var u=f(i,!0);return u[this._key]=o,this},a.prototype.delete=function(i){var o=f(i,!1);return o!==void 0?delete o[this._key]:!1},a.prototype.clear=function(){this._key=n()},a})();function n(){var a;do a="@@WeakMap@@"+c();while(I.has(t,a));return t[a]=!0,a}function f(a,i){if(!O.call(a,r)){if(!i)return;Object.defineProperty(a,r,{value:I.create()})}return a[r]}function v(a,i){for(var o=0;o<i;++o)a[o]=Math.random()*255|0;return a}function p(a){if(typeof Uint8Array=="function"){var i=new Uint8Array(a);return typeof crypto<"u"?crypto.getRandomValues(i):typeof msCrypto<"u"?msCrypto.getRandomValues(i):v(i,a),i}return v(new Array(a),a)}function c(){var a=p(e);a[6]=a[6]&79|64,a[8]=a[8]&191|128;for(var i="",o=0;o<e;++o){var u=a[o];(o===4||o===6||o===8)&&(i+="-"),u<16&&(i+="0"),i+=u.toString(16).toLowerCase()}return i}}function z(e){return e.__=void 0,delete e.__,e}})})(pe||(pe={}))});F();var et=Le(_e(),1);import T from"process";function Ye(){let _=null;return _=le({streams:T,note:M=>{_?.isDead("stderr")!==!0&&de(T.stderr,M)}}),_}async function Je(){Ye();let _=ve(T.env),{server:M,metricsServer:w,edgeIdentityServer:O,closeAll:P,closeWebSockets:x}=ye(_);await new Promise((m,g)=>{M.once("error",g),M.listen(_.port,S,m)}),await new Promise((m,g)=>{w.once("error",g),w.listen(L,S,m)}),await new Promise((m,g)=>{O.once("error",g),O.listen(Z,S,m)}),T.stdout.write(`inference-proxy listening on http://${S}:${_.port}/v1 (metrics http://${S}:${L}${he}, edge identity http://${S}:${Z}, control plane ${_.baseUrl}, org API ${_.apiUrl}, catalog oracle ${_.catalog?"on":"off"})
2
+ import{D as S,E as ve,U as ye,V as we,a as L,b as he,l as Z}from"../chunk-WUNJ3FMI.js";import"../chunk-OPMTYD3Z.js";import"../chunk-K23AZPI4.js";import{x as de,y as le}from"../chunk-55LV3IXW.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{a as ze,b as Le,c as F}from"../chunk-YSFSRI3D.js";var _e=ze(()=>{"use strict";F();var pe;(function(_){(function(M){var w=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:m(),O=P(_);typeof w.Reflect<"u"&&(O=P(w.Reflect,O)),M(O,w),typeof w.Reflect>"u"&&(w.Reflect=_);function P(g,C){return function(I,D){Object.defineProperty(g,I,{configurable:!0,writable:!0,value:D}),C&&C(I,D)}}function x(){try{return Function("return this;")()}catch{}}function E(){try{return(0,eval)("(function() { return this; })()")}catch{}}function m(){return x()||E()}})(function(M,w){var O=Object.prototype.hasOwnProperty,P=typeof Symbol=="function",x=P&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=P&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",m=typeof Object.create=="function",g={__proto__:[]}instanceof Array,C=!m&&!g,I={create:m?function(){return z(Object.create(null))}:g?function(){return z({__proto__:null})}:function(){return z({})},has:C?function(e,t){return O.call(e,t)}:function(e,t){return t in e},get:C?function(e,t){return O.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},D=Object.getPrototypeOf(Function),A=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ue(),U=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:We(),W=typeof WeakMap=="function"?WeakMap:Ne(),R=P?Symbol.for("@reflect-metadata:registry"):void 0,H=$e(),q=He(H);function Me(e,t,r,n){if(s(r)){if(!ne(e))throw new TypeError;if(!ae(t))throw new TypeError;return Se(e,t)}else{if(!ne(e))throw new TypeError;if(!h(t))throw new TypeError;if(!h(n)&&!s(n)&&!G(n))throw new TypeError;return G(n)&&(n=void 0),r=k(r),Re(e,t,r,n)}}M("decorate",Me);function ge(e,t){function r(n,f){if(!h(n))throw new TypeError;if(!s(f)&&!De(f))throw new TypeError;X(e,t,n,f)}return r}M("metadata",ge);function me(e,t,r,n){if(!h(r))throw new TypeError;return s(n)||(n=k(n)),X(e,t,r,n)}M("defineMetadata",me);function Oe(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),Y(e,t,r)}M("hasMetadata",Oe);function be(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),N(e,t,r)}M("hasOwnMetadata",be);function ke(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),J(e,t,r)}M("getMetadata",ke);function Te(e,t,r){if(!h(t))throw new TypeError;return s(r)||(r=k(r)),Q(e,t,r)}M("getOwnMetadata",Te);function Ee(e,t){if(!h(e))throw new TypeError;return s(t)||(t=k(t)),K(e,t)}M("getMetadataKeys",Ee);function Pe(e,t){if(!h(e))throw new TypeError;return s(t)||(t=k(t)),ee(e,t)}M("getOwnMetadataKeys",Pe);function Ie(e,t,r){if(!h(t))throw new TypeError;if(s(r)||(r=k(r)),!h(t))throw new TypeError;s(r)||(r=k(r));var n=$(t,r,!1);return s(n)?!1:n.OrdinaryDeleteMetadata(e,t,r)}M("deleteMetadata",Ie);function Se(e,t){for(var r=e.length-1;r>=0;--r){var n=e[r],f=n(t);if(!s(f)&&!G(f)){if(!ae(f))throw new TypeError;t=f}}return t}function Re(e,t,r,n){for(var f=e.length-1;f>=0;--f){var v=e[f],p=v(t,r,n);if(!s(p)&&!G(p)){if(!h(p))throw new TypeError;n=p}}return n}function Y(e,t,r){var n=N(e,t,r);if(n)return!0;var f=B(t);return G(f)?!1:Y(e,f,r)}function N(e,t,r){var n=$(t,r,!1);return s(n)?!1:re(n.OrdinaryHasOwnMetadata(e,t,r))}function J(e,t,r){var n=N(e,t,r);if(n)return Q(e,t,r);var f=B(t);if(!G(f))return J(e,f,r)}function Q(e,t,r){var n=$(t,r,!1);if(!s(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function X(e,t,r,n){var f=$(r,n,!0);f.OrdinaryDefineOwnMetadata(e,t,r,n)}function K(e,t){var r=ee(e,t),n=B(e);if(n===null)return r;var f=K(n,t);if(f.length<=0)return r;if(r.length<=0)return f;for(var v=new U,p=[],c=0,a=r;c<a.length;c++){var i=a[c],o=v.has(i);o||(v.add(i),p.push(i))}for(var u=0,d=f;u<d.length;u++){var i=d[u],o=v.has(i);o||(v.add(i),p.push(i))}return p}function ee(e,t){var r=$(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function te(e){if(e===null)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return e===null?1:6;default:return 6}}function s(e){return e===void 0}function G(e){return e===null}function Ge(e){return typeof e=="symbol"}function h(e){return typeof e=="object"?e!==null:typeof e=="function"}function je(e,t){switch(te(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var r=t===3?"string":t===5?"number":"default",n=ie(e,x);if(n!==void 0){var f=n.call(e,r);if(h(f))throw new TypeError;return f}return xe(e,r==="default"?"number":r)}function xe(e,t){if(t==="string"){var r=e.toString;if(j(r)){var n=r.call(e);if(!h(n))return n}var f=e.valueOf;if(j(f)){var n=f.call(e);if(!h(n))return n}}else{var f=e.valueOf;if(j(f)){var n=f.call(e);if(!h(n))return n}var v=e.toString;if(j(v)){var n=v.call(e);if(!h(n))return n}}throw new TypeError}function re(e){return!!e}function Ce(e){return""+e}function k(e){var t=je(e,3);return Ge(t)?t:Ce(t)}function ne(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)==="[object Array]"}function j(e){return typeof e=="function"}function ae(e){return typeof e=="function"}function De(e){switch(te(e)){case 3:return!0;case 4:return!0;default:return!1}}function V(e,t){return e===t||e!==e&&t!==t}function ie(e,t){var r=e[t];if(r!=null){if(!j(r))throw new TypeError;return r}}function oe(e){var t=ie(e,E);if(!j(t))throw new TypeError;var r=t.call(e);if(!h(r))throw new TypeError;return r}function ue(e){return e.value}function fe(e){var t=e.next();return t.done?!1:t}function se(e){var t=e.return;t&&t.call(e)}function B(e){var t=Object.getPrototypeOf(e);if(typeof e!="function"||e===D||t!==D)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(n==null||n===Object.prototype)return t;var f=n.constructor;return typeof f!="function"||f===e?t:f}function Ae(){var e;!s(R)&&typeof w.Reflect<"u"&&!(R in w.Reflect)&&typeof w.Reflect.defineMetadata=="function"&&(e=Fe(w.Reflect));var t,r,n,f=new W,v={registerProvider:p,getProvider:a,setProvider:o};return v;function p(u){if(!Object.isExtensible(v))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===u:break;case s(t):t=u;break;case t===u:break;case s(r):r=u;break;case r===u:break;default:n===void 0&&(n=new U),n.add(u);break}}function c(u,d){if(!s(t)){if(t.isProviderFor(u,d))return t;if(!s(r)){if(r.isProviderFor(u,d))return t;if(!s(n))for(var l=oe(n);;){var y=fe(l);if(!y)return;var b=ue(y);if(b.isProviderFor(u,d))return se(l),b}}}if(!s(e)&&e.isProviderFor(u,d))return e}function a(u,d){var l=f.get(u),y;return s(l)||(y=l.get(d)),s(y)&&(y=c(u,d),s(y)||(s(l)&&(l=new A,f.set(u,l)),l.set(d,y))),y}function i(u){if(s(u))throw new TypeError;return t===u||r===u||!s(n)&&n.has(u)}function o(u,d,l){if(!i(l))throw new Error("Metadata provider not registered.");var y=a(u,d);if(y!==l){if(!s(y))return!1;var b=f.get(u);s(b)&&(b=new A,f.set(u,b)),b.set(d,l)}return!0}}function $e(){var e;return!s(R)&&h(w.Reflect)&&Object.isExtensible(w.Reflect)&&(e=w.Reflect[R]),s(e)&&(e=Ae()),!s(R)&&h(w.Reflect)&&Object.isExtensible(w.Reflect)&&Object.defineProperty(w.Reflect,R,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function He(e){var t=new W,r={isProviderFor:function(i,o){var u=t.get(i);return s(u)?!1:u.has(o)},OrdinaryDefineOwnMetadata:p,OrdinaryHasOwnMetadata:f,OrdinaryGetOwnMetadata:v,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:a};return H.registerProvider(r),r;function n(i,o,u){var d=t.get(i),l=!1;if(s(d)){if(!u)return;d=new A,t.set(i,d),l=!0}var y=d.get(o);if(s(y)){if(!u)return;if(y=new A,d.set(o,y),!e.setProvider(i,o,r))throw d.delete(o),l&&t.delete(i),new Error("Wrong provider for target.")}return y}function f(i,o,u){var d=n(o,u,!1);return s(d)?!1:re(d.has(i))}function v(i,o,u){var d=n(o,u,!1);if(!s(d))return d.get(i)}function p(i,o,u,d){var l=n(u,d,!0);l.set(i,o)}function c(i,o){var u=[],d=n(i,o,!1);if(s(d))return u;for(var l=d.keys(),y=oe(l),b=0;;){var ce=fe(y);if(!ce)return u.length=b,u;var Ve=ue(ce);try{u[b]=Ve}catch(Be){try{se(y)}finally{throw Be}}b++}}function a(i,o,u){var d=n(o,u,!1);if(s(d)||!d.delete(i))return!1;if(d.size===0){var l=t.get(o);s(l)||(l.delete(u),l.size===0&&t.delete(l))}return!0}}function Fe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,f=e.getOwnMetadataKeys,v=e.deleteMetadata,p=new W,c={isProviderFor:function(a,i){var o=p.get(a);return!s(o)&&o.has(i)?!0:f(a,i).length?(s(o)&&(o=new U,p.set(a,o)),o.add(i),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:f,OrdinaryDeleteMetadata:v};return c}function $(e,t,r){var n=H.getProvider(e,t);if(!s(n))return n;if(r){if(H.setProvider(e,t,q))return q;throw new Error("Illegal state.")}}function Ue(){var e={},t=[],r=(function(){function c(a,i,o){this._index=0,this._keys=a,this._values=i,this._selector=o}return c.prototype["@@iterator"]=function(){return this},c.prototype[E]=function(){return this},c.prototype.next=function(){var a=this._index;if(a>=0&&a<this._keys.length){var i=this._selector(this._keys[a],this._values[a]);return a+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(a){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),a},c.prototype.return=function(a){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:a,done:!0}},c})(),n=(function(){function c(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(a){return this._find(a,!1)>=0},c.prototype.get=function(a){var i=this._find(a,!1);return i>=0?this._values[i]:void 0},c.prototype.set=function(a,i){var o=this._find(a,!0);return this._values[o]=i,this},c.prototype.delete=function(a){var i=this._find(a,!1);if(i>=0){for(var o=this._keys.length,u=i+1;u<o;u++)this._keys[u-1]=this._keys[u],this._values[u-1]=this._values[u];return this._keys.length--,this._values.length--,V(a,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},c.prototype.keys=function(){return new r(this._keys,this._values,f)},c.prototype.values=function(){return new r(this._keys,this._values,v)},c.prototype.entries=function(){return new r(this._keys,this._values,p)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[E]=function(){return this.entries()},c.prototype._find=function(a,i){if(!V(this._cacheKey,a)){this._cacheIndex=-1;for(var o=0;o<this._keys.length;o++)if(V(this._keys[o],a)){this._cacheIndex=o;break}}return this._cacheIndex<0&&i&&(this._cacheIndex=this._keys.length,this._keys.push(a),this._values.push(void 0)),this._cacheIndex},c})();return n;function f(c,a){return c}function v(c,a){return a}function p(c,a){return[c,a]}}function We(){var e=(function(){function t(){this._map=new A}return Object.defineProperty(t.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),t.prototype.has=function(r){return this._map.has(r)},t.prototype.add=function(r){return this._map.set(r,r),this},t.prototype.delete=function(r){return this._map.delete(r)},t.prototype.clear=function(){this._map.clear()},t.prototype.keys=function(){return this._map.keys()},t.prototype.values=function(){return this._map.keys()},t.prototype.entries=function(){return this._map.entries()},t.prototype["@@iterator"]=function(){return this.keys()},t.prototype[E]=function(){return this.keys()},t})();return e}function Ne(){var e=16,t=I.create(),r=n();return(function(){function a(){this._key=n()}return a.prototype.has=function(i){var o=f(i,!1);return o!==void 0?I.has(o,this._key):!1},a.prototype.get=function(i){var o=f(i,!1);return o!==void 0?I.get(o,this._key):void 0},a.prototype.set=function(i,o){var u=f(i,!0);return u[this._key]=o,this},a.prototype.delete=function(i){var o=f(i,!1);return o!==void 0?delete o[this._key]:!1},a.prototype.clear=function(){this._key=n()},a})();function n(){var a;do a="@@WeakMap@@"+c();while(I.has(t,a));return t[a]=!0,a}function f(a,i){if(!O.call(a,r)){if(!i)return;Object.defineProperty(a,r,{value:I.create()})}return a[r]}function v(a,i){for(var o=0;o<i;++o)a[o]=Math.random()*255|0;return a}function p(a){if(typeof Uint8Array=="function"){var i=new Uint8Array(a);return typeof crypto<"u"?crypto.getRandomValues(i):typeof msCrypto<"u"?msCrypto.getRandomValues(i):v(i,a),i}return v(new Array(a),a)}function c(){var a=p(e);a[6]=a[6]&79|64,a[8]=a[8]&191|128;for(var i="",o=0;o<e;++o){var u=a[o];(o===4||o===6||o===8)&&(i+="-"),u<16&&(i+="0"),i+=u.toString(16).toLowerCase()}return i}}function z(e){return e.__=void 0,delete e.__,e}})})(pe||(pe={}))});F();var et=Le(_e(),1);import T from"process";function Ye(){let _=null;return _=le({streams:T,note:M=>{_?.isDead("stderr")!==!0&&de(T.stderr,M)}}),_}async function Je(){Ye();let _=ve(T.env),{server:M,metricsServer:w,edgeIdentityServer:O,closeAll:P,closeWebSockets:x}=ye(_);await new Promise((m,g)=>{M.once("error",g),M.listen(_.port,S,m)}),await new Promise((m,g)=>{w.once("error",g),w.listen(L,S,m)}),await new Promise((m,g)=>{O.once("error",g),O.listen(Z,S,m)}),T.stdout.write(`inference-proxy listening on http://${S}:${_.port}/v1 (metrics http://${S}:${L}${he}, edge identity http://${S}:${Z}, control plane ${_.baseUrl}, org API ${_.apiUrl}, catalog oracle ${_.catalog?"on":"off"})
3
3
  `);let E=async m=>{T.stdout.write(`inference-proxy: ${m} \u2014 draining
4
4
  `),await we(M,P,x),await new Promise(g=>w.close(()=>g())),await new Promise(g=>O.close(()=>g()))};await new Promise(m=>{T.once("SIGINT",()=>{E("SIGINT").finally(m)}),T.once("SIGTERM",()=>{E("SIGTERM").finally(m)})})}Je().then(()=>T.exit(0),_=>{T.stderr.write(`inference-proxy: ${String(_ instanceof Error?_.stack??_.message:_)}
5
5
  `),T.exit(1)});
@@ -1 +1 @@
1
- import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-LCW3OUIV.js";import"../chunk-7E2KNW2C.js";import"../chunk-K23AZPI4.js";import"../chunk-RUJPI6BV.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
1
+ import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-WUNJ3FMI.js";import"../chunk-OPMTYD3Z.js";import"../chunk-K23AZPI4.js";import"../chunk-55LV3IXW.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
@@ -172,7 +172,7 @@ self.onrtctransform = (event) => {
172
172
  }
173
173
  `;function wH(t){let e=t.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return t;let r="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",s=!1,n=t.split(`\r
174
174
  `).map(i=>i.startsWith(`a=fmtp:${e} `)&&!i.includes("usedtx=")?(s=!0,`${i};${r}`):i);if(!s){let i=n.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);i>=0&&n.splice(i+1,0,`a=fmtp:${e} ${r}`)}return n.join(`\r
175
- `)}var Rie=class{constructor(t){this.sink=t}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(t){this.deadCb=t}setSource(t){if(this.stopped||t!==null&&t===this.currentTrack&&t.readyState==="live")return;let e=null;if(!(t!==null&&(e=Pie(t)?this.bridgedTrack(t):t,!e))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(e)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=e,e&&this.wireTrackLiveness(e);return}e!==null&&this.engage(e)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(t){let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof e.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(i){this.die(`transform worker: ${i instanceof Error?i.message:String(i)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(t);this.sender=s,this.currentTrack=t,this.wireTrackLiveness(t);let n=e.RTCRtpScriptTransform;if(s.transform=new n(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(i=>this.die(`loopback renegotiate: ${i instanceof Error?i.message:String(i)}`));return}this.negotiate().catch(i=>this.die(`loopback negotiate: ${i instanceof Error?i.message:String(i)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let e=t.RTCPeerConnection;this.sendPc=new e({iceServers:[]}),this.recvPc=new e({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(t){if(!this.stopped){if(t===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(t);else try{this.renderSender.replaceTrack(t)}catch(e){this.die(`render replaceTrack: ${e instanceof Error?e.message:String(e)}`);return}this.wireRenderRemote(t),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(e=>this.die(`loopback negotiate: ${e instanceof Error?e.message:String(e)}`))}}}onRenderTrack(t){this.renderRemoteCb=t}renderMidOf(){if(!this.renderSender)return null;let t=this.sendPc;try{return t.getTransceivers?.().find(e=>e.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(t){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},t.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let t=this.sendPc,e=this.recvPc;if(!(!t||!e||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await t.createOffer();r.sdp=wH(r.sdp??""),await t.setLocalDescription(r),await e.setRemoteDescription(t.localDescription??{type:"offer",sdp:r.sdp});let s=await e.createAnswer();s.sdp=wH(s.sdp??""),await e.setLocalDescription(s),await t.setRemoteDescription(e.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let t=this.candQueue;if(t){for(;t.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(t.toSend.shift())).catch(()=>{});for(;t.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(t.toRecv.shift())).catch(()=>{})}}bridgedTrack(t){let e=t;try{let r=e.context.createMediaStreamDestination();e.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:e,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(t){this.endedListener=()=>this.die("mic track ended"),t.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Iie],{type:"text/javascript"}));let t=new Worker(this.workerUrl);return t.onmessage=e=>{let r=e.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},t.onerror=e=>this.die(`transform worker: ${e.message||"error"}`),this.worker=t,t}onEncodedFrame(t,e){if(this.stopped)return;let r=zH(this.frameSeq,t,e,this.sink.maxDatagramSize()||eR);if(r===null){S.warn(`[urun] WT mic uplink: frame of ${e.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}die(t){this.stopped||(S.warn(`[urun] WT mic uplink lane dead (${t}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(t))}};function Pie(t){let e=t;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Bie=9e4,Die="avc1.42E01F",Lie=60,Oie=3,Nie=1e4;function Uie(t){return Math.round(t*(Bie/1e6))%2**32>>>0}var Mie=class{constructor(t){this.sink=t}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(t){this.deadCb=t}requestKeyframe(){this.keyframeWanted=!0}setSource(t){if(this.stopped||(this.teardownCapture(),t===null))return;let e=globalThis.MediaStreamTrackProcessor;if(typeof e!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new e({track:t}).readable.getReader(),n=!1;this.cancelCapture=()=>{n=!0,s.cancel().catch(()=>{})},(async()=>{for(;!n&&!this.stopped&&r===this.generation;){let{value:i,done:o}=await s.read();if(o)break;if(i){if(n||this.stopped||r!==this.generation){i.close();break}this.encodeFrame(i)}}})().catch(i=>{!n&&!this.stopped&&r===this.generation&&this.die(`capture: ${i instanceof Error?i.message:String(i)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(t){let e={width:t.codedWidth,height:t.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==e.width||this.encoderDims.height!==e.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){t.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)})),this.encoderDims=e,this.encoder.configure({codec:Die,avc:{format:"annexb"},width:e.width,height:e.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(n){t.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=Lie;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(t,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}t.close()}sendFrame(t){if(this.stopped)return;let e=new Uint8Array(t.byteLength);t.copyTo(e);let r=zH(this.frameSeq,Uie(t.timestamp),e,this.sink.maxDatagramSize()||eR,{lane:wie,keyframe:t.type==="key"});if(r===null){S.warn(`[urun] WT video uplink: AU of ${e.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(t){if(this.stopped)return;let e=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>e-r<Nie),this.encoderErrorsAt.push(e),this.encoderErrorsAt.length>=Oie){this.die(`video encoder: ${t.message}`);return}S.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",t.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(t){this.stopped||(S.warn(`[urun] WT video uplink lane dead (${t}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(t))}};function jie(t){return t.byteLength>=2&&t[0]===1&&t[1]===3}var $ie=class{constructor(t){this.transport=t}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(t){this.deadCb=t}send(t,e){let r=new TextEncoder().encode(t);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let n=this.streams.get(t);if(!n){let o=await this.transport.openUniStream(),a=new Uint8Array(2+r.byteLength);a[0]=1,a[1]=r.byteLength,a.set(r,2),await o.write(a),n={writer:o},this.streams.set(t,n)}let i=new Uint8Array(4+e.byteLength);new DataView(i.buffer).setUint32(0,e.byteLength,!0),i.set(e,4),await n.writer.write(i),jie(e)&&(this.streams.delete(t),await n.writer.close().catch(()=>{}))}catch(n){throw this.die(n instanceof Error?n.message:String(n)),n}});return this.chain=s.catch(()=>{}),s}stop(t="stopped"){if(this.dead===null){this.dead=t;for(let e of this.streams.values())e.writer.close().catch(()=>{});this.streams.clear()}}die(t){this.dead===null&&(S.warn(`[urun] WT data uplink lane dead (${t})`),this.stop(t),this.deadCb?.(t))}},vH=250,Fie=25,Hie=2e3,qie=15e3,Vie=1e3,zie=45e3,Wie=5e3,Kie={llm:!0},Gie=500,_H=10,Xie=2,Yie=2,gI=2,tR=class Al{constructor(e,r,s,n,i,o,a){this.offer=e,this.sessionId=r,this.canvas=s,this.audioLane=n,this.audioUplink=i,this.videoUplink=o,this.dataUplink=a,this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new YI({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let r=this.offer.codec,s=r!==void 0&&r!=="";this.hasVideoLane=s,s&&bH(r,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(u=>({algorithm:"sha-256",value:Uint8Array.from(atob(u),l=>l.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=n.readable.getReader(),o=new GI,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,S.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),s&&(bH(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let u={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},l=new Aie(this.offer.audio,{...this.audioLane,renderHop:u});try{l.start(),this.audioPlayout=l}catch(h){S.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),l.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let u=this.wt.createUnidirectionalStream?.bind(this.wt);if(!u)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new $ie({openUniStream:async()=>(await u()).getWriter()});l.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h,l)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(u){let l=u instanceof Error?u.message:String(u);S.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(i,o,a).catch(u=>this.die(`control loop: ${u}`)),this.datagramLoop().catch(u=>this.die(`datagram loop: ${u}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Gie)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(u=>{this.closedReason=`connection error: ${u}`,this.die(`connection error: ${u}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${vH}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??qie},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Vie))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let r=typeof e.ds=="number"?e.ds:null,s=typeof e.ur=="number"?e.ur:null;if(r===null&&s===null)return;this.gatewayExposesCounters=!0;let n=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:r,ur:s,recvDownlink:n,sentUplink:i},!o)return;let a=r!==null&&o.ds!==null?r-o.ds:null,c=s!==null&&o.ur!==null?s-o.ur:null,d=n-o.recvDownlink,u=i-o.sentUplink,l="none";if(a!==null&&a>=_H&&d<=0?l="downlink":c!==null&&u>=_H&&c<=0&&(l="uplink"),l==="none"){this.severedStreak="none",this.observePlayoutProgress(d,r);return}if(this.severedStreak!==l){this.severedStreak=l;return}this.severedStreak="none";let h=l==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${u} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${r} ur=${s}, client received=${n} accepted=${i}, confirmed on ${Xie} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,r){let s=this.audioPlayout;if(!s){this.playoutScheduledSeen=null;return}let n=s.playoutProgress(),i=n.surfaced;if(this.playoutScheduledSeen!==null&&n.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=n.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=n.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Yie)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,S.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{s.rebuildSurface()}catch(o){S.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=gI}return}this.playoutStallStreak<gI||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled} on ${gI} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let r=this.pathLiveness();if(!r.alive)return;let s=performance.now(),n=this.audioLaneLastArrivalAt===null?null:s-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:s-this.lastInboundControlAt,o=n===null&&i===null?!0:(n===null||n>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:s-this.lastInboundDataAt,u=n!==null?n:this.firstInboundDataAt===null?null:s-this.firstInboundDataAt,l=u!==null&&u>=e.stallMs;if(c&&l&&d!==null&&d<=Wie&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((u??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${r.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=zie&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let r=this.dataUplinkSender;r&&(this.dataUplinkSender=null,r.stop(e),this.dataUplink?.onUplinkLost(e,r))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let r={onData:(s,n)=>{if(Kie[s]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(s,n)},onLaneError:s=>e.onLaneError(s)};this.dataLaneSink=r,ZI(this.wt.incomingUnidirectionalStreams,r).catch(s=>{this.die(`data lane: ${s instanceof Error?s.message:String(s)}`)})}initDecoder(e,r,s){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:r,height:s};let o=new n({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...r>0&&s>0?{codedWidth:r,codedHeight:s}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;S.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(r.codec,r.width,r.height),this.decoderErrorLogged=!1}catch(s){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${s instanceof Error?s.message:String(s)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,r){this.stopped||this.deadFired||this.datagramWriter().write(e).then(r,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let r=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,S.error(`[urun] WT uplink datagram send FAILED (${r}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let s=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(n=>s-n<Hie),this.uplinkSendErrorsAt.push(s),!(this.uplinkSendErrorsAt.length<Fie)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${r}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let r=0;return{send:s=>this.uplinkSend(s,()=>{r++}),delivered:()=>r,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??eR}}engageAudioUplink(){let e=new Rie(this.uplinkSink("audio"));e.onDead(r=>this.onUplinkLaneDead("audio",r,e)),e.onRenderTrack?.(r=>this.renderRemoteCb?.(r)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new Mie(this.uplinkSink("video"));e.onDead(r=>this.onUplinkLaneDead("video",r,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let r=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(s){let n=s instanceof Error?s.message:String(s);S.warn(`[urun] WT ${r} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${r} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}freshLaneBuilt(e){let r={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),r}onUplinkLaneDead(e,r,s){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=i?.builtAt!=null&&Date.now()-i.builtAt>=Al.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(o>Al.UPLINK_LANE_RETRY_MAX){S.error(`[urun] WT ${n} uplink lane dead (${r}) \u2014 ${Al.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${Al.UPLINK_LANE_RETRY_MAX} recovery attempts: ${r}`,s);return}S.warn(`[urun] WT ${n} uplink lane dead (${r}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${Al.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},Al.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,r,s){e==="audio"?this.audioUplink.onUplinkLost(r,s):this.videoUplink.onUplinkLost(r,s)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:r,done:s}=await e.read();if(s)break;if(!r)continue;if(r.byteLength>=ei&&r[11]===VH){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(r);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let i=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(r)}}decodeFrame(e,r,s){let n=globalThis.EncodedVideoChunk;if(typeof n=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new n({type:r?"key":"delta",timestamp:e*(1e6/24),data:s})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(KI(e)),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async sendControlRaw(e){try{let r=new Uint8Array(4+e.byteLength);new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),await this.writer.write(r),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async readControl(e,r,s=[]){for(;;){let n=s.shift();if(n)return n;let{value:i,done:o}=await e.read();if(o)return null;i&&s.push(...r.push(i))}}async controlLoop(e,r,s){for(;!this.stopped;){let n=await this.readControl(e,r,s);if(!n)break;let i=n;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(yie(n.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let r=performance.now(),s=(r-e)/1e3;e=r;let n=this.reassembler.drainWindow(),i=n.delivered+n.abandoned;this.lastStats={recvBps:s>0?n.bytes*8/s:0,lossPct:i>0?100*n.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},vH)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}},SH=2500,EH=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Jie=1e4,rR=class vc{constructor(e,r,s){this.signaling=e,this.sessionId=r,this.opts=s}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let r=this.session;!r||r.kind!=="webtransport"||r.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let r=typeof e.WebTransport=="function",s=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,i={webtransport:r&&s&&n,webcodecs:s,codecs:EH,wtData:r&&s&&n&&this.opts.dataLane!==void 0,wtAudio:r&&s&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:r&&n&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:r&&s&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:r&&s&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&S.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await bI(d.start(),this.opts.quicDeadlineMs??SH,"quic connect deadline"),this.wtDialedHost=yI(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(u){if(S.warn(`[urun] WT dial failed (${av(u)}) \u2014 dialed ${CH(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(u instanceof Error?u.message:u);throw S.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),u}S.warn("[urun] webtransport failed, falling back to webrtc:",u),this.proceedWebRtcDial(`wt failed: ${String(u instanceof Error?u.message:u)}`),this.notifyEstablished("webrtc",String(u instanceof Error?u.message:u))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw S.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=yI(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,S.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Qie(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,n=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",i=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",o=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:EH,wtData:s,wtAudio:n,wtAudioUp:i,wtVideoUp:o,wtDataUp:a}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let c=this.createWebTransportSession();try{await bI(c.start(),this.opts.quicDeadlineMs??SH,"quic connect deadline")}catch(d){throw S.warn(`[urun] WT dial failed (${av(d)}) \u2014 dialed ${CH(this.offer.webtransport?.url)}`),c.stop().catch(()=>{}),d}if(this.wtDialedHost=yI(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,s)}catch(d){throw c.stop().catch(()=>{}),d}if(this.disconnected)return c.stop().catch(()=>{}),null;this.session=c;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),c}engageQuicDataLane(e,r){if(!r||this.offer?.webtransport?.data!==!0)return;let s=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,i)=>s.onData(n,i),onLaneError:n=>s.onLaneError(n)}),s.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new tR(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(r=>{S.error("[urun] webrtc path died:",r)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(r=>{if(this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT-REQUIRED leg died mid-session (${r}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(r,!0);return}let s=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),s){this.session=null,this.wtOnlyLeg=!1,S.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",r),this.redialWtAfterDeath(r,!0);return}S.warn("[urun] quic died mid-session, failing over to webrtc:",r),this.lateWebRtcFailover(e,r,s)})}redialWtAfterDeath(e,r=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=vc.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT re-dial failed ${vc.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}S.error(`[urun] WT re-dial failed ${vc.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let s=this.wtRedialFailures+1,n=WH(vc.WT_REDIAL_BASE_MS,s,vc.WT_REDIAL_CAP_MS,s===1&&r?0:void 0);S.warn(`[urun] WT re-dial attempt ${s} scheduled in ${Math.round(n)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},n)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){S.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${vc.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(r){let s=av(r);S.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${vc.WT_REDIAL_MAX} failed (${s}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${s}`)}}}lateWebRtcFailover(e,r,s){this.disconnected||(async()=>{let n=this.createWebRtc();try{let i=await bI(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Jie,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${r}`),this.opts.onTransportChange?.("webrtc",r)}catch(i){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=s?`media transport lost \u2014 the WebTransport connection dropped (${r}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${r}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;S.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,r){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:r})}};function av(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"){try{let e=JSON.stringify(t);if(e!==void 0&&e!=="{}")return e}catch{}return t.constructor?.name??Object.prototype.toString.call(t).slice(8,-1)}return String(t)}function yI(t){if(t)try{return new URL(t).host}catch{return}}function CH(t){if(!t)return"(no offer url)";try{let e=new URL(t);return e.searchParams.delete("token"),e.toString()}catch{return t.replace(/[?&]token=[^&\s]*/g,"")}}function Qie(t){if(!t)return!1;let e=t.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function WH(t,e,r,s){if(s!==void 0)return s;let n=Math.min(t*2**Math.max(0,e-2),r);return Math.round(n*(.75+Math.random()*.5))}function bI(t,e,r){return new Promise((s,n)=>{let i=setTimeout(()=>n(new Error(r)),e);t.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),n(o)})})}var Zie=1e4,sR=class{constructor(t,e=Zie){this.carrier=t,this.requestTimeoutMs=e}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(t,e){let r=ev();return new Promise((s,n)=>{let i=setTimeout(()=>{o(),n(new Error(`[urun] signaling request timed out: ${t}`))},this.requestTimeoutMs),o=this.carrier.onSignal(a=>{if(a.type!==`${t}.response`||a.requestId!==r)return;if(clearTimeout(i),o(),a.error){n(new Error(`[urun] ${t} failed: ${String(a.error)}`));return}let{type:c,requestId:d,...u}=a;s(u)});this.carrier.sendSignal({type:t,requestId:r,...e})||(clearTimeout(i),o(),n(new Error(`[urun] signaling request not sent: ${t} \u2014 the signaling socket is not open`)))})}notify(t,e){this.carrier.sendSignal({type:t,...e})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${t} \u2014 the signaling socket is not open`,detail:{method:t}})}on(t,e){return this.carrier.onSignal(r=>{r.type===t&&e(r)})}},eoe="video",nR=class{constructor(t,e=eoe){this.transport=t,this.streamName=e,this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let e=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(e(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(e)})}async stop(){for(let t of this.unsubscribers.splice(0))t()}onDead(t){this.deadCb=t}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(t){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(t)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(t))}};function toe(t){let e=t;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var roe="video",soe=45e3;async function noe(t,e,r){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let n=e,i=r.runtimeWaitCapMs??soe;return new Promise(o=>{let a=!1,c,d=null,u=null,l=!1,h=_=>{a||(a=!0,m(),u!==null&&(clearTimeout(u),u=null),c?.(),o(_))};u=setTimeout(()=>{if(l||a||r.isDisposed())return;l=!0;let _=n.current();t.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${r.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let p=()=>{d===null&&!a&&(d=setTimeout(()=>h("unconfirmed"),i))},m=()=>{d!==null&&(clearTimeout(d),d=null)};c=e.subscribe(_=>{let f=_?.name;if(f==="live")return h("live");if(f==="error")return h("gone");m(),xc(f)||p()}),xc(s)||p()})}function ioe(t,e,r){let s=globalThis,n=s.document;if(!(typeof n?.createElement=="function"&&typeof s.WebTransport=="function"&&typeof s.VideoDecoder=="function")||r.allowWebTransport===!1)return null;let i=t.holdWebRtcDial?.(),o=n.createElement("canvas"),a=!1,c=null,d=!1,u=()=>{if(c){for(let k of c.getVideoTracks())try{k.stop()}catch{}c=null}d&&(d=!1,r.onOverrideTrack(null))},l=new rR(new sR(t),e,{canvas:o,createWebRtcSession:r.createWebRtcSession??(()=>new nR(t,r.streamName??roe)),createWebTransportSession:r.createWebTransportSession,dataLane:{onData:(k,C)=>t.dispatchQuicStreamData(k,C),onQuicLane:()=>t.markStreamDataLaneQuic(),onQuicLaneLost:k=>t.quicStreamDataLaneLost(k),onLaneError:k=>t.raiseQuicStreamDataError(k)},audioLane:r.onOverrideAudioTrack?{jitterBufferTargetMs:r.audioPlayout?.jitterBufferTargetMs,ctx:r.audioPlayout?.audioContext,onTrack:k=>{a||(k&&t.noteQuicMediaFlowing?.(),r.onOverrideAudioTrack(k))}}:void 0,audioUplink:r.audioUplink,videoUplink:r.videoUplink,dataUplink:r.dataUplink,webRtcDial:i,allowWebRtcFallback:r.allowWebRtcFallback,onWtRequiredOutage:()=>E(),onMediaTransportLost:k=>{a||(u(),r.onOverrideAudioTrack?.(null),r.onMediaTransportLost?.(k),E())},onTransportChange:(k,C)=>{a||(k==="webrtc"&&(u(),E()),r.onTransportChange?.(k,C))}}),h=t.onWtOnlyLegDeath?.(k=>l.failCurrentWtLeg(k)),p=null,m=()=>{p!==null&&(clearInterval(p),p=null)},_=r.wtRetryBaseMs??2e3,f=r.wtRetryCapMs??3e4,b=null,w=0,E=()=>{if(a||b!==null||l.activeTransport==="webtransport")return;let k=WH(_,w+2,f);b=setTimeout(()=>{b=null,w+=1,l.retryWebTransport().then(C=>{if(a){C&&l.disconnect().catch(()=>{});return}if(C)return S.debug(`[urun] webtransport upgraded in background (retry ${w})`),w=0,q(C);E()}).catch(C=>{a||(S.debug(`[urun] webtransport background retry ${w} failed: `+av(C)),E())})},k)},O=()=>{b!==null&&(clearTimeout(b),b=null)},q=async k=>{if(a||k.kind!=="webtransport")return;let C=r.pathHealthProbeMs??1e4;m();let I=!1;p=setInterval(()=>{if(a||l.activeTransport!=="webtransport")return;let W=toe(k);if(!W){S.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),m();return}let J=W.pathLiveness();if(!J.alive){let F=l.isWtOnlyLeg;S.error(`[urun] webtransport path is DEAD: ${J.evidence}`+(F?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),m(),W.fail(`path health: ${J.evidence}`);return}if(!I){if(I=!0,l.isWtOnlyLeg){S.warn(`[urun] webtransport established, no application media yet after ${C}ms \u2014 the QUIC PATH IS HEALTHY (${J.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}S.warn(`[urun] webtransport established but no QUIC media after ${C}ms \u2014 no media datagrams reached this client (path healthy: ${J.evidence}); webrtc track remains authoritative`)}},C);try{await k.firstMedia}catch(W){m(),S.debug("[urun] webtransport ended before any media flowed:",W);return}if(m(),a||l.activeTransport!=="webtransport"||typeof o.captureStream!="function")return;c=o.captureStream();let H=c.getVideoTracks()[0];H&&(d=!0,r.onOverrideTrack(H))},R=!1;return(async()=>{let k=await noe(t,r.runtimePhase,{sessionId:e,runtimeWaitCapMs:r.runtimeWaitCapMs,isDisposed:()=>a});if(a)return;if(k==="gone"){S.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),i?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}R=!0;let C=await l.connect();if(a){l.disconnect().catch(()=>{});return}await q(C)})().catch(k=>{if(m(),a){S.debug("[urun] transport negotiation aborted: session disposed mid-dial:",k);return}if(r.allowWebRtcFallback===!1){S.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",k),E();return}i?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),S.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),E()}),{activeTransport:()=>l.activeTransport,mediaTransportAttempted:()=>R,watchDownlinkStall(k){l.watchDownlinkStall(k)},dispose(){a=!0,h?.(),m(),O(),u(),r.onOverrideAudioTrack?.(null),l.disconnect().catch(()=>{})}}}var ooe=new Set;function KH(t){if(t.functionsUrl)return{functionsUrl:t.functionsUrl,orgId:t.orgId,apiKey:t.apiKey,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}var aoe="rpc",coe="$presence",iR=3e4,TH=3e4,doe="rpc-resp";function loe(t){return`${doe}:${t}`}function xI(){return ev()}function uoe(t){if(t&&typeof t=="object"){let e=t.error;if(e&&typeof e=="object"){let{message:r,code:s}=e;return{message:typeof r=="string"?r:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof t=="string"?t:JSON.stringify(t)}}function hoe(t,e,r,s,n,i,o,a,c,d){let u=[],l=null,h=!1,p=null,m=!1,_,f,b=new Promise((z,se)=>{_=z,f=se});b.catch(()=>{});let w=o(),E=null,O=null,q=null,R=null,k=null,C=null,I=!0,H=()=>{q&&(clearTimeout(q),q=null),R&&(R(),R=null)},W=()=>{k&&(clearTimeout(k),k=null),C&&(C(),C=null)},J=!1,F=()=>{J||!m||(J=!0,t.set({rpc:{[e]:null}}))},V=()=>{I=!1,H(),W(),E?.(),E=null,O?.(),O=null,a?.removeEventListener("abort",P),w.dispose(),F()},Q=()=>{if(l){if(u.length>0){let z=l;l=null,z.resolve({value:u.shift(),done:!1})}else if(p!==null){let z=l;l=null,z.reject(p)}else if(h){let z=l;l=null,z.resolve({value:void 0,done:!0})}}},B=z=>{h||(u.push(z),Q())},X=z=>{h||(p=z,h=!0,f(z),V(),Q())},Z=z=>{h||(h=!0,_(z),V(),Q())},P=()=>{let z=a?.reason;X(z instanceof ta?z:new wg(e))},M=z=>{if(!(h||!z||typeof z!="object"))switch(W(),F(),z.t){case"delta":typeof z.delta=="string"&&B(z.delta);break;case"response":Z(z.body);break;case"error":{let{message:se,code:de}=uoe(z.body);X(new ta(se,{requestId:e,code:z.code??de}));break}}},Y=()=>{let z=w.messages()[Symbol.asyncIterator]();E=()=>{z.return?.(void 0)};let se=()=>{I&&z.next().then(de=>{if(I){if(de.done){h||Z(void 0);return}M(de.value),se()}},de=>{I&&X(de)})};se()},j=()=>{if(!m){if(m=!0,a){if(a.aborted){X(new wg(e));return}a.addEventListener("abort",P,{once:!0})}O=c?.(z=>X(z))??null,Y(),t.set({rpc:{[e]:{args:r,respond_on:s,consumer_id:n,stream:i}}}),d&&d>0&&!t.synced&&(q=setTimeout(()=>{q=null,!h&&!t.synced&&X(new H1(d,e))},d),R=t.onSynced(()=>H())),C=t.onSynced(()=>{C=null,!(h||J||k)&&(k=setTimeout(()=>{k=null,!(h||J)&&S.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(TH/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},TH))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(j(),u.length>0)return Promise.resolve({value:u.shift(),done:!1});if(p!==null){let z=p;return p=null,Promise.reject(z)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((z,se)=>{l={resolve:z,reject:se}})},return(){return h||(h=!0,_(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(z){return h||(h=!0,f(z),V()),Promise.reject(z)}}}},body:b,start:j}}function kH(t){if(t&&typeof t=="object"){let{epoch:e,by:r}=t,s={epoch:typeof e=="number"?e:0};return(r==="runtime"||r==="browser")&&(s.by=r),s}}function foe(t,e){let r=t.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:n,br:i}=r,o={};(s==="audio"||s==="video"||s==="data")&&(o.kind=s);let a=kH(n);a&&(o.rt=a);let c=kH(i);return c&&(o.br=c),o}var poe=class{constructor(t,e,r,s,n){this._name=t,this._transport=e,this._streamData=r,this._controlDoc=s,this._onActivity=n,this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let t=this;return{[Symbol.asyncIterator](){let e=[...t._replay],r=null,s=!1,n=null,i={push(a){if(!s)if(r){let c=r;r=null,c.resolve({value:a,done:!1})}else e.push(a)},end(){if(s=!0,r){let a=r;r=null,a.resolve({value:void 0,done:!0})}}};t._messageConsumers.add(i);let o=()=>{s=!0,t._messageConsumers.delete(i)};return t._transport.mediaAvailability().then(a=>{if(!(a===null||s)&&(n=t._streamConsumeUnavailableError(a),o(),r)){let c=r;r=null,c.reject(n)}}),{next(){return e.length>0?Promise.resolve({value:e.shift(),done:!1}):n?Promise.reject(n):s?Promise.resolve({value:void 0,done:!0}):new Promise((a,c)=>{r={resolve:a,reject:c}})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let t=this._transport.mediaUnavailableReason();if(t)throw this._streamConsumeUnavailableError(t)}_streamConsumeUnavailableError(t){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${t}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,t=>this._deliver(t))))}_deliver(t){this._replay.push(t);for(let e of this._messageConsumers)e.push(t)}get track(){let t=this._transport.getTrackByName(this._name)??this._track;return t!==this._track&&this._setTrack(t),this._overrideTrack??this._track}_setOverrideTrack(t){if(this._overrideTrack===t)return;this._overrideTrack=t,t&&t.addEventListener?.("ended",()=>{this._overrideTrack===t&&this._setOverrideTrack(null)},{once:!0});let e=t??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(e)}_claimBrowserProducer(t){if(!this._controlDoc)return;let e=this._controlDoc(),r=foe(e,this._name),s=r?.br;if(s?.by==="runtime")throw new q1(this._name,"runtime","browser");if(s)return;let n={br:{epoch:1}};r?.rt&&(n.rt=r.rt);let i=r?.kind??t;i&&(n.kind=i),e.set({streams:{[this._name]:n}})}async attach(t){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(t,this._name)}async attachVideo(t){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(t,this._name)}async emit(t,e={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,t,e)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(t){if(t!=="live"&&(!Number.isFinite(t)||t<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,t)}chunks(t={}){let e=t.source??zI;return gie(e,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(t){return this._transport.on("seeked",(e,r)=>{e===this._name&&t(r)})}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let t of this._messageConsumers)t.end();this._messageConsumers.clear()}_setTrack(t){if(this._track=t,t&&t.addEventListener("ended",()=>{this._track===t&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let e=this._handlers.get("track");if(e)for(let r of e)r(t)}},oR=class GH{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new tH;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,r,s,n,i,o){this._sessionId=e,this._multiplexer=r,this._transport=s,this._recordingsAuth=n,this._artifactsAuth=i,this._streamData=XF(s),this._wireControlDocIncarnation(),this._lifecycleUnsub=HI(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=MI({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new FI({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(coe).awareness.setLocalState({role:"client"}),this._activation=new AI({onPhase:a=>this.onPhase(a),hint:()=>this.doc(EI).get(CI)??this.doc("control").get(TI),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",r=>{this._transport.applyControlDocState(r)})}static async attach(e,r){let s=await qF({baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,sessionId:e,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}),n=r.getAccessToken?await r.getAccessToken()??void 0:r.jwt,i=new JA,o=new aI({url:s.wsUrl,orgId:r.orgId,jwt:n,authProvider:r.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new GH(e,i,o,KH(r),vI({...r,baseUrl:s.baseUrl}),{activity:r.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),o.setEndsAt(s.endsAt),Qh()&&await K1();let c=r.getAccessToken,d=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:s.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return W1(this,e)}on(e,r){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(r),this._generationTickStop||(this._generationTickStop=OI(this.doc("control"),s=>{for(let n of Array.from(this._generationTickHandlers))try{n(s)}catch(i){S.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(r),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let r=new uv(e);return this._recordingsAccessor={list:s=>r.list(s??this._sessionId),get:s=>r.get(s),retain:(s,n)=>r.retain(s,n),pin:s=>r.pin(s),unpin:s=>r.unpin(s),permanent:s=>r.permanent(s),delete:s=>r.delete(s)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Rg(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,r)=>new Rg(this._requireArtifactsAuth()).getDownloadUrl(e,r??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e!==this._sessionId){this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let r=this._streams.get(e);return r||(r=new poe(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,r),this._activation.watch(e,r)),r}doc(e){let r=this._docs.get(e);return r||(r=new sH(e,this._sessionId,ooe.has(e)?null:this._docConnector.connect),this._docs.set(e,r)),r}get presence(){return this._presence||(this._presence=nH(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let r=cI(e.wsUrl),s=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${r}\0${s}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(eH({serverUrl:r,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,r={}){let s=xI(),n=new AbortController;r.signal&&(r.signal.aborted?n.abort(r.signal.reason):r.signal.addEventListener("abort",()=>n.abort(r.signal.reason),{once:!0}));let i=null;if(typeof r.timeout=="number"&&r.timeout>=0){let c=r.timeout;i=setTimeout(()=>n.abort(new F1(c,s)),c)}let o=this._consumeResponse(s,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,r,s,n,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(aoe),a=loe(e);return hoe(o,e,r,a,this._streamData.consumerId,s,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??iR)}requestStream(e,r={}){let s=xI();return this._consumeResponse(s,e,!0,r.signal,r.docSyncTimeout).deltas}complete(e,r={}){let s=xI(),n=this._consumeResponse(s,e,!1,r.signal,r.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(r){S.warn("[urun] session recovery hook failed:",r)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=ioe(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:r=>this._transport.on("phase",r)},onOverrideTrack:r=>this.stream("video")._setOverrideTrack(r),onOverrideAudioTrack:r=>this.stream("audio")._setOverrideTrack(r),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new El)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new El);let e=this._cancelHandler().then(r=>(this.disconnect(),r));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let r=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let n of r)try{n()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let s=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of s)try{n(new V1)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function moe(t){return`urun:session:v2:${t.orgId}:${t.app}:${t.functionName}`}function aR(){try{return globalThis.sessionStorage??null}catch{return null}}var cR=new Map;function SI(t){if(!t)return;let e=t.split(".");if(!(e.length<2))try{let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r+"=".repeat((4-r.length%4)%4)));return typeof s?.sub=="string"&&s.sub.length>0?s.sub:void 0}catch{return}}function goe(t,e){return t!==void 0&&e!==void 0&&t!==e}function AH(t,e){let r=aR(),s=null;if(r)try{let i=r.getItem(t);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(s={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{s=null}let n=cR.get(t)??s??null;return!n||goe(n.actor,e)?null:n}function yoe(t,e){let r={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};cR.set(t,r);let s=aR();if(s)try{s.setItem(t,JSON.stringify(r))}catch{}}function wI(t){cR.delete(t);let e=aR();if(e)try{e.removeItem(t)}catch{}}var IH=new Set(["paused","acquiring","live"]),boe=new Set(["24h","keep"]);function RH(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}function xoe(t){if(typeof t?.id!="string"||t.id.length===0)throw new Gi("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof t.state!="string"||!IH.has(t.state))throw new Gi(`[urun] session ${t.id} reported an unrecognized state ${JSON.stringify(t.state)} \u2014 this @urun-sh/core build knows only ${[...IH].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof t.recordings_expired=="boolean"?e=t.recordings_expired:S.warn(`[urun] session ${t.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:t.id,label:typeof t.label=="string"&&t.label.length>0?t.label:null,state:t.state,app:typeof t.app=="string"?t.app:"",functionName:typeof t.function=="string"?t.function:"",createdAt:RH(t.created_at),lastActiveAt:RH(t.last_active_at),archived:t.archived===!0,preview:typeof t.preview=="string"&&t.preview.length>0?t.preview:null,recordingsExpired:e,retention:boe.has(t.retention)?t.retention:(t.retention!==void 0&&S.warn(`[urun] session ${t.id} reported an unrecognized retention ${JSON.stringify(t.retention)} \u2014 defaulting to '24h'`),"24h")}}var dR=class{_request;_app;constructor(t,e){this._app=t,this._request=e}async list(t={}){let{rows:e,nextCursor:r}=await $F({...this._request,app:t.app??this._app,functionName:t.functionName,includeArchived:t.includeArchived,limit:t.limit,cursor:t.cursor});return{sessions:e.map(xoe),nextCursor:r}}async end(t){await FF({...this._request,sessionId:t})}async archive(t){await rI({...this._request,sessionId:t,archived:!0})}async unarchive(t){await rI({...this._request,sessionId:t,archived:!1})}async setName(t,e,r={}){await HF({...this._request,sessionId:t,name:e,source:r.source})}};function PH(t,e,r){let s=SI(r);yoe(t,s!==void 0?{sessionId:e,actor:s}:{sessionId:e})}var woe=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function XH(t,e){return new dR(t,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function YH(t,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(r,s){if(!(woe.has(s)||typeof s!="string"))return(n,i)=>{let o=n??{},a=moe({orgId:e.orgId,app:t,functionName:s}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,u=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=u(),h=e.jwt,p=e.getAccessToken?async X=>{let Z=await e.getAccessToken(X);return Z&&(h=Z),Z}:void 0,m={...e,getAccessToken:p},_=new JA,f=new aI({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:l,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new oR(l,_,f,KH(m),vI(m),{activity:i?.activity}),w,E=!1,O=!1,q,R,k=new Promise(X=>{R=X}),C,I=X=>{X.sessionId||q||(q="teardown",C="ticket",Eg({baseUrl:X.baseUrl,requestId:X.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},H=X=>{q||X.sessionId||(q="abandon",Eg({baseUrl:X.baseUrl,requestId:X.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},W=X=>{let Z=X.sessionId||!d?X:{...X,sessionId:d};w=Z,R({status:"ready",handle:Z}),(O||q==="teardown")&&I(Z)};b.setEndHandler(async()=>{let X=w?{status:"ready",handle:w}:await k;if(X.status==="unavailable")throw new El("[urun] session allocation failed before a releasable request was created",{cause:X.cause});let Z=w??X.handle;return wI(a),q==="teardown"?Z.sessionId?{status:"paused",sessionId:Z.sessionId,reason:"client_ended"}:{status:"canceled",requestId:Z.requestId}:(q="end",Z.sessionId?tI({baseUrl:Z.baseUrl,sessionId:Z.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider}):eI({baseUrl:Z.baseUrl,requestId:Z.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let X=w?{status:"ready",handle:w}:await k;if(X.status==="unavailable")throw new El("[urun] session allocation failed before a cancellable request was created",{cause:X.cause});let Z=w??X.handle;if(Z.sessionId)throw new Sn(`[urun] cancel() is for a queued admission request, but this call already has session ${Z.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:Z.sessionId,code:"cancel_on_live_session"});q="end";try{let P=await eI({baseUrl:Z.baseUrl,requestId:Z.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider});return wI(a),P}catch(P){throw q==="end"&&(q=void 0),P}});let J=async X=>{let Z,P=i?.sessionId??e.sessionKey??d,M,Y;if(P===void 0&&!c){let Fe=AH(a);if(Fe?.sessionId){if(Y=SI(h),Fe.actor!==void 0&&Y===void 0&&p){let nt=await Promise.resolve(p()).catch(()=>{});Y=SI(nt??e.jwt)}M=Fe.actor!==void 0&&Y!==void 0&&Fe.actor!==Y?void 0:Fe.sessionId}}let j=P??M,z=(Fe,nt)=>jF({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:t,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider,idempotencyKey:Fe,sessionKey:nt,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:vt=>{f.reportAdmission(vt),vt.sessionId&&!d&&(d=vt.sessionId,Z=vt.sessionId,w&&w.sessionId!==vt.sessionId&&W({...w,sessionId:vt.sessionId}),E||(e.sessionKey||PH(a,vt.sessionId,h),b.setSessionId(vt.sessionId)))},onRequest:W}),se;try{se=await z(X,j)}catch(Fe){if(M===void 0||!(Fe instanceof Cr)||Fe.code!=="session_name_not_yours")throw Fe;S.warn(`[urun] session_name_not_yours: the control plane refused session ${M} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),AH(a,Y)?.sessionId===M&&wI(a),se=await z(u(),void 0)}let de=p?await p()??void 0:e.jwt;if(Z&&Z!==se.sessionId)throw w&&w.sessionId!==se.sessionId&&W({...w,sessionId:se.sessionId}),new Cr(`Gateway contract violation: admission minted session ${Z} but allocation completed as ${se.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=se.sessionId,w&&w.sessionId!==se.sessionId&&W({...w,sessionId:se.sessionId}),E||(e.sessionKey||PH(a,se.sessionId,h),b.setSessionId(se.sessionId),b.setArtifactsAuth(vI({...m,baseUrl:se.baseUrl})),f.setEndsAt(se.endsAt),f.seedRegion(sI(se.response))),{url:se.wsUrl,sessionId:se.sessionId,jwt:de,iceServers:se.response.ice_servers,endsAt:se.endsAt}},F,V=0,Q=p?async()=>{let X=V++>0;return await p(X?{forceRefresh:!0,reason:"background"}:void 0)??F}:()=>F,B=()=>{let X=f.connectedUrl;return X?cI(X):void 0};if(f.setConnectionResolver(async()=>{let X=await J(u());return F=X.jwt,X}),f.on("connected",()=>{f.multiplexer&&_.setTarget(f.multiplexer);let X=f.connectedUrl;X&&b.setDocTransport({wsUrl:X,token:Q,resolveServerUrl:B})}),(async X=>{let Z;try{Z=await J(X)}catch(P){if(E){R({status:"unavailable",cause:P});return}S.error(`[urun] Failed to create session for ${s}:`,P),w&&H(w);let M=P instanceof Error?P:new Error(String(P)),Y=P instanceof Cr?P.httpStatus:void 0,j=P instanceof Cr?P.code:void 0,z=P instanceof Cr?P.retryAfterSeconds:void 0;f.reportAllocationFailure(M,Y,j,z),R({status:"unavailable",cause:P});return}E||(f.setAuth({jwt:Z.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:Z.url,sessionId:Z.sessionId,iceServers:Z.iceServers}),Qh()&&await K1(),F=Z.jwt,b.setDocTransport({wsUrl:Z.url,token:Q,resolveServerUrl:B}),await f.connect({app:t,functionName:s,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(l).catch(X=>{S.error(`[urun] Failed to connect session for ${s}:`,X)}),e.releaseOnLeave!==!1){let X=qI(()=>{if(E=!0,f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let j=w;j?I(j):O=!0});b.onDisconnect(X);let Z,P,M=!1,Y=()=>{M||(M=!0,Z?.(),P?.())};k.then(j=>{j.status!=="ready"||M||(Z=VI(()=>w!==void 0))}),P=b.onPhase(j=>{let z=j?.name;(z==="paused"||z==="error")&&Y()}),M&&P(),b.onDisconnect(Y)}return b}}})}var WOe=globalThis.require??(0,rq.createRequire)(L),sq="https://api.urun.sh",nq="URUN_DEV";function voe(){if(typeof process>"u")return!1;let t=process.env?.[nq];if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"}var Bg=class extends Error{status;constructor(t,e){super(t),this.name="ClientTokenError",this.status=e}};async function _oe(t,e={}){if(!t)throw new Bg("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,s=Tr(e.baseUrl??sq),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??voe())&&(n.dev=!0);let i;try{i=await r(`${s}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(h){throw new Bg(`[urun] client token mint request failed: ${h instanceof Error?h.message:String(h)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let h=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new Bg(`[urun] client token mint failed: ${h}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,u=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Bg("[urun] client token mint returned no token (control-plane contract violation)",i.status);let l=Number.isFinite(d)?new Date(d):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var JH=3e4,QH="stream:",Soe=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(t,e){this._ws=t,this._multiplexer=e,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let n=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(n.timer),s.error?n.reject(new Error(s.error)):n.resolve(s.result)}})}async get(t){return this._sendRpc("store.get",{key:t})}async has(t){return await this._sendRpc("store.has",{key:t})}on(t,e){let r=`${QH}${t}`;return this._multiplexer.on(r,s=>{e(s)})}emit(t,e){let r=`${QH}${t}`,s=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{data:e};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(t,e){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let n=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(n)&&(this._pendingRpc.delete(n),s(new Error(`RPC request "${t}" timed out after ${JH}ms`)))},JH);this._pendingRpc.set(n,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:n,type:t,...e}))})}};function Eoe(t){let e=`${t.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(t.orgId)}`,r=new WebSocket(e);(t.jwt||t.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,apiKey:t.apiKey}))});let s=new YA(r);return new Soe(r,s)}var Coe='video/mp4; codecs="avc1.42E01E"';function Toe(t,e){let r=e?.codec??Coe,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(r)}catch(f){throw f instanceof DOMException&&f.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):f}let p=t.getReader();function m(){return h.updating?new Promise(f=>{h.addEventListener("updateend",()=>f(),{once:!0})}):Promise.resolve()}async function _(){try{for(;;){let{done:f,value:b}=await p.read();if(f){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{h.appendBuffer(b)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let E=h.buffered;if(E.length>0){let O=E.start(E.length-1);h.remove(0,O),await m(),h.appendBuffer(b)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}_()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),d=c.getTracks(),u=0,l=d.length;if(l===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of d)h.addEventListener("ended",()=>{u++,u>=l&&URL.revokeObjectURL(i)});return c}function koe(t){return t.status.startsWith("pending_")}var fv=class extends Error{status;code;constructor(t,e){super(t),this.name="CreditsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},fR=class extends fv{constructor(t="[urun] credits: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Aoe(t,e,r){let s=r||e||`HTTP ${t}`;return t===401?new fR(s,e??"unauthorized"):new fv(s,{status:t,code:e??`http_${t}`})}var iq=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let t=await this._request("GET","/balance");if(!t||typeof t!="object"||typeof t.org_id!="string")throw new fv("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return t}async getLedger(t={}){let e=(await this._request("GET","/ledger",{params:t.limit!==void 0?{limit:String(t.limit)}:void 0})).entries;return Array.isArray(e)?e:[]}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw Aoe(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(t,{method:e,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new fR("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function Ioe(t){return new iq(t)}var oq=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function ZH(t){let e=[];return t.audio&&e.push("audio"),t.video&&e.push("video"),e.join("+")}function Roe(t,e){return e==="audio"?t.getAudioTracks():t.getVideoTracks()}function Poe(t,e){let r=t.getTracks();if(r.length===1&&r[0]===e)return t;try{return new MediaStream([e])}catch{return t}}function lR(t,e){for(let r of[...t.lostListeners])try{r(e)}catch{}}var aq=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(t){this.injectedGetUserMedia=t?.getUserMedia}claim(t,e){return this.enqueue(async()=>{let r=this.claims.get(t);r&&(this.claims.delete(t),r.released=!0,r.track=null,r.stream=null,lR(r,new Error(`${t} capture claim superseded by a newer claim`)));let s=this.createState(t,e);return this.claims.set(t,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(t){let e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!t?.getUserMedia)throw new oq;return e=>t.getUserMedia(e)}async converge(t){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.stream=null);if(this.claims.size===0)return;let e=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await e(r)}catch(i){let o=`one-capture getUserMedia(${ZH(r)}) failed`,a=i instanceof Error?i.message:String(i);for(let c of[...this.claims.values()])if(this.claims.delete(c.kind),c.released=!0,c!==t){let d=new Error(`${o} \u2014 ${c.kind} capture lost: ${a||i}`);d.cause=i,lR(c,d)}throw i}let n=[...this.claims.values()].sort((i,o)=>i===t?1:o===t?-1:0);for(let i of n){let o=Roe(s,i.kind)[0]??null;if(i.released){o?.stop();continue}if(!o){this.claims.delete(i.kind),i.released=!0;let a=Object.assign(new Error(`one-capture getUserMedia(${ZH(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===t)throw a;lR(i,a);continue}if(i.track=o,i.stream=Poe(s,o),i!==t)for(let a of[...i.trackListeners])try{a(o,i.stream)}catch{}}}createState(t,e){let r=this,s={kind:t,constraints:e,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:t,get track(){return s.track},get stream(){return s.stream},update(n){return r.enqueue(async()=>{if(s.released)throw new Error(`${t} capture claim already released`);if(s.constraints=n,await r.converge(s),!s.track)throw new Error(`${t} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(t)===s&&r.claims.delete(t),s.track?.stop(),s.track=null,s.stream=null)},onTrack(n){return s.trackListeners.add(n),()=>s.trackListeners.delete(n)},onLost(n){return s.lostListeners.add(n),()=>s.lostListeners.delete(n)}}};return s}},Boe=null;function Doe(){return Boe??=new aq}var cq="input",Loe=30;function Ooe(t){let e=t.now??Date.now,r=t.field??cq,s=1e3/Math.max(t.hz??30,.001),n=new Set,i=0,o=0,a=0,c=0,d,u=null,l=!1,h=()=>{if(l)return;d=e(),c+=1;let m={keys:[...n],buttons:i,pointer:{x:o,y:a},seq:c,at:d};try{t.awareness.setLocalStateField(r,m)}catch{}},p=()=>{if(l)return;let m=e();if(d===void 0||m-d>=s){u&&(clearTimeout(u),u=null),h();return}if(u)return;let _=Math.max(s-(m-d),0);u=setTimeout(()=>{u=null,h()},_),u.unref?.()};return{keyDown(m){let _=String(m).toLowerCase();n.has(_)||(n.add(_),p())},keyUp(m){let _=String(m).toLowerCase();n.delete(_)&&p()},setButtons(m){let _=Number.isFinite(m)?Number(m):0;_!==i&&(i=_,p())},movePointer(m,_){let f=Number.isFinite(m)?Number(m):0,b=Number.isFinite(_)?Number(_):0;f===0&&b===0||(o+=f,a+=b,p())},heldKeys(){return[...n]},clear(){l||(n.clear(),i=0,u&&(clearTimeout(u),u=null),h())},dispose(){if(l)return;let m=n.size>0||i!==0;n.clear(),i=0,u&&(clearTimeout(u),u=null),m&&h(),l=!0}}}var Noe=1024,Uoe=.92,Moe=262144,joe=256e3,uR=[.9,.8,.7,.6,.5],eq=.8,$oe=8;function pR(t,e,r){if(!(t>0)||!(e>0))throw new Error(`reference image has no pixels (${t}x${e})`);let s=Math.min(1,r/Math.max(t,e));return{width:Math.max(1,Math.round(t*s)),height:Math.max(1,Math.round(e*s))}}async function Foe(t){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(t,{imageOrientation:"from-image"})}async function dq(t,e,r){let s=await new Promise(n=>{t.toBlob(n,e,e==="image/jpeg"?r:void 0)});if(!s)throw new Error(`could not encode the reference image as ${e}`);return s}function tq(t,e){S.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${t} -> ${e} bytes`)}async function hR(t,e,r,s,n){let i=document.createElement("canvas");i.width=e,i.height=r;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return s==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,r)),o.drawImage(t,0,0,e,r),await dq(i,s,n)}async function Hoe(t,e,r,s){let{width:n,height:i}=e,o=await hR(t,n,i,r,s);if(o.size<=256e3)return{blob:o,width:n,height:i};if(r==="image/jpeg"){for(let c of uR)if(!(c>=s)&&(o=await hR(t,n,i,r,c),o.size<=256e3))return tq(`quality ${s} -> ${c}`,o.size),{blob:o,width:n,height:i}}let a=r==="image/jpeg"?uR[uR.length-1]:s;for(let c=0;c<$oe;c++)if(n=Math.max(16,Math.round(n*eq)),i=Math.max(16,Math.round(i*eq)),o=await hR(t,n,i,r,a),o.size<=256e3)return tq(`downscaled to ${n}x${i} @ q${a}`,o.size),{blob:o,width:n,height:i};throw new Error(`this image cannot be sent: even at ${n}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function qoe(t,e){let{maxSize:r=1024,type:s="image/jpeg",quality:n=.92,source:i}=e,o=await Foe(t);try{let a=pR(o.width,o.height,r),c=await Hoe(o,a,s,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:s,width:c.width,height:c.height,source:i}}finally{o.close()}}function Voe(t){let e=t instanceof Error?t.name:"",r=t instanceof Error?t.message:String(t);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function zoe(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Woe(t,e){let r=t.videoWidth,s=t.videoHeight;if(!(r>0)||!(s>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=pR(r,s,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(t,0,0,a.width,a.height);let u=await dq(c,i,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Koe=new Set(["w","a","s","d"]),ef=(t,e)=>Math.min(e,Math.max(-e,t));function Goe(t={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:s=.18,decayTauMs:n=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=t,c=0,d=0,u=0,l=null,h=new Set;return{pointerDelta(p,m){c=ef(c-p*e,o),d=ef(d-m*e,o)},keyDown(p){let m=p.toLowerCase();Koe.has(m)&&h.add(m)},keyUp(p){h.delete(p.toLowerCase())},clearKeys(){h.clear()},frameArrived(){let p=1-i;c*=p,d*=p,u*=p},tick(p){if(l===null){l=p;return}let m=Math.max(0,Math.min(100,p-l))/1e3;l=p,h.has("w")&&(u=ef(u+r*m,a)),h.has("s")&&(u=ef(u-r*m,a)),h.has("a")&&(c=ef(c+s*m,o)),h.has("d")&&(c=ef(c-s*m,o));let _=Math.exp(-m*1e3/n);c*=_,d*=_,u*=_},transform(){return{translateX:c,translateY:d,scale:Math.exp(u)}},isIdentity(p=5e-4){return Math.abs(c)<p&&Math.abs(d)<p&&Math.abs(u)<p},reset(){c=0,d=0,u=0,h.clear()}}}g();y();var xq=require("@earendil-works/pi-ai"),tf=require("fs"),wq=require("path");g();y();g();y();g();y();g();y();function lq(t,e,r,s){let n=t.response??{},i={request_id:r,consumer_id:s,stream:!0,kind:"chat",messages:e};return typeof n.instructions=="string"&&(i.instructions=n.instructions),Array.isArray(n.modalities)&&(i.modalities=n.modalities),typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(i.max_output_tokens=n.max_output_tokens),n.tools!==void 0&&(i.tools=n.tools),i}function uq(t,e,r){let s={request_id:e,consumer_id:r,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(s.model=t.model),t.tools!==void 0&&(s.tools=t.tools),t.tool_choice!==void 0&&(s.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(s.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(s.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(s.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(s.stop=t.stop),typeof t.reasoning_effort=="string"&&(s.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(s.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(s.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(s.response_format=t.response_format),typeof t.voice=="string"&&(s.voice=t.voice),typeof t.language=="string"&&(s.language=t.language),s}g();y();g();y();function hq(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,r=e.body??{},s=r.error,n=s?.message??r.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:s?.type??"urun_error",code:e.code??s?.code??null,message:n}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Xoe="llm-resp";async function*gR(t,e){let r=`${Xoe}:${e}`,s=`resp_${e}`;yield{type:"response.created",response:{id:s,status:"in_progress"}};let n=new Map;try{for await(let i of t.stream(r).messages()){let o=i;if(o.t==="delta"){if(typeof o.delta=="string"&&(yield{type:"response.output_text.delta",item_id:s,delta:o.delta}),typeof o.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:s,delta:o.reasoning}),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let c=typeof a.index=="number"?a.index:0,d=n.get(c)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),n.set(c,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(o.t==="response"){yield{type:"response.completed",response:{id:s,status:"completed",...o.body}};return}else if(o.t==="error"){yield hq(o);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var mv=class t{constructor(e,r=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=r;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((n,i)=>{let o=e.onSynced(()=>{clearTimeout(r),n()});r=setTimeout(()=>{o(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){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,r){return this.writeGated(r,()=>{let s=uq(e,r,this.consumerId);return this.write(s),gR(this.session,r)})}sendResponseCreate(e,r,s){return this.writeGated(s,()=>{let n=lq(e,r,s,this.consumerId);return this.write(n),gR(this.session,s)})}async writeGated(e,r){try{await this.ensureDocSynced()}catch(s){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${s instanceof Error?s.message:String(s)}`)}return r()}};var fq=0;function Yoe(){return fq+=1,`req_${Date.now().toString(36)}_${fq.toString(36)}`}var gv=class{transport;constructor(e){this.transport=new mv(e)}responses={create:async e=>{let r=Yoe(),s=await this.transport.sendResponses(e,r);return Object.assign((async function*(){yield*s})(),{requestId:r})}}};Tv();g();y();g();y();g();y();g();y();g();y();g();y();g();y();var yR="https://api.urun.sh/v1";async function pq(t){let e=t.fetchImpl??fetch,r=`${t.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(r,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${r} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${r})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${r} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}async function mq(t){let e=await pq(t),r=e.filter(s=>s.function_name===t.fnName&&s.deployment_status==="active").map(s=>s.app_slug);if(r.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return r.sort()}var xR="urun-serve",eae="serve",tae=131072,rae=16384,gq=3,sae=42e4,nae=6e4,yq=2,iae=15e3;function oae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||yR,fnName:(t.URUN_FUNCTION??"").trim()||eae}}function vq(t){let e=(t.URUN_BASE_URL??"").trim(),r=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!r)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let s=(t.URUN_JWT??"").trim();if(s)return{baseUrl:e,orgId:r,auth:{lane:"jwt",jwt:s}};let n=(t.URUN_API_KEY??"").trim();if(!n)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:r,auth:{lane:"api-key",apiKey:n,gatewayUrl:i}}}function _q(t){let e=null;return r=>{e===null&&((0,tf.mkdirSync)((0,wq.dirname)(t),{recursive:!0}),e=(0,tf.openSync)(t,"a"));let s=r.detail?` ${JSON.stringify(r.detail)}`:"";(0,tf.writeSync)(e,`${new Date().toISOString()} [${r.level}] [urun] ${r.message}${s}
175
+ `)}var Rie=class{constructor(t){this.sink=t}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(t){this.deadCb=t}setSource(t){if(this.stopped||t!==null&&t===this.currentTrack&&t.readyState==="live")return;let e=null;if(!(t!==null&&(e=Pie(t)?this.bridgedTrack(t):t,!e))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(e)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=e,e&&this.wireTrackLiveness(e);return}e!==null&&this.engage(e)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(t){let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof e.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(i){this.die(`transform worker: ${i instanceof Error?i.message:String(i)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(t);this.sender=s,this.currentTrack=t,this.wireTrackLiveness(t);let n=e.RTCRtpScriptTransform;if(s.transform=new n(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(i=>this.die(`loopback renegotiate: ${i instanceof Error?i.message:String(i)}`));return}this.negotiate().catch(i=>this.die(`loopback negotiate: ${i instanceof Error?i.message:String(i)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let e=t.RTCPeerConnection;this.sendPc=new e({iceServers:[]}),this.recvPc=new e({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(t){if(!this.stopped){if(t===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(t);else try{this.renderSender.replaceTrack(t)}catch(e){this.die(`render replaceTrack: ${e instanceof Error?e.message:String(e)}`);return}this.wireRenderRemote(t),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(e=>this.die(`loopback negotiate: ${e instanceof Error?e.message:String(e)}`))}}}onRenderTrack(t){this.renderRemoteCb=t}renderMidOf(){if(!this.renderSender)return null;let t=this.sendPc;try{return t.getTransceivers?.().find(e=>e.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(t){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},t.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let t=this.sendPc,e=this.recvPc;if(!(!t||!e||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await t.createOffer();r.sdp=wH(r.sdp??""),await t.setLocalDescription(r),await e.setRemoteDescription(t.localDescription??{type:"offer",sdp:r.sdp});let s=await e.createAnswer();s.sdp=wH(s.sdp??""),await e.setLocalDescription(s),await t.setRemoteDescription(e.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let t=this.candQueue;if(t){for(;t.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(t.toSend.shift())).catch(()=>{});for(;t.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(t.toRecv.shift())).catch(()=>{})}}bridgedTrack(t){let e=t;try{let r=e.context.createMediaStreamDestination();e.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:e,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(t){this.endedListener=()=>this.die("mic track ended"),t.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Iie],{type:"text/javascript"}));let t=new Worker(this.workerUrl);return t.onmessage=e=>{let r=e.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},t.onerror=e=>this.die(`transform worker: ${e.message||"error"}`),this.worker=t,t}onEncodedFrame(t,e){if(this.stopped)return;let r=zH(this.frameSeq,t,e,this.sink.maxDatagramSize()||eR);if(r===null){S.warn(`[urun] WT mic uplink: frame of ${e.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}die(t){this.stopped||(S.warn(`[urun] WT mic uplink lane dead (${t}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(t))}};function Pie(t){let e=t;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Bie=9e4,Die="avc1.42E01F",Lie=60,Oie=3,Nie=1e4;function Uie(t){return Math.round(t*(Bie/1e6))%2**32>>>0}var Mie=class{constructor(t){this.sink=t}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(t){this.deadCb=t}requestKeyframe(){this.keyframeWanted=!0}setSource(t){if(this.stopped||(this.teardownCapture(),t===null))return;let e=globalThis.MediaStreamTrackProcessor;if(typeof e!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new e({track:t}).readable.getReader(),n=!1;this.cancelCapture=()=>{n=!0,s.cancel().catch(()=>{})},(async()=>{for(;!n&&!this.stopped&&r===this.generation;){let{value:i,done:o}=await s.read();if(o)break;if(i){if(n||this.stopped||r!==this.generation){i.close();break}this.encodeFrame(i)}}})().catch(i=>{!n&&!this.stopped&&r===this.generation&&this.die(`capture: ${i instanceof Error?i.message:String(i)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(t){let e={width:t.codedWidth,height:t.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==e.width||this.encoderDims.height!==e.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){t.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)})),this.encoderDims=e,this.encoder.configure({codec:Die,avc:{format:"annexb"},width:e.width,height:e.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(n){t.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=Lie;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(t,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}t.close()}sendFrame(t){if(this.stopped)return;let e=new Uint8Array(t.byteLength);t.copyTo(e);let r=zH(this.frameSeq,Uie(t.timestamp),e,this.sink.maxDatagramSize()||eR,{lane:wie,keyframe:t.type==="key"});if(r===null){S.warn(`[urun] WT video uplink: AU of ${e.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(t){if(this.stopped)return;let e=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>e-r<Nie),this.encoderErrorsAt.push(e),this.encoderErrorsAt.length>=Oie){this.die(`video encoder: ${t.message}`);return}S.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",t.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(t){this.stopped||(S.warn(`[urun] WT video uplink lane dead (${t}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(t))}};function jie(t){return t.byteLength>=2&&t[0]===1&&t[1]===3}var $ie=class{constructor(t){this.transport=t}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(t){this.deadCb=t}send(t,e){let r=new TextEncoder().encode(t);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let n=this.streams.get(t);if(!n){let o=await this.transport.openUniStream(),a=new Uint8Array(2+r.byteLength);a[0]=1,a[1]=r.byteLength,a.set(r,2),await o.write(a),n={writer:o},this.streams.set(t,n)}let i=new Uint8Array(4+e.byteLength);new DataView(i.buffer).setUint32(0,e.byteLength,!0),i.set(e,4),await n.writer.write(i),jie(e)&&(this.streams.delete(t),await n.writer.close().catch(()=>{}))}catch(n){throw this.die(n instanceof Error?n.message:String(n)),n}});return this.chain=s.catch(()=>{}),s}stop(t="stopped"){if(this.dead===null){this.dead=t;for(let e of this.streams.values())e.writer.close().catch(()=>{});this.streams.clear()}}die(t){this.dead===null&&(S.warn(`[urun] WT data uplink lane dead (${t})`),this.stop(t),this.deadCb?.(t))}},vH=250,Fie=25,Hie=2e3,qie=15e3,Vie=1e3,zie=45e3,Wie=5e3,Kie={llm:!0},Gie=500,_H=10,Xie=2,Yie=2,gI=2,tR=class Al{constructor(e,r,s,n,i,o,a){this.offer=e,this.sessionId=r,this.canvas=s,this.audioLane=n,this.audioUplink=i,this.videoUplink=o,this.dataUplink=a,this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new YI({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let r=this.offer.codec,s=r!==void 0&&r!=="";this.hasVideoLane=s,s&&bH(r,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(u=>({algorithm:"sha-256",value:Uint8Array.from(atob(u),l=>l.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=n.readable.getReader(),o=new GI,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,S.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),s&&(bH(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let u={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},l=new Aie(this.offer.audio,{...this.audioLane,renderHop:u});try{l.start(),this.audioPlayout=l}catch(h){S.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),l.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let u=this.wt.createUnidirectionalStream?.bind(this.wt);if(!u)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new $ie({openUniStream:async()=>(await u()).getWriter()});l.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h,l)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(u){let l=u instanceof Error?u.message:String(u);S.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(i,o,a).catch(u=>this.die(`control loop: ${u}`)),this.datagramLoop().catch(u=>this.die(`datagram loop: ${u}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Gie)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(u=>{this.closedReason=`connection error: ${u}`,this.die(`connection error: ${u}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${vH}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??qie},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Vie))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let r=typeof e.ds=="number"?e.ds:null,s=typeof e.ur=="number"?e.ur:null;if(r===null&&s===null)return;this.gatewayExposesCounters=!0;let n=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:r,ur:s,recvDownlink:n,sentUplink:i},!o)return;let a=r!==null&&o.ds!==null?r-o.ds:null,c=s!==null&&o.ur!==null?s-o.ur:null,d=n-o.recvDownlink,u=i-o.sentUplink,l="none";if(a!==null&&a>=_H&&d<=0?l="downlink":c!==null&&u>=_H&&c<=0&&(l="uplink"),l==="none"){this.severedStreak="none",this.observePlayoutProgress(d,r);return}if(this.severedStreak!==l){this.severedStreak=l;return}this.severedStreak="none";let h=l==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${u} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${r} ur=${s}, client received=${n} accepted=${i}, confirmed on ${Xie} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,r){let s=this.audioPlayout;if(!s){this.playoutScheduledSeen=null;return}let n=s.playoutProgress(),i=n.surfaced;if(this.playoutScheduledSeen!==null&&n.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=n.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=n.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Yie)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,S.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{s.rebuildSurface()}catch(o){S.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=gI}return}this.playoutStallStreak<gI||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled} on ${gI} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let r=this.pathLiveness();if(!r.alive)return;let s=performance.now(),n=this.audioLaneLastArrivalAt===null?null:s-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:s-this.lastInboundControlAt,o=n===null&&i===null?!0:(n===null||n>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:s-this.lastInboundDataAt,u=n!==null?n:this.firstInboundDataAt===null?null:s-this.firstInboundDataAt,l=u!==null&&u>=e.stallMs;if(c&&l&&d!==null&&d<=Wie&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((u??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${r.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=zie&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let r=this.dataUplinkSender;r&&(this.dataUplinkSender=null,r.stop(e),this.dataUplink?.onUplinkLost(e,r))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let r={onData:(s,n)=>{if(Kie[s]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(s,n)},onLaneError:s=>e.onLaneError(s)};this.dataLaneSink=r,ZI(this.wt.incomingUnidirectionalStreams,r).catch(s=>{this.die(`data lane: ${s instanceof Error?s.message:String(s)}`)})}initDecoder(e,r,s){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:r,height:s};let o=new n({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...r>0&&s>0?{codedWidth:r,codedHeight:s}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;S.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(r.codec,r.width,r.height),this.decoderErrorLogged=!1}catch(s){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${s instanceof Error?s.message:String(s)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,r){this.stopped||this.deadFired||this.datagramWriter().write(e).then(r,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let r=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,S.error(`[urun] WT uplink datagram send FAILED (${r}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let s=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(n=>s-n<Hie),this.uplinkSendErrorsAt.push(s),!(this.uplinkSendErrorsAt.length<Fie)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${r}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let r=0;return{send:s=>this.uplinkSend(s,()=>{r++}),delivered:()=>r,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??eR}}engageAudioUplink(){let e=new Rie(this.uplinkSink("audio"));e.onDead(r=>this.onUplinkLaneDead("audio",r,e)),e.onRenderTrack?.(r=>this.renderRemoteCb?.(r)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new Mie(this.uplinkSink("video"));e.onDead(r=>this.onUplinkLaneDead("video",r,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let r=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(s){let n=s instanceof Error?s.message:String(s);S.warn(`[urun] WT ${r} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${r} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}freshLaneBuilt(e){let r={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),r}onUplinkLaneDead(e,r,s){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=i?.builtAt!=null&&Date.now()-i.builtAt>=Al.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(o>Al.UPLINK_LANE_RETRY_MAX){S.error(`[urun] WT ${n} uplink lane dead (${r}) \u2014 ${Al.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${Al.UPLINK_LANE_RETRY_MAX} recovery attempts: ${r}`,s);return}S.warn(`[urun] WT ${n} uplink lane dead (${r}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${Al.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},Al.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,r,s){e==="audio"?this.audioUplink.onUplinkLost(r,s):this.videoUplink.onUplinkLost(r,s)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:r,done:s}=await e.read();if(s)break;if(!r)continue;if(r.byteLength>=ei&&r[11]===VH){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(r);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let i=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(r)}}decodeFrame(e,r,s){let n=globalThis.EncodedVideoChunk;if(typeof n=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new n({type:r?"key":"delta",timestamp:e*(1e6/24),data:s})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(KI(e)),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async sendControlRaw(e){try{let r=new Uint8Array(4+e.byteLength);new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),await this.writer.write(r),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async readControl(e,r,s=[]){for(;;){let n=s.shift();if(n)return n;let{value:i,done:o}=await e.read();if(o)return null;i&&s.push(...r.push(i))}}async controlLoop(e,r,s){for(;!this.stopped;){let n=await this.readControl(e,r,s);if(!n)break;let i=n;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(yie(n.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let r=performance.now(),s=(r-e)/1e3;e=r;let n=this.reassembler.drainWindow(),i=n.delivered+n.abandoned;this.lastStats={recvBps:s>0?n.bytes*8/s:0,lossPct:i>0?100*n.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},vH)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}},SH=2500,EH=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Jie=1e4,rR=class vc{constructor(e,r,s){this.signaling=e,this.sessionId=r,this.opts=s}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let r=this.session;!r||r.kind!=="webtransport"||r.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let r=typeof e.WebTransport=="function",s=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,i={webtransport:r&&s&&n,webcodecs:s,codecs:EH,wtData:r&&s&&n&&this.opts.dataLane!==void 0,wtAudio:r&&s&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:r&&n&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:r&&s&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:r&&s&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&S.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await bI(d.start(),this.opts.quicDeadlineMs??SH,"quic connect deadline"),this.wtDialedHost=yI(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(u){if(S.warn(`[urun] WT dial failed (${av(u)}) \u2014 dialed ${CH(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(u instanceof Error?u.message:u);throw S.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),u}S.warn("[urun] webtransport failed, falling back to webrtc:",u),this.proceedWebRtcDial(`wt failed: ${String(u instanceof Error?u.message:u)}`),this.notifyEstablished("webrtc",String(u instanceof Error?u.message:u))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw S.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=yI(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,S.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Qie(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,n=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",i=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",o=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:EH,wtData:s,wtAudio:n,wtAudioUp:i,wtVideoUp:o,wtDataUp:a}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let c=this.createWebTransportSession();try{await bI(c.start(),this.opts.quicDeadlineMs??SH,"quic connect deadline")}catch(d){throw S.warn(`[urun] WT dial failed (${av(d)}) \u2014 dialed ${CH(this.offer.webtransport?.url)}`),c.stop().catch(()=>{}),d}if(this.wtDialedHost=yI(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,s)}catch(d){throw c.stop().catch(()=>{}),d}if(this.disconnected)return c.stop().catch(()=>{}),null;this.session=c;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),c}engageQuicDataLane(e,r){if(!r||this.offer?.webtransport?.data!==!0)return;let s=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,i)=>s.onData(n,i),onLaneError:n=>s.onLaneError(n)}),s.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new tR(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(r=>{S.error("[urun] webrtc path died:",r)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(r=>{if(this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT-REQUIRED leg died mid-session (${r}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(r,!0);return}let s=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),s){this.session=null,this.wtOnlyLeg=!1,S.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",r),this.redialWtAfterDeath(r,!0);return}S.warn("[urun] quic died mid-session, failing over to webrtc:",r),this.lateWebRtcFailover(e,r,s)})}redialWtAfterDeath(e,r=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=vc.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT re-dial failed ${vc.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}S.error(`[urun] WT re-dial failed ${vc.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let s=this.wtRedialFailures+1,n=WH(vc.WT_REDIAL_BASE_MS,s,vc.WT_REDIAL_CAP_MS,s===1&&r?0:void 0);S.warn(`[urun] WT re-dial attempt ${s} scheduled in ${Math.round(n)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},n)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){S.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${vc.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(r){let s=av(r);S.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${vc.WT_REDIAL_MAX} failed (${s}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${s}`)}}}lateWebRtcFailover(e,r,s){this.disconnected||(async()=>{let n=this.createWebRtc();try{let i=await bI(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Jie,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${r}`),this.opts.onTransportChange?.("webrtc",r)}catch(i){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=s?`media transport lost \u2014 the WebTransport connection dropped (${r}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${r}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;S.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,r){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:r})}};function av(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"){try{let e=JSON.stringify(t);if(e!==void 0&&e!=="{}")return e}catch{}return t.constructor?.name??Object.prototype.toString.call(t).slice(8,-1)}return String(t)}function yI(t){if(t)try{return new URL(t).host}catch{return}}function CH(t){if(!t)return"(no offer url)";try{let e=new URL(t);return e.searchParams.delete("token"),e.toString()}catch{return t.replace(/[?&]token=[^&\s]*/g,"")}}function Qie(t){if(!t)return!1;let e=t.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function WH(t,e,r,s){if(s!==void 0)return s;let n=Math.min(t*2**Math.max(0,e-2),r);return Math.round(n*(.75+Math.random()*.5))}function bI(t,e,r){return new Promise((s,n)=>{let i=setTimeout(()=>n(new Error(r)),e);t.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),n(o)})})}var Zie=1e4,sR=class{constructor(t,e=Zie){this.carrier=t,this.requestTimeoutMs=e}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(t,e){let r=ev();return new Promise((s,n)=>{let i=setTimeout(()=>{o(),n(new Error(`[urun] signaling request timed out: ${t}`))},this.requestTimeoutMs),o=this.carrier.onSignal(a=>{if(a.type!==`${t}.response`||a.requestId!==r)return;if(clearTimeout(i),o(),a.error){n(new Error(`[urun] ${t} failed: ${String(a.error)}`));return}let{type:c,requestId:d,...u}=a;s(u)});this.carrier.sendSignal({type:t,requestId:r,...e})||(clearTimeout(i),o(),n(new Error(`[urun] signaling request not sent: ${t} \u2014 the signaling socket is not open`)))})}notify(t,e){this.carrier.sendSignal({type:t,...e})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${t} \u2014 the signaling socket is not open`,detail:{method:t}})}on(t,e){return this.carrier.onSignal(r=>{r.type===t&&e(r)})}},eoe="video",nR=class{constructor(t,e=eoe){this.transport=t,this.streamName=e,this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let e=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(e(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(e)})}async stop(){for(let t of this.unsubscribers.splice(0))t()}onDead(t){this.deadCb=t}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(t){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(t)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(t))}};function toe(t){let e=t;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var roe="video",soe=45e3;async function noe(t,e,r){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let n=e,i=r.runtimeWaitCapMs??soe;return new Promise(o=>{let a=!1,c,d=null,u=null,l=!1,h=_=>{a||(a=!0,m(),u!==null&&(clearTimeout(u),u=null),c?.(),o(_))};u=setTimeout(()=>{if(l||a||r.isDisposed())return;l=!0;let _=n.current();t.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${r.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let p=()=>{d===null&&!a&&(d=setTimeout(()=>h("unconfirmed"),i))},m=()=>{d!==null&&(clearTimeout(d),d=null)};c=e.subscribe(_=>{let f=_?.name;if(f==="live")return h("live");if(f==="error")return h("gone");m(),xc(f)||p()}),xc(s)||p()})}function ioe(t,e,r){let s=globalThis,n=s.document;if(!(typeof n?.createElement=="function"&&typeof s.WebTransport=="function"&&typeof s.VideoDecoder=="function")||r.allowWebTransport===!1)return null;let i=t.holdWebRtcDial?.(),o=n.createElement("canvas"),a=!1,c=null,d=!1,u=()=>{if(c){for(let k of c.getVideoTracks())try{k.stop()}catch{}c=null}d&&(d=!1,r.onOverrideTrack(null))},l=new rR(new sR(t),e,{canvas:o,createWebRtcSession:r.createWebRtcSession??(()=>new nR(t,r.streamName??roe)),createWebTransportSession:r.createWebTransportSession,dataLane:{onData:(k,C)=>t.dispatchQuicStreamData(k,C),onQuicLane:()=>t.markStreamDataLaneQuic(),onQuicLaneLost:k=>t.quicStreamDataLaneLost(k),onLaneError:k=>t.raiseQuicStreamDataError(k)},audioLane:r.onOverrideAudioTrack?{jitterBufferTargetMs:r.audioPlayout?.jitterBufferTargetMs,ctx:r.audioPlayout?.audioContext,onTrack:k=>{a||(k&&t.noteQuicMediaFlowing?.(),r.onOverrideAudioTrack(k))}}:void 0,audioUplink:r.audioUplink,videoUplink:r.videoUplink,dataUplink:r.dataUplink,webRtcDial:i,allowWebRtcFallback:r.allowWebRtcFallback,onWtRequiredOutage:()=>E(),onMediaTransportLost:k=>{a||(u(),r.onOverrideAudioTrack?.(null),r.onMediaTransportLost?.(k),E())},onTransportChange:(k,C)=>{a||(k==="webrtc"&&(u(),E()),r.onTransportChange?.(k,C))}}),h=t.onWtOnlyLegDeath?.(k=>l.failCurrentWtLeg(k)),p=null,m=()=>{p!==null&&(clearInterval(p),p=null)},_=r.wtRetryBaseMs??2e3,f=r.wtRetryCapMs??3e4,b=null,w=0,E=()=>{if(a||b!==null||l.activeTransport==="webtransport")return;let k=WH(_,w+2,f);b=setTimeout(()=>{b=null,w+=1,l.retryWebTransport().then(C=>{if(a){C&&l.disconnect().catch(()=>{});return}if(C)return S.debug(`[urun] webtransport upgraded in background (retry ${w})`),w=0,q(C);E()}).catch(C=>{a||(S.debug(`[urun] webtransport background retry ${w} failed: `+av(C)),E())})},k)},O=()=>{b!==null&&(clearTimeout(b),b=null)},q=async k=>{if(a||k.kind!=="webtransport")return;let C=r.pathHealthProbeMs??1e4;m();let I=!1;p=setInterval(()=>{if(a||l.activeTransport!=="webtransport")return;let W=toe(k);if(!W){S.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),m();return}let J=W.pathLiveness();if(!J.alive){let F=l.isWtOnlyLeg;S.error(`[urun] webtransport path is DEAD: ${J.evidence}`+(F?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),m(),W.fail(`path health: ${J.evidence}`);return}if(!I){if(I=!0,l.isWtOnlyLeg){S.warn(`[urun] webtransport established, no application media yet after ${C}ms \u2014 the QUIC PATH IS HEALTHY (${J.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}S.warn(`[urun] webtransport established but no QUIC media after ${C}ms \u2014 no media datagrams reached this client (path healthy: ${J.evidence}); webrtc track remains authoritative`)}},C);try{await k.firstMedia}catch(W){m(),S.debug("[urun] webtransport ended before any media flowed:",W);return}if(m(),a||l.activeTransport!=="webtransport"||typeof o.captureStream!="function")return;c=o.captureStream();let H=c.getVideoTracks()[0];H&&(d=!0,r.onOverrideTrack(H))},R=!1;return(async()=>{let k=await noe(t,r.runtimePhase,{sessionId:e,runtimeWaitCapMs:r.runtimeWaitCapMs,isDisposed:()=>a});if(a)return;if(k==="gone"){S.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),i?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}R=!0;let C=await l.connect();if(a){l.disconnect().catch(()=>{});return}await q(C)})().catch(k=>{if(m(),a){S.debug("[urun] transport negotiation aborted: session disposed mid-dial:",k);return}if(r.allowWebRtcFallback===!1){S.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",k),E();return}i?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),S.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),E()}),{activeTransport:()=>l.activeTransport,mediaTransportAttempted:()=>R,watchDownlinkStall(k){l.watchDownlinkStall(k)},dispose(){a=!0,h?.(),m(),O(),u(),r.onOverrideAudioTrack?.(null),l.disconnect().catch(()=>{})}}}var ooe=new Set;function KH(t){if(t.functionsUrl)return{functionsUrl:t.functionsUrl,orgId:t.orgId,apiKey:t.apiKey,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}var aoe="rpc",coe="$presence",iR=3e4,TH=3e4,doe="rpc-resp";function loe(t){return`${doe}:${t}`}function xI(){return ev()}function uoe(t){if(t&&typeof t=="object"){let e=t.error;if(e&&typeof e=="object"){let{message:r,code:s}=e;return{message:typeof r=="string"?r:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof t=="string"?t:JSON.stringify(t)}}function hoe(t,e,r,s,n,i,o,a,c,d){let u=[],l=null,h=!1,p=null,m=!1,_,f,b=new Promise((z,se)=>{_=z,f=se});b.catch(()=>{});let w=o(),E=null,O=null,q=null,R=null,k=null,C=null,I=!0,H=()=>{q&&(clearTimeout(q),q=null),R&&(R(),R=null)},W=()=>{k&&(clearTimeout(k),k=null),C&&(C(),C=null)},J=!1,F=()=>{J||!m||(J=!0,t.set({rpc:{[e]:null}}))},V=()=>{I=!1,H(),W(),E?.(),E=null,O?.(),O=null,a?.removeEventListener("abort",P),w.dispose(),F()},Q=()=>{if(l){if(u.length>0){let z=l;l=null,z.resolve({value:u.shift(),done:!1})}else if(p!==null){let z=l;l=null,z.reject(p)}else if(h){let z=l;l=null,z.resolve({value:void 0,done:!0})}}},B=z=>{h||(u.push(z),Q())},X=z=>{h||(p=z,h=!0,f(z),V(),Q())},Z=z=>{h||(h=!0,_(z),V(),Q())},P=()=>{let z=a?.reason;X(z instanceof ta?z:new wg(e))},M=z=>{if(!(h||!z||typeof z!="object"))switch(W(),F(),z.t){case"delta":typeof z.delta=="string"&&B(z.delta);break;case"response":Z(z.body);break;case"error":{let{message:se,code:de}=uoe(z.body);X(new ta(se,{requestId:e,code:z.code??de}));break}}},Y=()=>{let z=w.messages()[Symbol.asyncIterator]();E=()=>{z.return?.(void 0)};let se=()=>{I&&z.next().then(de=>{if(I){if(de.done){h||Z(void 0);return}M(de.value),se()}},de=>{I&&X(de)})};se()},j=()=>{if(!m){if(m=!0,a){if(a.aborted){X(new wg(e));return}a.addEventListener("abort",P,{once:!0})}O=c?.(z=>X(z))??null,Y(),t.set({rpc:{[e]:{args:r,respond_on:s,consumer_id:n,stream:i}}}),d&&d>0&&!t.synced&&(q=setTimeout(()=>{q=null,!h&&!t.synced&&X(new H1(d,e))},d),R=t.onSynced(()=>H())),C=t.onSynced(()=>{C=null,!(h||J||k)&&(k=setTimeout(()=>{k=null,!(h||J)&&S.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(TH/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},TH))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(j(),u.length>0)return Promise.resolve({value:u.shift(),done:!1});if(p!==null){let z=p;return p=null,Promise.reject(z)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((z,se)=>{l={resolve:z,reject:se}})},return(){return h||(h=!0,_(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(z){return h||(h=!0,f(z),V()),Promise.reject(z)}}}},body:b,start:j}}function kH(t){if(t&&typeof t=="object"){let{epoch:e,by:r}=t,s={epoch:typeof e=="number"?e:0};return(r==="runtime"||r==="browser")&&(s.by=r),s}}function foe(t,e){let r=t.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:n,br:i}=r,o={};(s==="audio"||s==="video"||s==="data")&&(o.kind=s);let a=kH(n);a&&(o.rt=a);let c=kH(i);return c&&(o.br=c),o}var poe=class{constructor(t,e,r,s,n){this._name=t,this._transport=e,this._streamData=r,this._controlDoc=s,this._onActivity=n,this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let t=this;return{[Symbol.asyncIterator](){let e=[...t._replay],r=null,s=!1,n=null,i={push(a){if(!s)if(r){let c=r;r=null,c.resolve({value:a,done:!1})}else e.push(a)},end(){if(s=!0,r){let a=r;r=null,a.resolve({value:void 0,done:!0})}}};t._messageConsumers.add(i);let o=()=>{s=!0,t._messageConsumers.delete(i)};return t._transport.mediaAvailability().then(a=>{if(!(a===null||s)&&(n=t._streamConsumeUnavailableError(a),o(),r)){let c=r;r=null,c.reject(n)}}),{next(){return e.length>0?Promise.resolve({value:e.shift(),done:!1}):n?Promise.reject(n):s?Promise.resolve({value:void 0,done:!0}):new Promise((a,c)=>{r={resolve:a,reject:c}})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let t=this._transport.mediaUnavailableReason();if(t)throw this._streamConsumeUnavailableError(t)}_streamConsumeUnavailableError(t){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${t}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,t=>this._deliver(t))))}_deliver(t){this._replay.push(t);for(let e of this._messageConsumers)e.push(t)}get track(){let t=this._transport.getTrackByName(this._name)??this._track;return t!==this._track&&this._setTrack(t),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(t,e){if(this._overrideTrack===t&&this._directOut===(e?.directOut??!1))return;this._overrideTrack=t,this._directOut=t?e?.directOut??!1:!1,t&&t.addEventListener?.("ended",()=>{this._overrideTrack===t&&this._setOverrideTrack(null)},{once:!0});let r=t??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let n of s)n(r)}_claimBrowserProducer(t){if(!this._controlDoc)return;let e=this._controlDoc(),r=foe(e,this._name),s=r?.br;if(s?.by==="runtime")throw new q1(this._name,"runtime","browser");if(s)return;let n={br:{epoch:1}};r?.rt&&(n.rt=r.rt);let i=r?.kind??t;i&&(n.kind=i),e.set({streams:{[this._name]:n}})}async attach(t){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(t,this._name)}async attachVideo(t){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(t,this._name)}async emit(t,e={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,t,e)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(t){if(t!=="live"&&(!Number.isFinite(t)||t<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,t)}chunks(t={}){let e=t.source??zI;return gie(e,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(t){return this._transport.on("seeked",(e,r)=>{e===this._name&&t(r)})}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let t of this._messageConsumers)t.end();this._messageConsumers.clear()}_setTrack(t){if(this._track=t,t&&t.addEventListener("ended",()=>{this._track===t&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let e=this._handlers.get("track");if(e)for(let r of e)r(t)}},oR=class GH{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new tH;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,r,s,n,i,o){this._sessionId=e,this._multiplexer=r,this._transport=s,this._recordingsAuth=n,this._artifactsAuth=i,this._streamData=XF(s),this._wireControlDocIncarnation(),this._lifecycleUnsub=HI(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=MI({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new FI({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(coe).awareness.setLocalState({role:"client"}),this._activation=new AI({onPhase:a=>this.onPhase(a),hint:()=>this.doc(EI).get(CI)??this.doc("control").get(TI),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",r=>{this._transport.applyControlDocState(r)})}static async attach(e,r){let s=await qF({baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,sessionId:e,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}),n=r.getAccessToken?await r.getAccessToken()??void 0:r.jwt,i=new JA,o=new aI({url:s.wsUrl,orgId:r.orgId,jwt:n,authProvider:r.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new GH(e,i,o,KH(r),vI({...r,baseUrl:s.baseUrl}),{activity:r.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),o.setEndsAt(s.endsAt),Qh()&&await K1();let c=r.getAccessToken,d=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:s.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return W1(this,e)}on(e,r){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(r),this._generationTickStop||(this._generationTickStop=OI(this.doc("control"),s=>{for(let n of Array.from(this._generationTickHandlers))try{n(s)}catch(i){S.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(r),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let r=new uv(e);return this._recordingsAccessor={list:s=>r.list(s??this._sessionId),get:s=>r.get(s),retain:(s,n)=>r.retain(s,n),pin:s=>r.pin(s),unpin:s=>r.unpin(s),permanent:s=>r.permanent(s),delete:s=>r.delete(s)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Rg(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,r)=>new Rg(this._requireArtifactsAuth()).getDownloadUrl(e,r??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e!==this._sessionId){this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let r=this._streams.get(e);return r||(r=new poe(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,r),this._activation.watch(e,r)),r}doc(e){let r=this._docs.get(e);return r||(r=new sH(e,this._sessionId,ooe.has(e)?null:this._docConnector.connect),this._docs.set(e,r)),r}get presence(){return this._presence||(this._presence=nH(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let r=cI(e.wsUrl),s=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${r}\0${s}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(eH({serverUrl:r,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,r={}){let s=xI(),n=new AbortController;r.signal&&(r.signal.aborted?n.abort(r.signal.reason):r.signal.addEventListener("abort",()=>n.abort(r.signal.reason),{once:!0}));let i=null;if(typeof r.timeout=="number"&&r.timeout>=0){let c=r.timeout;i=setTimeout(()=>n.abort(new F1(c,s)),c)}let o=this._consumeResponse(s,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,r,s,n,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(aoe),a=loe(e);return hoe(o,e,r,a,this._streamData.consumerId,s,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??iR)}requestStream(e,r={}){let s=xI();return this._consumeResponse(s,e,!0,r.signal,r.docSyncTimeout).deltas}complete(e,r={}){let s=xI(),n=this._consumeResponse(s,e,!1,r.signal,r.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(r){S.warn("[urun] session recovery hook failed:",r)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=ioe(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:r=>this._transport.on("phase",r)},onOverrideTrack:r=>this.stream("video")._setOverrideTrack(r),onOverrideAudioTrack:r=>this.stream("audio")._setOverrideTrack(r,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new El)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new El);let e=this._cancelHandler().then(r=>(this.disconnect(),r));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let r=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let n of r)try{n()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let s=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of s)try{n(new V1)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function moe(t){return`urun:session:v2:${t.orgId}:${t.app}:${t.functionName}`}function aR(){try{return globalThis.sessionStorage??null}catch{return null}}var cR=new Map;function SI(t){if(!t)return;let e=t.split(".");if(!(e.length<2))try{let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r+"=".repeat((4-r.length%4)%4)));return typeof s?.sub=="string"&&s.sub.length>0?s.sub:void 0}catch{return}}function goe(t,e){return t!==void 0&&e!==void 0&&t!==e}function AH(t,e){let r=aR(),s=null;if(r)try{let i=r.getItem(t);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(s={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{s=null}let n=cR.get(t)??s??null;return!n||goe(n.actor,e)?null:n}function yoe(t,e){let r={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};cR.set(t,r);let s=aR();if(s)try{s.setItem(t,JSON.stringify(r))}catch{}}function wI(t){cR.delete(t);let e=aR();if(e)try{e.removeItem(t)}catch{}}var IH=new Set(["paused","acquiring","live"]),boe=new Set(["24h","keep"]);function RH(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}function xoe(t){if(typeof t?.id!="string"||t.id.length===0)throw new Gi("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof t.state!="string"||!IH.has(t.state))throw new Gi(`[urun] session ${t.id} reported an unrecognized state ${JSON.stringify(t.state)} \u2014 this @urun-sh/core build knows only ${[...IH].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof t.recordings_expired=="boolean"?e=t.recordings_expired:S.warn(`[urun] session ${t.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:t.id,label:typeof t.label=="string"&&t.label.length>0?t.label:null,state:t.state,app:typeof t.app=="string"?t.app:"",functionName:typeof t.function=="string"?t.function:"",createdAt:RH(t.created_at),lastActiveAt:RH(t.last_active_at),archived:t.archived===!0,preview:typeof t.preview=="string"&&t.preview.length>0?t.preview:null,recordingsExpired:e,retention:boe.has(t.retention)?t.retention:(t.retention!==void 0&&S.warn(`[urun] session ${t.id} reported an unrecognized retention ${JSON.stringify(t.retention)} \u2014 defaulting to '24h'`),"24h")}}var dR=class{_request;_app;constructor(t,e){this._app=t,this._request=e}async list(t={}){let{rows:e,nextCursor:r}=await $F({...this._request,app:t.app??this._app,functionName:t.functionName,includeArchived:t.includeArchived,limit:t.limit,cursor:t.cursor});return{sessions:e.map(xoe),nextCursor:r}}async end(t){await FF({...this._request,sessionId:t})}async archive(t){await rI({...this._request,sessionId:t,archived:!0})}async unarchive(t){await rI({...this._request,sessionId:t,archived:!1})}async setName(t,e,r={}){await HF({...this._request,sessionId:t,name:e,source:r.source})}};function PH(t,e,r){let s=SI(r);yoe(t,s!==void 0?{sessionId:e,actor:s}:{sessionId:e})}var woe=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function XH(t,e){return new dR(t,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function YH(t,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(r,s){if(!(woe.has(s)||typeof s!="string"))return(n,i)=>{let o=n??{},a=moe({orgId:e.orgId,app:t,functionName:s}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,u=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=u(),h=e.jwt,p=e.getAccessToken?async X=>{let Z=await e.getAccessToken(X);return Z&&(h=Z),Z}:void 0,m={...e,getAccessToken:p},_=new JA,f=new aI({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:l,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new oR(l,_,f,KH(m),vI(m),{activity:i?.activity}),w,E=!1,O=!1,q,R,k=new Promise(X=>{R=X}),C,I=X=>{X.sessionId||q||(q="teardown",C="ticket",Eg({baseUrl:X.baseUrl,requestId:X.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},H=X=>{q||X.sessionId||(q="abandon",Eg({baseUrl:X.baseUrl,requestId:X.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},W=X=>{let Z=X.sessionId||!d?X:{...X,sessionId:d};w=Z,R({status:"ready",handle:Z}),(O||q==="teardown")&&I(Z)};b.setEndHandler(async()=>{let X=w?{status:"ready",handle:w}:await k;if(X.status==="unavailable")throw new El("[urun] session allocation failed before a releasable request was created",{cause:X.cause});let Z=w??X.handle;return wI(a),q==="teardown"?Z.sessionId?{status:"paused",sessionId:Z.sessionId,reason:"client_ended"}:{status:"canceled",requestId:Z.requestId}:(q="end",Z.sessionId?tI({baseUrl:Z.baseUrl,sessionId:Z.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider}):eI({baseUrl:Z.baseUrl,requestId:Z.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let X=w?{status:"ready",handle:w}:await k;if(X.status==="unavailable")throw new El("[urun] session allocation failed before a cancellable request was created",{cause:X.cause});let Z=w??X.handle;if(Z.sessionId)throw new Sn(`[urun] cancel() is for a queued admission request, but this call already has session ${Z.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:Z.sessionId,code:"cancel_on_live_session"});q="end";try{let P=await eI({baseUrl:Z.baseUrl,requestId:Z.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider});return wI(a),P}catch(P){throw q==="end"&&(q=void 0),P}});let J=async X=>{let Z,P=i?.sessionId??e.sessionKey??d,M,Y;if(P===void 0&&!c){let Fe=AH(a);if(Fe?.sessionId){if(Y=SI(h),Fe.actor!==void 0&&Y===void 0&&p){let nt=await Promise.resolve(p()).catch(()=>{});Y=SI(nt??e.jwt)}M=Fe.actor!==void 0&&Y!==void 0&&Fe.actor!==Y?void 0:Fe.sessionId}}let j=P??M,z=(Fe,nt)=>jF({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:t,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:p,authProvider:e.authProvider,idempotencyKey:Fe,sessionKey:nt,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:vt=>{f.reportAdmission(vt),vt.sessionId&&!d&&(d=vt.sessionId,Z=vt.sessionId,w&&w.sessionId!==vt.sessionId&&W({...w,sessionId:vt.sessionId}),E||(e.sessionKey||PH(a,vt.sessionId,h),b.setSessionId(vt.sessionId)))},onRequest:W}),se;try{se=await z(X,j)}catch(Fe){if(M===void 0||!(Fe instanceof Cr)||Fe.code!=="session_name_not_yours")throw Fe;S.warn(`[urun] session_name_not_yours: the control plane refused session ${M} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),AH(a,Y)?.sessionId===M&&wI(a),se=await z(u(),void 0)}let de=p?await p()??void 0:e.jwt;if(Z&&Z!==se.sessionId)throw w&&w.sessionId!==se.sessionId&&W({...w,sessionId:se.sessionId}),new Cr(`Gateway contract violation: admission minted session ${Z} but allocation completed as ${se.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=se.sessionId,w&&w.sessionId!==se.sessionId&&W({...w,sessionId:se.sessionId}),E||(e.sessionKey||PH(a,se.sessionId,h),b.setSessionId(se.sessionId),b.setArtifactsAuth(vI({...m,baseUrl:se.baseUrl})),f.setEndsAt(se.endsAt),f.seedRegion(sI(se.response))),{url:se.wsUrl,sessionId:se.sessionId,jwt:de,iceServers:se.response.ice_servers,endsAt:se.endsAt}},F,V=0,Q=p?async()=>{let X=V++>0;return await p(X?{forceRefresh:!0,reason:"background"}:void 0)??F}:()=>F,B=()=>{let X=f.connectedUrl;return X?cI(X):void 0};if(f.setConnectionResolver(async()=>{let X=await J(u());return F=X.jwt,X}),f.on("connected",()=>{f.multiplexer&&_.setTarget(f.multiplexer);let X=f.connectedUrl;X&&b.setDocTransport({wsUrl:X,token:Q,resolveServerUrl:B})}),(async X=>{let Z;try{Z=await J(X)}catch(P){if(E){R({status:"unavailable",cause:P});return}S.error(`[urun] Failed to create session for ${s}:`,P),w&&H(w);let M=P instanceof Error?P:new Error(String(P)),Y=P instanceof Cr?P.httpStatus:void 0,j=P instanceof Cr?P.code:void 0,z=P instanceof Cr?P.retryAfterSeconds:void 0;f.reportAllocationFailure(M,Y,j,z),R({status:"unavailable",cause:P});return}E||(f.setAuth({jwt:Z.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:Z.url,sessionId:Z.sessionId,iceServers:Z.iceServers}),Qh()&&await K1(),F=Z.jwt,b.setDocTransport({wsUrl:Z.url,token:Q,resolveServerUrl:B}),await f.connect({app:t,functionName:s,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(l).catch(X=>{S.error(`[urun] Failed to connect session for ${s}:`,X)}),e.releaseOnLeave!==!1){let X=qI(()=>{if(E=!0,f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let j=w;j?I(j):O=!0});b.onDisconnect(X);let Z,P,M=!1,Y=()=>{M||(M=!0,Z?.(),P?.())};k.then(j=>{j.status!=="ready"||M||(Z=VI(()=>w!==void 0))}),P=b.onPhase(j=>{let z=j?.name;(z==="paused"||z==="error")&&Y()}),M&&P(),b.onDisconnect(Y)}return b}}})}var WOe=globalThis.require??(0,rq.createRequire)(L),sq="https://api.urun.sh",nq="URUN_DEV";function voe(){if(typeof process>"u")return!1;let t=process.env?.[nq];if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"}var Bg=class extends Error{status;constructor(t,e){super(t),this.name="ClientTokenError",this.status=e}};async function _oe(t,e={}){if(!t)throw new Bg("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,s=Tr(e.baseUrl??sq),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??voe())&&(n.dev=!0);let i;try{i=await r(`${s}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(h){throw new Bg(`[urun] client token mint request failed: ${h instanceof Error?h.message:String(h)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let h=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new Bg(`[urun] client token mint failed: ${h}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,u=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Bg("[urun] client token mint returned no token (control-plane contract violation)",i.status);let l=Number.isFinite(d)?new Date(d):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var JH=3e4,QH="stream:",Soe=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(t,e){this._ws=t,this._multiplexer=e,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let n=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(n.timer),s.error?n.reject(new Error(s.error)):n.resolve(s.result)}})}async get(t){return this._sendRpc("store.get",{key:t})}async has(t){return await this._sendRpc("store.has",{key:t})}on(t,e){let r=`${QH}${t}`;return this._multiplexer.on(r,s=>{e(s)})}emit(t,e){let r=`${QH}${t}`,s=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{data:e};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(t,e){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let n=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(n)&&(this._pendingRpc.delete(n),s(new Error(`RPC request "${t}" timed out after ${JH}ms`)))},JH);this._pendingRpc.set(n,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:n,type:t,...e}))})}};function Eoe(t){let e=`${t.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(t.orgId)}`,r=new WebSocket(e);(t.jwt||t.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,apiKey:t.apiKey}))});let s=new YA(r);return new Soe(r,s)}var Coe='video/mp4; codecs="avc1.42E01E"';function Toe(t,e){let r=e?.codec??Coe,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(r)}catch(f){throw f instanceof DOMException&&f.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):f}let p=t.getReader();function m(){return h.updating?new Promise(f=>{h.addEventListener("updateend",()=>f(),{once:!0})}):Promise.resolve()}async function _(){try{for(;;){let{done:f,value:b}=await p.read();if(f){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{h.appendBuffer(b)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let E=h.buffered;if(E.length>0){let O=E.start(E.length-1);h.remove(0,O),await m(),h.appendBuffer(b)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}_()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),d=c.getTracks(),u=0,l=d.length;if(l===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of d)h.addEventListener("ended",()=>{u++,u>=l&&URL.revokeObjectURL(i)});return c}function koe(t){return t.status.startsWith("pending_")}var fv=class extends Error{status;code;constructor(t,e){super(t),this.name="CreditsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},fR=class extends fv{constructor(t="[urun] credits: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Aoe(t,e,r){let s=r||e||`HTTP ${t}`;return t===401?new fR(s,e??"unauthorized"):new fv(s,{status:t,code:e??`http_${t}`})}var iq=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let t=await this._request("GET","/balance");if(!t||typeof t!="object"||typeof t.org_id!="string")throw new fv("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return t}async getLedger(t={}){let e=(await this._request("GET","/ledger",{params:t.limit!==void 0?{limit:String(t.limit)}:void 0})).entries;return Array.isArray(e)?e:[]}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw Aoe(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(t,{method:e,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new fR("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function Ioe(t){return new iq(t)}var oq=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function ZH(t){let e=[];return t.audio&&e.push("audio"),t.video&&e.push("video"),e.join("+")}function Roe(t,e){return e==="audio"?t.getAudioTracks():t.getVideoTracks()}function Poe(t,e){let r=t.getTracks();if(r.length===1&&r[0]===e)return t;try{return new MediaStream([e])}catch{return t}}function lR(t,e){for(let r of[...t.lostListeners])try{r(e)}catch{}}var aq=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(t){this.injectedGetUserMedia=t?.getUserMedia}claim(t,e){return this.enqueue(async()=>{let r=this.claims.get(t);r&&(this.claims.delete(t),r.released=!0,r.track=null,r.stream=null,lR(r,new Error(`${t} capture claim superseded by a newer claim`)));let s=this.createState(t,e);return this.claims.set(t,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(t){let e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!t?.getUserMedia)throw new oq;return e=>t.getUserMedia(e)}async converge(t){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.stream=null);if(this.claims.size===0)return;let e=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await e(r)}catch(i){let o=`one-capture getUserMedia(${ZH(r)}) failed`,a=i instanceof Error?i.message:String(i);for(let c of[...this.claims.values()])if(this.claims.delete(c.kind),c.released=!0,c!==t){let d=new Error(`${o} \u2014 ${c.kind} capture lost: ${a||i}`);d.cause=i,lR(c,d)}throw i}let n=[...this.claims.values()].sort((i,o)=>i===t?1:o===t?-1:0);for(let i of n){let o=Roe(s,i.kind)[0]??null;if(i.released){o?.stop();continue}if(!o){this.claims.delete(i.kind),i.released=!0;let a=Object.assign(new Error(`one-capture getUserMedia(${ZH(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===t)throw a;lR(i,a);continue}if(i.track=o,i.stream=Poe(s,o),i!==t)for(let a of[...i.trackListeners])try{a(o,i.stream)}catch{}}}createState(t,e){let r=this,s={kind:t,constraints:e,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:t,get track(){return s.track},get stream(){return s.stream},update(n){return r.enqueue(async()=>{if(s.released)throw new Error(`${t} capture claim already released`);if(s.constraints=n,await r.converge(s),!s.track)throw new Error(`${t} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(t)===s&&r.claims.delete(t),s.track?.stop(),s.track=null,s.stream=null)},onTrack(n){return s.trackListeners.add(n),()=>s.trackListeners.delete(n)},onLost(n){return s.lostListeners.add(n),()=>s.lostListeners.delete(n)}}};return s}},Boe=null;function Doe(){return Boe??=new aq}var cq="input",Loe=30;function Ooe(t){let e=t.now??Date.now,r=t.field??cq,s=1e3/Math.max(t.hz??30,.001),n=new Set,i=0,o=0,a=0,c=0,d,u=null,l=!1,h=()=>{if(l)return;d=e(),c+=1;let m={keys:[...n],buttons:i,pointer:{x:o,y:a},seq:c,at:d};try{t.awareness.setLocalStateField(r,m)}catch{}},p=()=>{if(l)return;let m=e();if(d===void 0||m-d>=s){u&&(clearTimeout(u),u=null),h();return}if(u)return;let _=Math.max(s-(m-d),0);u=setTimeout(()=>{u=null,h()},_),u.unref?.()};return{keyDown(m){let _=String(m).toLowerCase();n.has(_)||(n.add(_),p())},keyUp(m){let _=String(m).toLowerCase();n.delete(_)&&p()},setButtons(m){let _=Number.isFinite(m)?Number(m):0;_!==i&&(i=_,p())},movePointer(m,_){let f=Number.isFinite(m)?Number(m):0,b=Number.isFinite(_)?Number(_):0;f===0&&b===0||(o+=f,a+=b,p())},heldKeys(){return[...n]},clear(){l||(n.clear(),i=0,u&&(clearTimeout(u),u=null),h())},dispose(){if(l)return;let m=n.size>0||i!==0;n.clear(),i=0,u&&(clearTimeout(u),u=null),m&&h(),l=!0}}}var Noe=1024,Uoe=.92,Moe=262144,joe=256e3,uR=[.9,.8,.7,.6,.5],eq=.8,$oe=8;function pR(t,e,r){if(!(t>0)||!(e>0))throw new Error(`reference image has no pixels (${t}x${e})`);let s=Math.min(1,r/Math.max(t,e));return{width:Math.max(1,Math.round(t*s)),height:Math.max(1,Math.round(e*s))}}async function Foe(t){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(t,{imageOrientation:"from-image"})}async function dq(t,e,r){let s=await new Promise(n=>{t.toBlob(n,e,e==="image/jpeg"?r:void 0)});if(!s)throw new Error(`could not encode the reference image as ${e}`);return s}function tq(t,e){S.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${t} -> ${e} bytes`)}async function hR(t,e,r,s,n){let i=document.createElement("canvas");i.width=e,i.height=r;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return s==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,r)),o.drawImage(t,0,0,e,r),await dq(i,s,n)}async function Hoe(t,e,r,s){let{width:n,height:i}=e,o=await hR(t,n,i,r,s);if(o.size<=256e3)return{blob:o,width:n,height:i};if(r==="image/jpeg"){for(let c of uR)if(!(c>=s)&&(o=await hR(t,n,i,r,c),o.size<=256e3))return tq(`quality ${s} -> ${c}`,o.size),{blob:o,width:n,height:i}}let a=r==="image/jpeg"?uR[uR.length-1]:s;for(let c=0;c<$oe;c++)if(n=Math.max(16,Math.round(n*eq)),i=Math.max(16,Math.round(i*eq)),o=await hR(t,n,i,r,a),o.size<=256e3)return tq(`downscaled to ${n}x${i} @ q${a}`,o.size),{blob:o,width:n,height:i};throw new Error(`this image cannot be sent: even at ${n}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function qoe(t,e){let{maxSize:r=1024,type:s="image/jpeg",quality:n=.92,source:i}=e,o=await Foe(t);try{let a=pR(o.width,o.height,r),c=await Hoe(o,a,s,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:s,width:c.width,height:c.height,source:i}}finally{o.close()}}function Voe(t){let e=t instanceof Error?t.name:"",r=t instanceof Error?t.message:String(t);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function zoe(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Woe(t,e){let r=t.videoWidth,s=t.videoHeight;if(!(r>0)||!(s>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=pR(r,s,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(t,0,0,a.width,a.height);let u=await dq(c,i,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Koe=new Set(["w","a","s","d"]),ef=(t,e)=>Math.min(e,Math.max(-e,t));function Goe(t={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:s=.18,decayTauMs:n=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=t,c=0,d=0,u=0,l=null,h=new Set;return{pointerDelta(p,m){c=ef(c-p*e,o),d=ef(d-m*e,o)},keyDown(p){let m=p.toLowerCase();Koe.has(m)&&h.add(m)},keyUp(p){h.delete(p.toLowerCase())},clearKeys(){h.clear()},frameArrived(){let p=1-i;c*=p,d*=p,u*=p},tick(p){if(l===null){l=p;return}let m=Math.max(0,Math.min(100,p-l))/1e3;l=p,h.has("w")&&(u=ef(u+r*m,a)),h.has("s")&&(u=ef(u-r*m,a)),h.has("a")&&(c=ef(c+s*m,o)),h.has("d")&&(c=ef(c-s*m,o));let _=Math.exp(-m*1e3/n);c*=_,d*=_,u*=_},transform(){return{translateX:c,translateY:d,scale:Math.exp(u)}},isIdentity(p=5e-4){return Math.abs(c)<p&&Math.abs(d)<p&&Math.abs(u)<p},reset(){c=0,d=0,u=0,h.clear()}}}g();y();var xq=require("@earendil-works/pi-ai"),tf=require("fs"),wq=require("path");g();y();g();y();g();y();g();y();function lq(t,e,r,s){let n=t.response??{},i={request_id:r,consumer_id:s,stream:!0,kind:"chat",messages:e};return typeof n.instructions=="string"&&(i.instructions=n.instructions),Array.isArray(n.modalities)&&(i.modalities=n.modalities),typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(i.max_output_tokens=n.max_output_tokens),n.tools!==void 0&&(i.tools=n.tools),i}function uq(t,e,r){let s={request_id:e,consumer_id:r,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(s.model=t.model),t.tools!==void 0&&(s.tools=t.tools),t.tool_choice!==void 0&&(s.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(s.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(s.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(s.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(s.stop=t.stop),typeof t.reasoning_effort=="string"&&(s.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(s.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(s.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(s.response_format=t.response_format),typeof t.voice=="string"&&(s.voice=t.voice),typeof t.language=="string"&&(s.language=t.language),s}g();y();g();y();function hq(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,r=e.body??{},s=r.error,n=s?.message??r.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:s?.type??"urun_error",code:e.code??s?.code??null,message:n}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Xoe="llm-resp";async function*gR(t,e){let r=`${Xoe}:${e}`,s=`resp_${e}`;yield{type:"response.created",response:{id:s,status:"in_progress"}};let n=new Map;try{for await(let i of t.stream(r).messages()){let o=i;if(o.t==="delta"){if(typeof o.delta=="string"&&(yield{type:"response.output_text.delta",item_id:s,delta:o.delta}),typeof o.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:s,delta:o.reasoning}),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let c=typeof a.index=="number"?a.index:0,d=n.get(c)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),n.set(c,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(o.t==="response"){yield{type:"response.completed",response:{id:s,status:"completed",...o.body}};return}else if(o.t==="error"){yield hq(o);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var mv=class t{constructor(e,r=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=r;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((n,i)=>{let o=e.onSynced(()=>{clearTimeout(r),n()});r=setTimeout(()=>{o(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){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,r){return this.writeGated(r,()=>{let s=uq(e,r,this.consumerId);return this.write(s),gR(this.session,r)})}sendResponseCreate(e,r,s){return this.writeGated(s,()=>{let n=lq(e,r,s,this.consumerId);return this.write(n),gR(this.session,s)})}async writeGated(e,r){try{await this.ensureDocSynced()}catch(s){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${s instanceof Error?s.message:String(s)}`)}return r()}};var fq=0;function Yoe(){return fq+=1,`req_${Date.now().toString(36)}_${fq.toString(36)}`}var gv=class{transport;constructor(e){this.transport=new mv(e)}responses={create:async e=>{let r=Yoe(),s=await this.transport.sendResponses(e,r);return Object.assign((async function*(){yield*s})(),{requestId:r})}}};Tv();g();y();g();y();g();y();g();y();g();y();g();y();g();y();var yR="https://api.urun.sh/v1";async function pq(t){let e=t.fetchImpl??fetch,r=`${t.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(r,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${r} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${r})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${r} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}async function mq(t){let e=await pq(t),r=e.filter(s=>s.function_name===t.fnName&&s.deployment_status==="active").map(s=>s.app_slug);if(r.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return r.sort()}var xR="urun-serve",eae="serve",tae=131072,rae=16384,gq=3,sae=42e4,nae=6e4,yq=2,iae=15e3;function oae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||yR,fnName:(t.URUN_FUNCTION??"").trim()||eae}}function vq(t){let e=(t.URUN_BASE_URL??"").trim(),r=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!r)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let s=(t.URUN_JWT??"").trim();if(s)return{baseUrl:e,orgId:r,auth:{lane:"jwt",jwt:s}};let n=(t.URUN_API_KEY??"").trim();if(!n)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:r,auth:{lane:"api-key",apiKey:n,gatewayUrl:i}}}function _q(t){let e=null;return r=>{e===null&&((0,tf.mkdirSync)((0,wq.dirname)(t),{recursive:!0}),e=(0,tf.openSync)(t,"a"));let s=r.detail?` ${JSON.stringify(r.detail)}`:"";(0,tf.writeSync)(e,`${new Date().toISOString()} [${r.level}] [urun] ${r.message}${s}
176
176
  `)}}function xv(t){let e=_q(Mg());return async(r,s,n)=>{let{baseUrl:i,orgId:o,auth:a}=vq(r),{App:c,createClientToken:d}=await t(),l=(a.lane==="jwt"?c(s,{baseUrl:i,orgId:o,jwt:a.jwt,diagnosticSink:e}):c(s,{baseUrl:i,orgId:o,diagnosticSink:e,getAccessToken:async()=>(await d(a.apiKey,{baseUrl:a.gatewayUrl,expiresIn:300,allowedFunctions:[`${s}/${n}`]})).token}))[n];if(typeof l!="function")throw new Error(`urun pi extension: app "${s}" has no function "${n}"`);let h=l();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${s}" function "${n}" returned a session without end()`);let p=h.connect;return typeof p=="function"&&await p.call(h),h}}var aae=xv(async()=>{let{createRequire:t}=await import("module"),e=t(L);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function cae(t,e){try{return Promise.resolve(t.end()).then(()=>{},r=>e(r))}catch(r){return e(r),Promise.resolve()}}function dae(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let r=e.indexOf("--mode");return r!==-1&&(e[r+1]==="json"||e[r+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function Sq(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var yv=class{constructor(e,r,s,n=(i,o)=>S.warn(Sq(i,o))){this.open=e;this.env=r;this.fnName=s;this.onReleaseError=n}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let r=this.pool.get(e);if(!r){let s=Promise.resolve(this.open(this.env,e,this.fnName)).then(n=>({session:n,responses:new gv(n)}));r=s,this.pool.set(e,s),s.catch(()=>{this.pool.get(e)===s&&this.pool.delete(e)})}return r}evict(e){let r=this.pool.get(e);if(!r)return Promise.resolve();this.pool.delete(e);let s=r.then(n=>cae(n.session,i=>this.onReleaseError(e,i)),()=>{});return this.releasing.add(s),s.then(()=>this.releasing.delete(s)),s}closeAll(){let e=[...this.pool.keys()].map(r=>this.evict(r));return Promise.all([...e,...this.releasing]).then(()=>{})}};function Eq(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let r of t.messages){if(r.role==="toolResult"){e.push({type:"function_call_output",call_id:r.toolCallId,output:uae(r.content)});continue}if(r.role==="assistant"&&Array.isArray(r.content)){let n="",i=()=>{n&&(e.push({role:"assistant",content:n}),n="")};for(let o of r.content)if(o.type==="text")n+=String(o.text??"");else if(o.type==="toolCall")i(),e.push({type:"function_call",call_id:String(o.id??""),name:String(o.name??""),arguments:JSON.stringify(o.arguments??{})});else{if(o.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(o.type)}"`)}i();continue}let s=r.role==="assistant"?"assistant":"user";e.push({role:s,content:lae(r.content)})}return Cq(e)}function Cq(t){let e=[];for(let r of t){let s=e[e.length-1];s&&"role"in s&&"role"in r&&s.role===r.role?s.content=[s.content,r.content].filter(n=>n.length>0).join(`
177
177
 
178
178
  `):e.push({...r})}return e}function lae(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e?String(e.text):"").join(""):""}function uae(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e="";for(let r of t){let s=String(r.type??"");if(s!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${s}" \u2014 the serve lane carries text tool results only`);e+=String(r.text??"")}return e}function hae(t){if(!(!Array.isArray(t)||t.length===0))return t.map(e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))}function bq(t,e){if(!e.trim())return{};try{return JSON.parse(e)}catch{throw new Error(`uRun serve error: tool call "${t}" arguments are not valid JSON: ${e}`)}}function fae(t){let e=t?.output;return Array.isArray(e)?e.filter(r=>r.type==="function_call"):[]}function Tq(t,e){let r=e?.usage;if(!r||typeof r!="object")return;let s=typeof r.input_tokens=="number"?r.input_tokens:void 0,n=typeof r.output_tokens=="number"?r.output_tokens:void 0;s===void 0||n===void 0||(t.input=s,t.output=n,t.totalTokens=typeof r.total_tokens=="number"?r.total_tokens:s+n)}function pae(t){let e=t?.output;if(!Array.isArray(e))return"";let r="";for(let s of e)if(!(s.type!=="reasoning"||!Array.isArray(s.content)))for(let n of s.content)n.type==="reasoning_text"&&(r+=String(n.text??""));return r}var mae=["<tool_call>","<function="];function gae(t,e){let r=mae.find(s=>e.includes(s));if(r)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(r)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`)}var bv=class extends Error{};function yae(t){let e=t instanceof Error?t.message:String(t),r=t?.code;return/\b529\b/.test(e)||/overloaded/i.test(e)||r===529||r==="529"}function bae(t){return new Promise(e=>setTimeout(e,t))}function xae(t,e,r,s){return new Promise((n,i)=>{let o=!1,a=u=>{o||(o=!0,clearTimeout(c),s?.removeEventListener("abort",d),u())},c=setTimeout(()=>a(()=>i(r())),e),d=()=>a(()=>i(new Error("aborted")));if(s?.aborted){d();return}s?.addEventListener("abort",d,{once:!0}),Promise.resolve(t).then(u=>a(()=>n(u)),u=>a(()=>i(u)))})}async function*wae(t,e){let r=t[Symbol.asyncIterator](),s,n=new Promise((i,o)=>{s=()=>o(new Error("aborted")),e.addEventListener("abort",s,{once:!0})});try{for(;;){if(e.aborted)throw new Error("aborted");let i=await Promise.race([r.next(),n]);if(i.done)return;yield i.value}}finally{s&&e.removeEventListener("abort",s),r.return?.(void 0)}}function bR(t,e){if(t?.hasUI===!1){Cv(`${e}
@@ -15,7 +15,7 @@ Connection: close\r
15
15
  Content-Type: text/plain; charset=utf-8\r
16
16
  Content-Length: ${Buffer.byteLength(o)}\r
17
17
  \r
18
- ${o}`)}function zo(t,e){let n=new Ee.WebSocketServer({noServer:!0,maxPayload:eu}),r=new Me,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,m)=>{let f;try{f=new URL(l.url??"/","http://localhost")}catch{Vt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==Za){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Vt(c,401,"invalid local proxy api key");return}let y;try{y=await a(l)}catch(g){let _=e.statusOf?.(g)??null;Vt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(l,c,m,g=>{s.delete(c),o.add(g),g.on("close",()=>o.delete(g));try{new Nn(g,y,r,e.statusOf)}catch{o.delete(g),g.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Vt(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Dn();if(u)return c(),l;u=!0,t.off("upgrade",d);for(let f of s)f.destroy();s.clear();for(let f of i)f.destroy();i.clear();for(let f of o)f.close(1001,"server shutting down");let m=setTimeout(()=>{for(let f of o)f.readyState!==Ee.WebSocket.CLOSED&&f.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),c()}),l}}}var ks=require("@urun-sh/core");var Yo=require("@urun-sh/core"),iu={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},au={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; 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:"admission is momentarily contended (lock convoy) \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 Fn(t,e){let n=au[t.code];return e?`${n} (${e})`:n}function Jt(t){if(t==null)return null;let e=iu[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 Wt(t){if(t.kind==="create-failed")return Jt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Yo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Jt(e?"cold_start_exceeded":"queue_timeout")}var Qo=qe(require("os"),1),Zo=qe(require("path"),1),es=require("url"),ts=require("util");var Xo="0.6.29";var ns=4141,du=Xo,zt={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function jn(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function rs(t,e,n){let r={...t,...jn(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function os(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function ss(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function is(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function as(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=(0,es.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function us(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function ds(t){if(t[0]!=="--port")return null;let e=us(t[1]);return t.splice(0,2),e}function Gn(t){let e=t.indexOf("--port");if(e===-1)return ns;let n=us(t[e+1]);return t.splice(e,2),n}function ls(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function Bn(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Ye(t){let e=lu(Bn(t,"URUN_BASE_URL")),n=Bn(t,"URUN_ORG_ID"),r=Bn(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Kt(s,"URUN_API_URL"):to,a=(t.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(t.URUN_API_KEY??"").trim();if(u){let d=(t.URUN_GATEWAY_URL??"").trim(),l=d?Kt(d):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function lu(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 Kt(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function Hn(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:du}}function cu(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var pu=250;async function Vn(t,e=pu){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var cs=2e3;async function fu(t,e=cs){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ps(t,e,n=ns,r=cs){if(t!=null)return{mode:"spawn",port:t};let o=await Vn(n);if(o!==null&&cu(o,e)){let s=await fu(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function Jn(t,e=Qo.default.homedir()){return Zo.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var qn=["log","info","warn","error","debug","trace"];function fs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(qn.map(a=>[a,n[a]]));for(let a of qn)n[a]=(...u)=>{t.write(`${(0,ts.format)(...u)}
18
+ ${o}`)}function zo(t,e){let n=new Ee.WebSocketServer({noServer:!0,maxPayload:eu}),r=new Me,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,m)=>{let f;try{f=new URL(l.url??"/","http://localhost")}catch{Vt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==Za){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Vt(c,401,"invalid local proxy api key");return}let y;try{y=await a(l)}catch(g){let _=e.statusOf?.(g)??null;Vt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(l,c,m,g=>{s.delete(c),o.add(g),g.on("close",()=>o.delete(g));try{new Nn(g,y,r,e.statusOf)}catch{o.delete(g),g.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Vt(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Dn();if(u)return c(),l;u=!0,t.off("upgrade",d);for(let f of s)f.destroy();s.clear();for(let f of i)f.destroy();i.clear();for(let f of o)f.close(1001,"server shutting down");let m=setTimeout(()=>{for(let f of o)f.readyState!==Ee.WebSocket.CLOSED&&f.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),c()}),l}}}var ks=require("@urun-sh/core");var Yo=require("@urun-sh/core"),iu={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},au={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; 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:"admission is momentarily contended (lock convoy) \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 Fn(t,e){let n=au[t.code];return e?`${n} (${e})`:n}function Jt(t){if(t==null)return null;let e=iu[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 Wt(t){if(t.kind==="create-failed")return Jt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Yo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Jt(e?"cold_start_exceeded":"queue_timeout")}var Qo=qe(require("os"),1),Zo=qe(require("path"),1),es=require("url"),ts=require("util");var Xo="0.6.30";var ns=4141,du=Xo,zt={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function jn(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function rs(t,e,n){let r={...t,...jn(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function os(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function ss(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function is(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function as(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=(0,es.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function us(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function ds(t){if(t[0]!=="--port")return null;let e=us(t[1]);return t.splice(0,2),e}function Gn(t){let e=t.indexOf("--port");if(e===-1)return ns;let n=us(t[e+1]);return t.splice(e,2),n}function ls(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function Bn(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Ye(t){let e=lu(Bn(t,"URUN_BASE_URL")),n=Bn(t,"URUN_ORG_ID"),r=Bn(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Kt(s,"URUN_API_URL"):to,a=(t.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(t.URUN_API_KEY??"").trim();if(u){let d=(t.URUN_GATEWAY_URL??"").trim(),l=d?Kt(d):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function lu(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 Kt(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function Hn(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:du}}function cu(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var pu=250;async function Vn(t,e=pu){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var cs=2e3;async function fu(t,e=cs){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ps(t,e,n=ns,r=cs){if(t!=null)return{mode:"spawn",port:t};let o=await Vn(n);if(o!==null&&cu(o,e)){let s=await fu(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function Jn(t,e=Qo.default.homedir()){return Zo.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var qn=["log","info","warn","error","debug","trace"];function fs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(qn.map(a=>[a,n[a]]));for(let a of qn)n[a]=(...u)=>{t.write(`${(0,ts.format)(...u)}
19
19
  `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of qn)n[a]=i[a]}}var mu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ms(t){let e=t?.code;return typeof e=="string"&&mu.has(e)}function le(t,e){try{return t.write(e),!0}catch(n){if(ms(n))return!1;throw n}}function gs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{ms(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
20
20
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function hs(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
21
21
  `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as J,b as q,c as H,d as Y,e as V}from"../chunk-7E2KNW2C.js";import"../chunk-K23AZPI4.js";import{A as F,Y as K,f as v,g as $,h as C,i as U,j as I,k as L,l as N,m as O,n as x,o as _,p as g,r as G,s as P,t as D,u as M,v as A,w as W,x as b,y as B,z as j}from"../chunk-RUJPI6BV.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
2
+ import{a as J,b as q,c as H,d as Y,e as V}from"../chunk-OPMTYD3Z.js";import"../chunk-K23AZPI4.js";import{A as F,Y as K,f as v,g as $,h as C,i as U,j as I,k as L,l as N,m as O,n as x,o as _,p as g,r as G,s as P,t as D,u as M,v as A,w as W,x as b,y as B,z as j}from"../chunk-55LV3IXW.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
3
3
  `),null):{catalogUrl:l,anonKey:s}}function me(e){let i={baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:fe(n.env,l=>n.stderr.write(l)),decisionPool:J(n.env,n.env.HOSTNAME)??void 0},t=H(i);return{router:t,decision:i.decisionPool?Y(i,t):null}}async function Q(e,i,t){let l=ee(e,i,{stdio:"inherit",env:t});return new Promise(s=>{l.once("exit",r=>s(r??1)),l.once("error",r=>{n.stderr.write(`failed to launch ${e}: ${String(r)}
4
4
  `),s(127)})})}function X(){return N(n.env,import.meta.url,pe)}function te(e){for(let[i,t]of Object.entries($(e)))n.stdout.write(`export ${i}=${t}
5
5
  `)}async function Z(e,i){let t=g(n.env),l=i?P(t):void 0,{router:s,decision:r}=me(t);r&&(r.boot().then(()=>r.reap()).catch(u=>n.stderr.write(`[decision-pool] boot FAILED: ${String(u instanceof Error?u.message:u)}
@@ -1 +1 @@
1
- import{B as l,C as a,D as x,E as s,G as O,H as f,Y as I,a as n,b as p,c as m}from"../chunk-RUJPI6BV.js";import{f as r,g as i}from"../chunk-CUDFHFNX.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
1
+ import{B as l,C as a,D as x,E as s,G as O,H as f,Y as I,a as n,b as p,c as m}from"../chunk-55LV3IXW.js";import{f as r,g as i}from"../chunk-CUDFHFNX.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.29",
3
+ "version": "0.6.30",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",