@urun-sh/openai 0.6.25 → 0.6.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-PPPJ42Z7.js → chunk-4MQCXL73.js} +1 -1
- package/dist/{chunk-SOAZAPCO.js → chunk-BGAV27A5.js} +2 -2
- package/dist/chunk-VHWL6HP5.js +8 -0
- package/dist/hosted/bin.cjs +28 -27
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +31 -30
- package/dist/hosted/index.d.cts +77 -22
- package/dist/hosted/index.d.ts +13 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +54 -54
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +1 -1
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-C0PBaF29.d.cts → responses-turn-BFURb0jK.d.cts} +16 -3
- package/dist/{responses-turn-2UJImii3.d.ts → responses-turn-Cxfv-oXb.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-VY333OKA.js +0 -7
package/dist/proxy/cli.cjs
CHANGED
|
@@ -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 Ko(t,e){let n=new Re.WebSocketServer({noServer:!0,maxPayload:Za}),r=new Ce,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,d=(l,c,h)=>{let f;try{f=new URL(l.url??"/","http://localhost")}catch{Ht(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==Qa){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ht(c,401,"invalid local proxy api key");return}let _;try{_=await u(l)}catch(m){let y=e.statusOf?.(m)??null;Ht(c,y?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(p=!0,n.handleUpgrade(l,c,h,m=>{s.delete(c),o.add(m),m.on("close",()=>o.delete(m));try{new Un(m,_,r,e.statusOf)}catch{o.delete(m),m.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Ht(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Nn();if(a)return c(),l;a=!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 h=setTimeout(()=>{for(let f of o)f.readyState!==Re.WebSocket.CLOSED&&f.terminate()},2e3);return h.unref?.(),n.close(()=>{clearTimeout(h),c()}),l}}}var Ss=require("@urun-sh/core");var zo=require("@urun-sh/core"),su={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},iu={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 Dn(t,e){let n=iu[t.code];return e?`${n} (${e})`:n}function Vt(t){if(t==null)return null;let e=su[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 Jt(t){if(t.kind==="create-failed")return Vt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=zo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Vt(e?"cold_start_exceeded":"queue_timeout")}var Xo=Be(require("os"),1),Qo=Be(require("path"),1),Zo=require("url"),es=require("util");var Yo="0.6.
|
|
18
|
+
${o}`)}function Ko(t,e){let n=new Re.WebSocketServer({noServer:!0,maxPayload:Za}),r=new Ce,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,d=(l,c,h)=>{let f;try{f=new URL(l.url??"/","http://localhost")}catch{Ht(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==Qa){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ht(c,401,"invalid local proxy api key");return}let _;try{_=await u(l)}catch(m){let y=e.statusOf?.(m)??null;Ht(c,y?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(p=!0,n.handleUpgrade(l,c,h,m=>{s.delete(c),o.add(m),m.on("close",()=>o.delete(m));try{new Un(m,_,r,e.statusOf)}catch{o.delete(m),m.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Ht(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Nn();if(a)return c(),l;a=!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 h=setTimeout(()=>{for(let f of o)f.readyState!==Re.WebSocket.CLOSED&&f.terminate()},2e3);return h.unref?.(),n.close(()=>{clearTimeout(h),c()}),l}}}var Ss=require("@urun-sh/core");var zo=require("@urun-sh/core"),su={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},iu={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 Dn(t,e){let n=iu[t.code];return e?`${n} (${e})`:n}function Vt(t){if(t==null)return null;let e=su[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 Jt(t){if(t.kind==="create-failed")return Vt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=zo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Vt(e?"cold_start_exceeded":"queue_timeout")}var Xo=Be(require("os"),1),Qo=Be(require("path"),1),Zo=require("url"),es=require("util");var Yo="0.6.27";var ts=4141,uu=Yo,Kt={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 qn(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 ns(t,e,n){let r={...t,...qn(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function rs(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=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),d=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function os(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ss(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function is(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,Zo.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 as(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 us(t){if(t[0]!=="--port")return null;let e=as(t[1]);return t.splice(0,2),e}function jn(t){let e=t.indexOf("--port");if(e===-1)return ts;let n=as(t[e+1]);return t.splice(e,2),n}function ds(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 Fn(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 ze(t){let e=du(Fn(t,"URUN_BASE_URL")),n=Fn(t,"URUN_ORG_ID"),r=Fn(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Wt(s,"URUN_API_URL"):eo,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let d=(t.URUN_GATEWAY_URL??"").trim(),l=d?Wt(d):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,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 du(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 Wt(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 Gn(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:uu}}function lu(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 cu=250;async function Hn(t,e=cu){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var ls=2e3;async function pu(t,e=ls){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 cs(t,e,n=ts,r=ls){if(t!=null)return{mode:"spawn",port:t};let o=await Hn(n);if(o!==null&&lu(o,e)){let s=await pu(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 Vn(t,e=Xo.default.homedir()){return Qo.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Bn=["log","info","warn","error","debug","trace"];function ps(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Bn.map(u=>[u,n[u]]));for(let u of Bn)n[u]=(...a)=>{t.write(`${(0,es.format)(...a)}
|
|
19
19
|
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Bn)n[u]=i[u]}}var fu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function fs(t){let e=t?.code;return typeof e=="string"&&fu.has(e)}function le(t,e){try{return t.write(e),!0}catch(n){if(fs(n))return!1;throw n}}function ms(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{fs(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
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 gs(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}
|
|
@@ -26,7 +26,7 @@ Content-Type: text/plain\r
|
|
|
26
26
|
\r
|
|
27
27
|
${Su(n)}\r
|
|
28
28
|
`),t.destroy()}function xu(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
29
|
-
`}function Ru(t){le(process.stdout,t)}function Eu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Xn(t){return t.audioSession?.audio.sessionId??void 0}function Zn(t,e){let n=new ks.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Qn)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=R("rtup"),d=Eu(o),l=b=>{(e.log??Ru)(xu(b))};l({stage:"accept",conn:a,model:d}),s.resume();let c=new AbortController,h=null,f=b=>{h??=b,c.abort(new Error(h))},p=()=>f("client socket closed"),_=()=>f("client socket closed (half-close)"),m=b=>f(`client socket error: ${b.message}`);s.once("close",p),s.once("end",_),s.once("error",m);let y=()=>{s.removeListener("close",p),s.removeListener("end",_),s.removeListener("error",m)},g=b=>{l({stage:"close",conn:a,model:d,...b})},v=b=>{let w=b,k=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!k&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((x,I)=>{n.handleUpgrade(o,s,i,L=>{try{new pt({ws:L,binding:b,onClosed:(F,Y)=>{g({while:"live",reason:Y.reason})}}),l({stage:"admit",conn:a,model:d,...Xn(b)===void 0?{}:{session:Xn(b)}}),x()}catch(F){I(F)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){y();let w=Xn(b);try{await b.release?.()}catch(k){g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",released:!0}),s.destroy();return}y(),await v(b)}).catch(b=>{let w=b instanceof Ss.SessionFailedError?Jt(b):null,k=null;if(b!==null&&typeof b=="object"&&"status"in b){let I=b.status;typeof I=="number"&&(k=I)}let M=k??w?.status??502,x=b instanceof Error?b.message:String(b);g({while:"queued",...c.signal.aborted?{reason:h??"client socket closed"}:{reason:x,status:M}}),s.destroyed||ku(s,M,x)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var ce=(t,e)=>Object.assign(new Error(e),{status:t});function Au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ou='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tu(t,e,n,r){if(!t.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof N?ce(404,d.message):d}if(!o)throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof N?ce(404,d.message):d}if(s&&!t.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?ce(404,l.message):l}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ou}`);if(r==="transcription"&&!s)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i=await t.sessionHandle(e),u={audio:await t.openAudioOn(i,n)},a={clients:{createResponse:async d=>await t.createResponseOn(i,d)},voice:o,audioSession:u};return s&&(a.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(a.intent="transcription"),e!==void 0&&(a.model=e),a}function xs(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw ce(401,"invalid local proxy api key")}return Tu(t,Au(n),r,Iu(n))}}}var X=class extends Error{};async function Zt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function en(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new X(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Rs="/v1/images/generations",tn="/v1/images/edits";function Es(t){return t===Rs||t===tn}var As="/v1/images/models";async function Is(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Pu=16*1024*1024,Os=64*1024*1024;function Ts(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function ft(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Ps(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let c of o){if(c.type==="error"){let h=c.error??{};throw new $(502,`image upstream error: ${String(h.message??"upstream reported an error")}`)}if(c.type==="response.completed"){s=c.response??null;break}}if(s===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let u=[],a=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(a,"base64");if(Ts(d)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return u.push(a),{images:u}}function Cs(t){return t instanceof $?t:t instanceof N?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ms(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return ft(r,new $(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ls(t,e){t&&(t.outputUnits=e.images.length)}function $s(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Cu={model:!0,prompt:!0,response_format:!0,n:!0};async function Us(t,e,n){let r=n.maxBodyBytes??Os;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Rs}`);let o;try{o=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof X?new $(413,c.message):new $(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new $(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!Cu[c])throw new $(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new $(400,"model must be a string","model");await Is(n.turn,n.clients,u);let a=s.n??1;if(a!==1)throw new $(400,`n=${JSON.stringify(a)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new $(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Ms(n.imageModels,u,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await Ps(n.clients,u,l,n.turn?ae(n.turn):void 0);Ls(n.turn,c),$s(e,c)}catch(c){throw Cs(c)}}catch(o){if(o instanceof X){ft(e,new $(413,o.message));return}if(o instanceof $){ft(e,o);return}throw o}}var Mu={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ns(t,e,n){let r=n.maxBodyBytes??Os,o=n.maxImagePartBytes??Pu;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(f){throw f instanceof X?new $(413,f.message):new $(400,String(f instanceof Error?f.message:f))}let u=i.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let a=i.get("model");if(a!==null&&typeof a!="string")throw new $(400,"model must be a string field","model");let d=a===null?void 0:a;await Is(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new $(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of i.keys())if(!Mu[f])throw new $(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of i.getAll(f)){if(!(p instanceof File))throw new $(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let _=new Uint8Array(await p.arrayBuffer()),m=Ts(_);if(m===null)throw new $(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:_,mime:m})}if(c.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Ms(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:f,mime:p}of c)h.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Ps(n.clients,d,h,n.turn?ae(n.turn):void 0);Ls(n.turn,f),$s(e,f)}catch(f){throw Cs(f)}}catch(s){if(s instanceof X){ft(e,new $(413,s.message));return}if(s instanceof $){ft(e,s);return}throw s}}var mt="/v1/audio/speech";function Js(t){return t===mt}var Ds=4096,Fs=18e4,Bs=5e3,Lu=64*1024*1024,qs=8,js=5,Gs=1024*1024,Xe="voice_applied",rn="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function er(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var on=class extends P{constructor(e){super(502,e)}};function Ws(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ks(t){return new P(502,`the runtime's ${Xe} receipt ${JSON.stringify(t)} cannot be relayed as the ${rn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function $u(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function zs(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Uu=2;function Nu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Uu)return!1;return!0}function Du(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Hs=new WeakMap,nn=new WeakMap;function Fu(t,e){let n=nn.get(t)??0;if(n>=qs)throw new P(503,`this model's speech queue is full \u2014 ${qs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${js}s`,void 0,js);nn.set(t,n+1);let r=Hs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Hs.set(t,s),(async()=>{await r;try{return await e()}finally{nn.set(t,(nn.get(t)??1)-1),o()}})()}async function Bu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof J))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Ue(t){return t instanceof P?t:t instanceof N?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Vs(t,e,n,r,o,s,i,u){let a=u??(()=>{});return Fu(e,async()=>{if(i?.()===!0)return null;let d=!1,l=!1,c=!1,h,f=new Promise(b=>{h=b}),p=[],_=()=>{l&&!c&&p.length>=o.quietRunFrames&&(c=!0,h())},m=e.onOutputAudio(b=>{let w=Buffer.from(b,"base64");if(w.byteLength===0)return;let k=Nu(w);if(!d){if(k)return;d=!0}if(k){p.push(w),_();return}for(let M of p)a(M);p.length=0,a(w),_()}),y=null,g,v,E;try{E=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let w=new Promise(x=>{v=setTimeout(x,s.capMs)}),k=!1;for(;;){let x=E.next(),I=await Promise.race([x,w]);if(I===void 0){k=!0,x.catch(()=>{});break}if(I.done)break;let L=I.value;if(L.type==="error"){let F=L.error??{};throw await E.return?.(),new P(502,`speech upstream error: ${String(F.message??"upstream reported an error")}`)}if(L.type==="response.completed"){y=L.response??null,l=!0,_(),await E.return?.();break}}if(clearTimeout(v),k)throw new P(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(y===null)throw new P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let M=!1;if(await Promise.race([f,new Promise(x=>{g=setTimeout(()=>{M=!0,x()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let x=y[Xe];if(typeof x!="string"||x!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${Xe} ${JSON.stringify(x)}`:`no ${Xe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new on(I):new P(502,I)}}if(!d)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(M&&!c&&p.length<1)throw new P(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(b){throw b instanceof on||await Bu(t,n,E,s.returnBoundMs),b}finally{g!==void 0&&clearTimeout(g),v!==void 0&&clearTimeout(v),m()}})}function qu(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",rn)),t.write(u,a=>{a||(s+=u.byteLength,zs(e,s))}),t.writableLength>Gs&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Gs} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[Xe];if(typeof a=="string"){if(!Ws(a))throw Ks(a);t.addTrailers({[rn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function ju(t,e,n){let r;try{r=await t(e)}catch(o){throw Ue(o)}return r?!0:(er(n,new P(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Gu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hu="wav, pcm";async function Ys(t,e,n){let r=n.maxBodyBytes??Lu,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${mt}`);let i;try{i=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(v){throw v instanceof X?new P(413,v.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let u=i;for(let v of Object.keys(u))if(!Gu[v])throw new P(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let a=u.input;if(typeof a!="string"||a.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(a.length>Ds)throw new P(400,`input is ${a.length} chars \u2014 over the ${Ds}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new P(400,"model must be a string","model");let l=u.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${mt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(d)}catch(v){throw Ue(v)}if(c.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof l=="string"?l:void 0;if(h!==void 0&&c.published.length>0&&!c.published.includes(h))throw new P(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new P(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hu} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new P(400,"stream_format, when present, must be a string","stream_format");let p=u.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new P(400,"speed, when present, must be a number","speed");if(p!==1)throw new P(400,`speed=${JSON.stringify(p)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let _=u.instructions;if(_!==void 0){if(typeof _!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(_.trim().length>0)throw new P(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await $u(n.turn,n.clients,d);let m=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",m,m),!await ju(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new P(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw Ue(v)}let g;try{g=await n.clients.openAudioOn(y)}catch(v){throw Ue(v)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(f==="wav"){let v=[],E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,w=>v.push(w));if(E===null||s())return;let b=Buffer.concat(v);if(h===void 0){let w=E[Xe];if(typeof w=="string"){if(!Ws(w))throw Ks(w);e.setHeader(rn,w)}}zs(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Du(b.byteLength),b]))}else{let v=qu(e,n.turn,s,h===void 0),E;try{E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,v.sink)}catch(b){let w=Ue(b);if(!v.started())throw w;n.turn&&(n.turn.streamError=!0),v.fail(w);return}if(E===null)return;try{await v.finish(E)}catch(b){let w=Ue(b);n.turn&&(n.turn.streamError=!0),v.fail(w);return}}}catch(v){throw Ue(v)}}catch(i){if(i instanceof X){er(e,new P(413,i.message));return}if(i instanceof P){er(e,i);return}throw i}}var sn="/v1/audio/transcriptions";function Xs(t){return t===sn}var Qs="/v1/audio/models",Vu=16*1024*1024,Ju=64*1024*1024,q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function tr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Zs(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Wu(t){if(!Zs(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,d=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,l=t[u+14]|t[u+15]<<8;n={sampleRate:d,channels:a,bitsPerSample:l}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ku(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function zu(t,e){t&&(t.outputUnits=e.seconds)}async function Yu(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],u=null;for await(let a of s){if(i.push(a),a.type==="error"){let d=a.error??{},l=typeof d.type=="string"?d.type:"upstream_error",c=String(d.message??"upstream reported an error");throw new q(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(a.type==="response.completed"){u=a.response??null;break}}if(u===null)throw new q(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return We(i,u)}function ei(t){return t instanceof q?t:t instanceof N?new q(404,t.message):new q(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Xu(t,e,n){let r;try{r=await t(e)}catch(o){throw ei(o)}return r?!0:(tr(n,new q(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Qu=new Set(["file","model","language","response_format"]);async function ti(t,e,n){let r=n.maxBodyBytes??Ju,o=n.maxAudioPartBytes??Vu;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${sn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(y){throw y instanceof X?new q(413,y.message):new q(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of i.keys()){if(!Qu.has(y))throw new q(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,g]of u)if(g>1)throw new q(400,`form field "${y}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let a=i.get("model");if(a!==null&&typeof a!="string")throw new q(400,"model must be a string field","model");let d=a===null?void 0:a,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new q(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,h=i.get("response_format")??"json";if(h!=="json")throw new q(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=i.get("file");if(!(f instanceof File))throw new q(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new q(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!Zs(p))throw new q(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let _=Wu(p);if(_===null)throw new q(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ku(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",p.length,p.length),!await Xu(n.transcriptionModels,d,e))return;let m=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let y=await Yu(n.clients,d,m,c,n.turn?ae(n.turn):void 0);zu(n.turn,_),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw ei(y)}}catch(s){if(s instanceof X){tr(e,new q(413,s.message));return}if(s instanceof q){tr(e,s);return}throw s}}var ri="/v1/usage/requests",ni=1e4,Zu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ee=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Qe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var oi=1024*1024;function nr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ee(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ee(`"${e}" must be an array of uuid strings`);if(n.length>ni)throw new Ee(`"${e}" carries ${n.length} ids; at most ${ni} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Zu.test(s))throw new Ee(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function si(t){return nr(t,"inference_ids")}function an(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new Qe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new Qe(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var pn=require("@urun-sh/core");var rr="/partners/huggingface/v1/billing/requests";function ed(t){return nr(t,"requestIds")}function td(t){return t>=200&&t<=399}function nd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&td(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ii(t,e){let n=ed(t),r=await e(n);return an(r,n),nd(r)}var rd={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function od(t){return rd[t]??null}var li=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function sd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function id(t){return t==="surface"}function ad(t){let e=t?.ledgerFailureReason;return li.includes(e)?e:"unknown"}var ud=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ai=["priced","unpriced"],dd={written:ai,already_written:ai,skipped:ud,failed:li},Dp=Object.entries(dd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ld(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function cd(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var pd=256,ui=4096,ht=12e4,fd=250,md=8e3,yt=[],di=new Set,_t=0,gt=!1;var gd=new Set;function hd(){return _t===0&&yt.length===0}function yd(){if(hd()){gt=!1;for(let t of[...gd])t()}}function ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
29
|
+
`}function Ru(t){le(process.stdout,t)}function Eu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Xn(t){return t.audioSession?.audio.sessionId??void 0}function Zn(t,e){let n=new ks.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Qn)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=R("rtup"),d=Eu(o),l=b=>{(e.log??Ru)(xu(b))};l({stage:"accept",conn:a,model:d}),s.resume();let c=new AbortController,h=null,f=b=>{h??=b,c.abort(new Error(h))},p=()=>f("client socket closed"),_=()=>f("client socket closed (half-close)"),m=b=>f(`client socket error: ${b.message}`);s.once("close",p),s.once("end",_),s.once("error",m);let y=()=>{s.removeListener("close",p),s.removeListener("end",_),s.removeListener("error",m)},g=b=>{l({stage:"close",conn:a,model:d,...b})},v=b=>{let w=b,k=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!k&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((x,I)=>{n.handleUpgrade(o,s,i,L=>{try{new pt({ws:L,binding:b,onClosed:(F,Y)=>{g({while:"live",reason:Y.reason})}}),l({stage:"admit",conn:a,model:d,...Xn(b)===void 0?{}:{session:Xn(b)}}),x()}catch(F){I(F)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){y();let w=Xn(b);try{await b.release?.()}catch(k){g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",released:!0}),s.destroy();return}y(),await v(b)}).catch(b=>{let w=b instanceof Ss.SessionFailedError?Jt(b):null,k=null;if(b!==null&&typeof b=="object"&&"status"in b){let I=b.status;typeof I=="number"&&(k=I)}let M=k??w?.status??502,x=b instanceof Error?b.message:String(b);g({while:"queued",...c.signal.aborted?{reason:h??"client socket closed"}:{reason:x,status:M}}),s.destroyed||ku(s,M,x)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var ce=(t,e)=>Object.assign(new Error(e),{status:t});function Au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ou='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tu(t,e,n,r){if(!t.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof N?ce(404,d.message):d}if(!o)throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof N?ce(404,d.message):d}if(s&&!t.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?ce(404,l.message):l}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ou}`);if(r==="transcription"&&!s)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i=await t.sessionHandle(e),u={audio:await t.openAudioOn(i,n)},a={clients:{createResponse:async d=>await t.createResponseOn(i,d)},voice:o,audioSession:u};return s&&(a.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(a.intent="transcription"),e!==void 0&&(a.model=e),a}function xs(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw ce(401,"invalid local proxy api key")}return Tu(t,Au(n),r,Iu(n))}}}var X=class extends Error{};async function Zt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function en(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new X(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Rs="/v1/images/generations",tn="/v1/images/edits";function Es(t){return t===Rs||t===tn}var As="/v1/images/models";async function Is(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Pu=16*1024*1024,Os=64*1024*1024;function Ts(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function ft(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Ps(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let c of o){if(c.type==="error"){let h=c.error??{};throw new $(502,`image upstream error: ${String(h.message??"upstream reported an error")}`)}if(c.type==="response.completed"){s=c.response??null;break}}if(s===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let u=[],a=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(a,"base64");if(Ts(d)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return u.push(a),{images:u}}function Cs(t){return t instanceof $?t:t instanceof N?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ms(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return ft(r,new $(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ls(t,e){t&&(t.outputUnits=e.images.length)}function $s(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Cu={model:!0,prompt:!0,response_format:!0,n:!0};async function Us(t,e,n){let r=n.maxBodyBytes??Os;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Rs}`);let o;try{o=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof X?new $(413,c.message):new $(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new $(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!Cu[c])throw new $(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new $(400,"model must be a string","model");await Is(n.turn,n.clients,u);let a=s.n??1;if(a!==1)throw new $(400,`n=${JSON.stringify(a)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new $(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Ms(n.imageModels,u,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await Ps(n.clients,u,l,n.turn?ae(n.turn):void 0);Ls(n.turn,c),$s(e,c)}catch(c){throw Cs(c)}}catch(o){if(o instanceof X){ft(e,new $(413,o.message));return}if(o instanceof $){ft(e,o);return}throw o}}var Mu={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ns(t,e,n){let r=n.maxBodyBytes??Os,o=n.maxImagePartBytes??Pu;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(f){throw f instanceof X?new $(413,f.message):new $(400,String(f instanceof Error?f.message:f))}let u=i.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let a=i.get("model");if(a!==null&&typeof a!="string")throw new $(400,"model must be a string field","model");let d=a===null?void 0:a;await Is(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new $(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of i.keys())if(!Mu[f])throw new $(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of i.getAll(f)){if(!(p instanceof File))throw new $(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let _=new Uint8Array(await p.arrayBuffer()),m=Ts(_);if(m===null)throw new $(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:_,mime:m})}if(c.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Ms(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:f,mime:p}of c)h.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Ps(n.clients,d,h,n.turn?ae(n.turn):void 0);Ls(n.turn,f),$s(e,f)}catch(f){throw Cs(f)}}catch(s){if(s instanceof X){ft(e,new $(413,s.message));return}if(s instanceof $){ft(e,s);return}throw s}}var mt="/v1/audio/speech";function Js(t){return t===mt}var Ds=4096,Fs=18e4,Bs=5e3,Lu=64*1024*1024,qs=8,js=5,Gs=1024*1024,Xe="voice_applied",rn="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function er(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var on=class extends P{constructor(e){super(502,e)}};function Ws(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ks(t){return new P(502,`the runtime's ${Xe} receipt ${JSON.stringify(t)} cannot be relayed as the ${rn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function $u(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function zs(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Uu=2;function Nu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Uu)return!1;return!0}function Du(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Hs=new WeakMap,nn=new WeakMap;function Fu(t,e){let n=nn.get(t)??0;if(n>=qs)throw new P(503,`this model's speech queue is full \u2014 ${qs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${js}s`,void 0,js);nn.set(t,n+1);let r=Hs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Hs.set(t,s),(async()=>{await r;try{return await e()}finally{nn.set(t,(nn.get(t)??1)-1),o()}})()}async function Bu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof J))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Ue(t){return t instanceof P?t:t instanceof N?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Vs(t,e,n,r,o,s,i,u){let a=u??(()=>{});return Fu(e,async()=>{if(i?.()===!0)return null;let d=!1,l=!1,c=!1,h,f=new Promise(b=>{h=b}),p=[],_=()=>{l&&!c&&p.length>=o.quietRunFrames&&(c=!0,h())},m=e.onOutputAudio(b=>{let w=Buffer.from(b,"base64");if(w.byteLength===0)return;let k=Nu(w);if(!d){if(k)return;d=!0}if(k){p.push(w),_();return}for(let M of p)a(M);p.length=0,a(w),_()}),y=null,g,v,E;try{E=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let w=new Promise(x=>{v=setTimeout(x,s.capMs)}),k=!1;for(;;){let x=E.next(),I=await Promise.race([x,w]);if(I===void 0){k=!0,x.catch(()=>{});break}if(I.done)break;let L=I.value;if(L.type==="error"){let F=L.error??{};throw await E.return?.(),new P(502,`speech upstream error: ${String(F.message??"upstream reported an error")}`)}if(L.type==="response.completed"){y=L.response??null,l=!0,_(),await E.return?.();break}}if(clearTimeout(v),k)throw new P(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(y===null)throw new P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let M=!1;if(await Promise.race([f,new Promise(x=>{g=setTimeout(()=>{M=!0,x()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let x=y[Xe];if(typeof x!="string"||x!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${Xe} ${JSON.stringify(x)}`:`no ${Xe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new on(I):new P(502,I)}}if(!d)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(M&&!c&&p.length<1)throw new P(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(b){throw b instanceof on||await Bu(t,n,E,s.returnBoundMs),b}finally{g!==void 0&&clearTimeout(g),v!==void 0&&clearTimeout(v),m()}})}function qu(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",rn)),t.write(u,a=>{a||(s+=u.byteLength,zs(e,s))}),t.writableLength>Gs&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Gs} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[Xe];if(typeof a=="string"){if(!Ws(a))throw Ks(a);t.addTrailers({[rn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function ju(t,e,n){let r;try{r=await t(e)}catch(o){throw Ue(o)}return r?!0:(er(n,new P(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Gu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hu="wav, pcm";async function Ys(t,e,n){let r=n.maxBodyBytes??Lu,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${mt}`);let i;try{i=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(v){throw v instanceof X?new P(413,v.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let u=i;for(let v of Object.keys(u))if(!Gu[v])throw new P(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let a=u.input;if(typeof a!="string"||a.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(a.length>Ds)throw new P(400,`input is ${a.length} chars \u2014 over the ${Ds}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new P(400,"model must be a string","model");let l=u.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${mt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(d)}catch(v){throw Ue(v)}if(c.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof l=="string"?l:void 0;if(h!==void 0&&c.published.length>0&&!c.published.includes(h))throw new P(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new P(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hu} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new P(400,"stream_format, when present, must be a string","stream_format");let p=u.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new P(400,"speed, when present, must be a number","speed");if(p!==1)throw new P(400,`speed=${JSON.stringify(p)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let _=u.instructions;if(_!==void 0){if(typeof _!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(_.trim().length>0)throw new P(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await $u(n.turn,n.clients,d);let m=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",m,m),!await ju(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new P(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw Ue(v)}let g;try{g=await n.clients.openAudioOn(y)}catch(v){throw Ue(v)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(f==="wav"){let v=[],E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,w=>v.push(w));if(E===null||s())return;let b=Buffer.concat(v);if(h===void 0){let w=E[Xe];if(typeof w=="string"){if(!Ws(w))throw Ks(w);e.setHeader(rn,w)}}zs(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Du(b.byteLength),b]))}else{let v=qu(e,n.turn,s,h===void 0),E;try{E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,v.sink)}catch(b){let w=Ue(b);if(!v.started())throw w;n.turn&&(n.turn.streamError=!0),v.fail(w);return}if(E===null)return;try{await v.finish(E)}catch(b){let w=Ue(b);n.turn&&(n.turn.streamError=!0),v.fail(w);return}}}catch(v){throw Ue(v)}}catch(i){if(i instanceof X){er(e,new P(413,i.message));return}if(i instanceof P){er(e,i);return}throw i}}var sn="/v1/audio/transcriptions";function Xs(t){return t===sn}var Qs="/v1/audio/models",Vu=16*1024*1024,Ju=64*1024*1024,q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function tr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Zs(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Wu(t){if(!Zs(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,d=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,l=t[u+14]|t[u+15]<<8;n={sampleRate:d,channels:a,bitsPerSample:l}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ku(t,e,n){if(t){if(t.model=ne({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function zu(t,e){t&&(t.outputUnits=e.seconds)}async function Yu(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],u=null;for await(let a of s){if(i.push(a),a.type==="error"){let d=a.error??{},l=typeof d.type=="string"?d.type:"upstream_error",c=String(d.message??"upstream reported an error");throw new q(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(a.type==="response.completed"){u=a.response??null;break}}if(u===null)throw new q(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return We(i,u)}function ei(t){return t instanceof q?t:t instanceof N?new q(404,t.message):new q(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Xu(t,e,n){let r;try{r=await t(e)}catch(o){throw ei(o)}return r?!0:(tr(n,new q(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Qu=new Set(["file","model","language","response_format"]);async function ti(t,e,n){let r=n.maxBodyBytes??Ju,o=n.maxAudioPartBytes??Vu;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${sn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(y){throw y instanceof X?new q(413,y.message):new q(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of i.keys()){if(!Qu.has(y))throw new q(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,g]of u)if(g>1)throw new q(400,`form field "${y}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let a=i.get("model");if(a!==null&&typeof a!="string")throw new q(400,"model must be a string field","model");let d=a===null?void 0:a,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new q(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,h=i.get("response_format")??"json";if(h!=="json")throw new q(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=i.get("file");if(!(f instanceof File))throw new q(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new q(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!Zs(p))throw new q(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let _=Wu(p);if(_===null)throw new q(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ku(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",p.length,p.length),!await Xu(n.transcriptionModels,d,e))return;let m=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let y=await Yu(n.clients,d,m,c,n.turn?ae(n.turn):void 0);zu(n.turn,_),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw ei(y)}}catch(s){if(s instanceof X){tr(e,new q(413,s.message));return}if(s instanceof q){tr(e,s);return}throw s}}var ri="/v1/usage/requests",ni=1e4,Zu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ee=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Qe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var oi=1024*1024;function nr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ee(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ee(`"${e}" must be an array of uuid strings`);if(n.length>ni)throw new Ee(`"${e}" carries ${n.length} ids; at most ${ni} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Zu.test(s))throw new Ee(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function si(t){return nr(t,"inference_ids")}function an(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new Qe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new Qe(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var pn=require("@urun-sh/core");var rr="/partners/huggingface/v1/billing/requests";function ed(t){return nr(t,"requestIds")}function td(t){return t>=200&&t<=399}function nd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&td(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ii(t,e){let n=ed(t),r=await e(n);return an(r,n),nd(r)}var rd={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function od(t){return rd[t]??null}var li=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function sd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function id(t){return t==="surface"}function ad(t){let e=t?.ledgerFailureReason;return li.includes(e)?e:"unknown"}var ud=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ai=["priced","unpriced"],dd={written:ai,already_written:ai,skipped:ud,failed:li},Dp=Object.entries(dd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ld(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function cd(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var pd=256,ui=4096,ht=12e4,fd=250,md=8e3,yt=[],di=new Set,_t=0,gt=!1;var gd=new Set;function hd(){return _t===0&&yt.length===0}function yd(){if(hd()){gt=!1;for(let t of[...gd])t()}}function ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
30
30
|
`}function _d(t){le(process.stdout,t)}function pi(t,e){try{t(e)}catch{}}function fi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??_d,o=od(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{s({outcome:"skipped",reason:l}),pi(r,ci("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:cd(e),completed_at:e.ts,billable_outcome:ld(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(yt.length>=ui){i("queue_full",`${yt.length} ledger writes are already waiting (capacity ${ui}, ${_t} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}yt.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),_t<pd&&(_t+=1,wd())}async function wd(){try{for(;;){let t=vd();if(t===void 0)return;di.add(t);try{await bd(t)}finally{di.delete(t)}}}finally{_t-=1,yd()}}function vd(){let t=Date.now();for(;;){let e=yt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<ht)return e;Ze(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${ht}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function bd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ze(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=sd(o);if(s!==null){Ze(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=ad(o),u=Date.now()-t.queuedAt;if(gt){Ze(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(id(i)&&u<ht){if(await kd(Sd(t.attempts)),gt||Date.now()-t.queuedAt>=ht){let a=Date.now()-t.queuedAt;Ze(t,{outcome:"failed",reason:gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${ht}ms dwell bound (waited ${a}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}Ze(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Sd(t){return Math.min(md,fd*2**Math.max(0,t-1))}function kd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ze(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;pi(t.report,ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var sr="x-urun-profile",wt="voice";var oe=class extends Error{status=400},xd=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Rd=/\s/;function Ed(t){return xd.test(t)}function or(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new oe(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function mi(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new oe(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new oe(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new oe(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function gi(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new oe(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new oe(`the ${sr} header is empty \u2014 the only profile this lane accepts is "${wt}" (omit the header for the ordinary lane)`);if(d!==wt)throw new oe(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${wt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==wt)throw new oe(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${wt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new oe("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new oe("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:mi(a,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:mi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:or(a,"sentence_flush",!0),includeReasoning:or(a,"include_reasoning",!1),metadata:or(a,"metadata",!1)}}var un=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Ed(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Rd.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function ur(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ad(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){ee(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function dr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);ee(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function me(t,e,n,r){ee(t,e,{type:"error",error:{type:n,message:r}})}function et(t,e,n){if(e==="anthropic"){ee(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ee(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Id=64*1024*1024,vt=class extends Error{};async function hi(t,e=Id){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new vt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ne(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function wi(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function dn(t){let e=wi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function yi(t){let e=dn(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Od(t,e){let n=wi(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Td(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let d=n[a];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function Pd(t,e){let n=Td(e);n&&(t.timing=n)}function De(t,e){Od(t,e),Pd(t,e)}async function fn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function vi(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Cd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var ln=class extends Error{};function Md(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new ln(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ld(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Md(n.role,n.content)})}return e}function ir(t){return Ve(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function $d(t,e,n,r,o,s){let i=ut(s.id),u=t.stream===!0;if(s.model=ne(t),s.stream=u,await fn(s,e,typeof t.model=="string"?t.model:void 0),u){let y;try{y=await lt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(g){if(g instanceof N){et(r,"openai",g);return}if(g instanceof ue){K(r,g.status,g.message);return}throw g}ur(r);for await(let g of y.events)g.type==="error"&&(s.streamError=!0),g.type==="response.completed"&&De(s,g.response),r.write(`event: ${String(g.type??"message")}
|
|
31
31
|
data: ${JSON.stringify(g)}
|
|
32
32
|
|
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-
|
|
2
|
+
import{a as J,b as q,c as H,d as Y,e as V}from"../chunk-4MQCXL73.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-BGAV27A5.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)}
|
package/dist/proxy/index.cjs
CHANGED
|
@@ -16,7 +16,7 @@ Content-Type: text/plain\r
|
|
|
16
16
|
\r
|
|
17
17
|
${ii(n)}\r
|
|
18
18
|
`),t.destroy()}function ai(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
19
|
-
`}function ui(t){Se(process.stdout,t)}function di(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zt(t){return t.audioSession?.audio.sessionId??void 0}function Ke(t,e){let n=new rr.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==We)return;r.add(i),i.on("close",()=>{r.delete(i)});let d=x("rtup"),u=di(o),l=_=>{(e.log??ui)(ai(_))};l({stage:"accept",conn:d,model:u}),i.resume();let c=new AbortController,y=null,p=_=>{y??=_,c.abort(new Error(y))},k=()=>p("client socket closed"),E=()=>p("client socket closed (half-close)"),S=_=>p(`client socket error: ${_.message}`);i.once("close",k),i.once("end",E),i.once("error",S);let f=()=>{i.removeListener("close",k),i.removeListener("end",E),i.removeListener("error",S)},h=_=>{l({stage:"close",conn:d,model:u,..._})},g=_=>{let m=_,v=m.session!=null&&typeof m.session.sendResponseCreate=="function",P=m.clients!=null&&typeof m.clients.createResponse=="function";if(!v&&!P)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((b,I)=>{n.handleUpgrade(o,i,s,C=>{try{new xe({ws:C,binding:_,onClosed:(D,W)=>{h({while:"live",reason:W.reason})}}),l({stage:"admit",conn:d,model:u,...Zt(_)===void 0?{}:{session:Zt(_)}}),b()}catch(D){I(D)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){f();let m=Zt(_);try{await _.release?.()}catch(v){h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",released:!0}),i.destroy();return}f(),await g(_)}).catch(_=>{let m=_ instanceof nr.SessionFailedError?_t(_):null,v=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(v=I)}let P=v??m?.status??502,b=_ instanceof Error?_.message:String(_);h({while:"queued",...c.signal.aborted?{reason:y??"client socket closed"}:{reason:b,status:P}}),i.destroyed||si(i,P,b)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var se=(t,e)=>Object.assign(new Error(e),{status:t});function en(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function li(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ci='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function tn(t,e,n,r){if(!t.supportsAudio)throw se(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(!o)throw se(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw se(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(i&&!t.openTurnsOn)throw se(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let u;try{u=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?se(404,l.message):l}if(u!=="stt")throw se(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw se(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ci}`);if(r==="transcription"&&!i)throw se(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},d={clients:{createResponse:async u=>await t.createResponseOn(s,u)},voice:o,audioSession:a};return i&&(d.turns=u=>t.openTurnsOn(s,u)),r==="transcription"&&(d.intent="transcription"),e!==void 0&&(d.model=e),d}function St(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,i=typeof o=="string"?o.trim():"",s=i.startsWith("Bearer ")?i.slice(7).trim():"";if(s===""||s!==e)throw se(401,"invalid local proxy api key")}return tn(t,en(n),r,li(n))}}}var xt=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ze=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var K=class extends Error{};async function Rt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new K(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new K(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Et(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new K(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[u,l]of Object.entries(t.headers))if(typeof l=="string")s.set(u,l);else if(Array.isArray(l))for(let c of l)s.append(u,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof K?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var or="/v1/images/generations",At="/v1/images/edits";function ir(t){return t===or||t===At}var sr="/v1/images/models";async function ar(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},pi=16*1024*1024,ur=64*1024*1024;function dr(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Ye(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function lr(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let y=c.error??{};throw new M(502,`image upstream error: ${String(y.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new M(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new M(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],d=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],u=Buffer.from(d,"base64");if(dr(u)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(d),{images:a}}function cr(t){return t instanceof M?t:t instanceof N?new M(404,t.message):new M(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function pr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Ye(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function fr(t,e){t&&(t.outputUnits=e.images.length)}function mr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var fi={model:!0,prompt:!0,response_format:!0,n:!0};async function hr(t,e,n){let r=n.maxBodyBytes??ur;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${or}`);let o;try{o=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof K?new M(413,c.message):new M(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new M(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!fi[c])throw new M(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new M(400,"model must be a string","model");await ar(n.turn,n.clients,a);let d=i.n??1;if(d!==1)throw new M(400,`n=${JSON.stringify(d)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=i.response_format??"b64_json";if(u!=="b64_json")throw new M(400,`response_format ${JSON.stringify(u)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await pr(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:s}];try{let c=await lr(n.clients,a,l,n.turn?re(n.turn):void 0);fr(n.turn,c),mr(e,c)}catch(c){throw cr(c)}}catch(o){if(o instanceof K){Ye(e,new M(413,o.message));return}if(o instanceof M){Ye(e,o);return}throw o}}var mi={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function gr(t,e,n){let r=n.maxBodyBytes??ur,o=n.maxImagePartBytes??pi;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${At}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(p){throw p instanceof K?new M(413,p.message):new M(400,String(p instanceof Error?p.message:p))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let d=s.get("model");if(d!==null&&typeof d!="string")throw new M(400,"model must be a string field","model");let u=d===null?void 0:d;await ar(n.turn,n.clients,u);let l=s.get("response_format")??"b64_json";if(l!=="b64_json")throw new M(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let p of s.keys())if(!mi[p])throw new M(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let k of s.getAll(p)){if(!(k instanceof File))throw new M(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(k.size>o)throw new M(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let E=new Uint8Array(await k.arrayBuffer()),S=dr(E);if(S===null)throw new M(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:E,mime:S})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await pr(n.imageModels,u,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:p,mime:k}of c)y.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(p).toString("base64")}`});try{let p=await lr(n.clients,u,y,n.turn?re(n.turn):void 0);fr(n.turn,p),mr(e,p)}catch(p){throw cr(p)}}catch(i){if(i instanceof K){Ye(e,new M(413,i.message));return}if(i instanceof M){Ye(e,i);return}throw i}}var Xe="/v1/audio/speech";function Rr(t){return t===Xe}var yr=4096,_r=18e4,wr=5e3,hi=64*1024*1024,vr=8,br=5,kr=1024*1024,Ne="voice_applied",Ot="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function nn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Tt=class extends T{constructor(e){super(502,e)}};function Er(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ar(t){return new T(502,`the runtime's ${Ne} receipt ${JSON.stringify(t)} cannot be relayed as the ${Ot} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function gi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ir(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var yi=2;function _i(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>yi)return!1;return!0}function wi(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Sr=new WeakMap,It=new WeakMap;function vi(t,e){let n=It.get(t)??0;if(n>=vr)throw new T(503,`this model's speech queue is full \u2014 ${vr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${br}s`,void 0,br);It.set(t,n+1);let r=Sr.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Sr.set(t,i),(async()=>{await r;try{return await e()}finally{It.set(t,(It.get(t)??1)-1),o()}})()}async function bi(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof Z))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function Re(t){return t instanceof T?t:t instanceof N?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function xr(t,e,n,r,o,i,s,a){let d=a??(()=>{});return vi(e,async()=>{if(s?.()===!0)return null;let u=!1,l=!1,c=!1,y,p=new Promise(_=>{y=_}),k=[],E=()=>{l&&!c&&k.length>=o.quietRunFrames&&(c=!0,y())},S=e.onOutputAudio(_=>{let m=Buffer.from(_,"base64");if(m.byteLength===0)return;let v=_i(m);if(!u){if(v)return;u=!0}if(v){k.push(m),E();return}for(let P of k)d(P);k.length=0,d(m),E()}),f=null,h,g,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let m=new Promise(b=>{g=setTimeout(b,i.capMs)}),v=!1;for(;;){let b=A.next(),I=await Promise.race([b,m]);if(I===void 0){v=!0,b.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let D=C.error??{};throw await A.return?.(),new T(502,`speech upstream error: ${String(D.message??"upstream reported an error")}`)}if(C.type==="response.completed"){f=C.response??null,l=!0,E(),await A.return?.();break}}if(clearTimeout(g),v)throw new T(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(f===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(b=>{h=setTimeout(()=>{P=!0,b()},o.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let b=f[Ne];if(typeof b!="string"||b!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof b=="string"?`${Ne} ${JSON.stringify(b)}`:`no ${Ne} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Tt(I):new T(502,I)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&k.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return f}catch(_){throw _ instanceof Tt||await bi(t,n,A,i.returnBoundMs),_}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),S()}})}function ki(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Ot)),t.write(a,d=>{d||(i+=a.byteLength,Ir(e,i))}),t.writableLength>kr&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${kr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let d=a[Ne];if(typeof d=="string"){if(!Er(d))throw Ar(d);t.addTrailers({[Ot]:d})}}await new Promise(d=>{t.end(()=>d())})}},fail:s}}async function Si(t,e,n){let r;try{r=await t(e)}catch(o){throw Re(o)}return r?!0:(nn(n,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var xi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ri="wav, pcm";async function Or(t,e,n){let r=n.maxBodyBytes??hi,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Xe}`);let s;try{s=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(g){throw g instanceof K?new T(413,g.message):new T(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new T(400,"request body must be a JSON object");let a=s;for(let g of Object.keys(a))if(!xi[g])throw new T(400,`request field "${g}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,g);let d=a.input;if(typeof d!="string"||d.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(d.length>yr)throw new T(400,`input is ${d.length} chars \u2014 over the ${yr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Xe} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(g){throw Re(g)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof l=="string"?l:void 0;if(y!==void 0&&c.published.length>0&&!c.published.includes(y))throw new T(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ri} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let k=a.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new T(400,"speed, when present, must be a number","speed");if(k!==1)throw new T(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let E=a.instructions;if(E!==void 0){if(typeof E!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(E.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await gi(n.turn,n.clients,u);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await Si(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let f;try{f=await n.clients.speechSessionHandle(u)}catch(g){throw Re(g)}let h;try{h=await n.clients.openAudioOn(f)}catch(g){throw Re(g)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,m=>g.push(m));if(A===null||i())return;let _=Buffer.concat(g);if(y===void 0){let m=A[Ne];if(typeof m=="string"){if(!Er(m))throw Ar(m);e.setHeader(Ot,m)}}Ir(n.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([wi(_.byteLength),_]))}else{let g=ki(e,n.turn,i,y===void 0),A;try{A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,g.sink)}catch(_){let m=Re(_);if(!g.started())throw m;n.turn&&(n.turn.streamError=!0),g.fail(m);return}if(A===null)return;try{await g.finish(A)}catch(_){let m=Re(_);n.turn&&(n.turn.streamError=!0),g.fail(m);return}}}catch(g){throw Re(g)}}catch(s){if(s instanceof K){nn(e,new T(413,s.message));return}if(s instanceof T){nn(e,s);return}throw s}}var Pt="/v1/audio/transcriptions";function Tr(t){return t===Pt}var Pr="/v1/audio/models",Ei=16*1024*1024,Ai=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function rn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Cr(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Ii(t){if(!Cr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let d=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:d,bitsPerSample:l}}else if(i==="data"){let d=t.length-a;r=Math.min(s===0||s===4294967295?d:s,d)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Oi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ti(t,e){t&&(t.outputUnits=e.seconds)}async function Pi(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let d of i){if(s.push(d),d.type==="error"){let u=d.error??{},l=typeof u.type=="string"?u.type:"upstream_error",c=String(u.message??"upstream reported an error");throw new B(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(d.type==="response.completed"){a=d.response??null;break}}if(a===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Me(s,a)}function Mr(t){return t instanceof B?t:t instanceof N?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ci(t,e,n){let r;try{r=await t(e)}catch(o){throw Mr(o)}return r?!0:(rn(n,new B(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Mi=new Set(["file","model","language","response_format"]);async function $r(t,e,n){let r=n.maxBodyBytes??Ai,o=n.maxAudioPartBytes??Ei;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Pt}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(f){throw f instanceof K?new B(413,f.message):new B(400,String(f instanceof Error?f.message:f))}let a=new Map;for(let f of s.keys()){if(!Mi.has(f))throw new B(400,`form field "${f}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,f);a.set(f,(a.get(f)??0)+1)}for(let[f,h]of a)if(h>1)throw new B(400,`form field "${f}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let d=s.get("model");if(d!==null&&typeof d!="string")throw new B(400,"model must be a string field","model");let u=d===null?void 0:d,l=s.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,y=s.get("response_format")??"json";if(y!=="json")throw new B(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=s.get("file");if(!(p instanceof File))throw new B(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>o)throw new B(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await p.arrayBuffer());if(!Cr(k))throw new B(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let E=Ii(k);if(E===null)throw new B(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Oi(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ci(n.transcriptionModels,u,e))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let f=await Pi(n.clients,u,S,c,n.turn?re(n.turn):void 0);Ti(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw Mr(f)}}catch(i){if(i instanceof K){rn(e,new B(413,i.message));return}if(i instanceof B){rn(e,i);return}throw i}}var Nr="/v1/usage/requests",Lr=1e4,$i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ge=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ue=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Ur=1024*1024;function on(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ge(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ge(`"${e}" must be an array of uuid strings`);if(n.length>Lr)throw new ge(`"${e}" carries ${n.length} ids; at most ${Lr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!$i.test(i))throw new ge(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Dr(t){return on(t,"inference_ids")}function Ct(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new Ue(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new Ue(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Ut=require("@urun-sh/core");var Li=require("@urun-sh/core"),Qe=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var sn="/partners/huggingface/v1/billing/requests";function Ni(t){return on(t,"requestIds")}function Ui(t){return t>=200&&t<=399}function Di(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ui(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Fr(t,e){let n=Ni(t),r=await e(n);return Ct(r,n),Di(r)}var Fi={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Bi(t){return Fi[t]??null}var Hr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function qi(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ji(t){return t==="surface"}function Hi(t){let e=t?.ledgerFailureReason;return Hr.includes(e)?e:"unknown"}var Vi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Br=["priced","unpriced"],Gi={written:Br,already_written:Br,skipped:Vi,failed:Hr},Bu=Object.entries(Gi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ji(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Wi(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Ki=256,qr=4096,et=12e4,zi=250,Yi=8e3,tt=[],jr=new Set,nt=0,Ze=!1;var Xi=new Set;function Qi(){return nt===0&&tt.length===0}function Zi(){if(Qi()){Ze=!1;for(let t of[...Xi])t()}}function Vr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
19
|
+
`}function ui(t){Se(process.stdout,t)}function di(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zt(t){return t.audioSession?.audio.sessionId??void 0}function Ke(t,e){let n=new rr.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==We)return;r.add(i),i.on("close",()=>{r.delete(i)});let d=x("rtup"),u=di(o),l=_=>{(e.log??ui)(ai(_))};l({stage:"accept",conn:d,model:u}),i.resume();let c=new AbortController,y=null,p=_=>{y??=_,c.abort(new Error(y))},k=()=>p("client socket closed"),E=()=>p("client socket closed (half-close)"),S=_=>p(`client socket error: ${_.message}`);i.once("close",k),i.once("end",E),i.once("error",S);let f=()=>{i.removeListener("close",k),i.removeListener("end",E),i.removeListener("error",S)},h=_=>{l({stage:"close",conn:d,model:u,..._})},g=_=>{let m=_,v=m.session!=null&&typeof m.session.sendResponseCreate=="function",P=m.clients!=null&&typeof m.clients.createResponse=="function";if(!v&&!P)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((b,I)=>{n.handleUpgrade(o,i,s,C=>{try{new xe({ws:C,binding:_,onClosed:(D,W)=>{h({while:"live",reason:W.reason})}}),l({stage:"admit",conn:d,model:u,...Zt(_)===void 0?{}:{session:Zt(_)}}),b()}catch(D){I(D)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){f();let m=Zt(_);try{await _.release?.()}catch(v){h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",released:!0}),i.destroy();return}f(),await g(_)}).catch(_=>{let m=_ instanceof nr.SessionFailedError?_t(_):null,v=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(v=I)}let P=v??m?.status??502,b=_ instanceof Error?_.message:String(_);h({while:"queued",...c.signal.aborted?{reason:y??"client socket closed"}:{reason:b,status:P}}),i.destroyed||si(i,P,b)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var se=(t,e)=>Object.assign(new Error(e),{status:t});function en(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function li(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ci='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function tn(t,e,n,r){if(!t.supportsAudio)throw se(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(!o)throw se(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw se(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(i&&!t.openTurnsOn)throw se(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let u;try{u=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?se(404,l.message):l}if(u!=="stt")throw se(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw se(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ci}`);if(r==="transcription"&&!i)throw se(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},d={clients:{createResponse:async u=>await t.createResponseOn(s,u)},voice:o,audioSession:a};return i&&(d.turns=u=>t.openTurnsOn(s,u)),r==="transcription"&&(d.intent="transcription"),e!==void 0&&(d.model=e),d}function St(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,i=typeof o=="string"?o.trim():"",s=i.startsWith("Bearer ")?i.slice(7).trim():"";if(s===""||s!==e)throw se(401,"invalid local proxy api key")}return tn(t,en(n),r,li(n))}}}var xt=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ze=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var K=class extends Error{};async function Rt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new K(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new K(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Et(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new K(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[u,l]of Object.entries(t.headers))if(typeof l=="string")s.set(u,l);else if(Array.isArray(l))for(let c of l)s.append(u,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof K?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var or="/v1/images/generations",At="/v1/images/edits";function ir(t){return t===or||t===At}var sr="/v1/images/models";async function ar(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},pi=16*1024*1024,ur=64*1024*1024;function dr(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Ye(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function lr(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let y=c.error??{};throw new M(502,`image upstream error: ${String(y.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new M(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new M(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],d=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],u=Buffer.from(d,"base64");if(dr(u)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(d),{images:a}}function cr(t){return t instanceof M?t:t instanceof N?new M(404,t.message):new M(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function pr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Ye(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function fr(t,e){t&&(t.outputUnits=e.images.length)}function mr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var fi={model:!0,prompt:!0,response_format:!0,n:!0};async function hr(t,e,n){let r=n.maxBodyBytes??ur;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${or}`);let o;try{o=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof K?new M(413,c.message):new M(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new M(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!fi[c])throw new M(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new M(400,"model must be a string","model");await ar(n.turn,n.clients,a);let d=i.n??1;if(d!==1)throw new M(400,`n=${JSON.stringify(d)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=i.response_format??"b64_json";if(u!=="b64_json")throw new M(400,`response_format ${JSON.stringify(u)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await pr(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:s}];try{let c=await lr(n.clients,a,l,n.turn?re(n.turn):void 0);fr(n.turn,c),mr(e,c)}catch(c){throw cr(c)}}catch(o){if(o instanceof K){Ye(e,new M(413,o.message));return}if(o instanceof M){Ye(e,o);return}throw o}}var mi={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function gr(t,e,n){let r=n.maxBodyBytes??ur,o=n.maxImagePartBytes??pi;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${At}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(p){throw p instanceof K?new M(413,p.message):new M(400,String(p instanceof Error?p.message:p))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let d=s.get("model");if(d!==null&&typeof d!="string")throw new M(400,"model must be a string field","model");let u=d===null?void 0:d;await ar(n.turn,n.clients,u);let l=s.get("response_format")??"b64_json";if(l!=="b64_json")throw new M(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let p of s.keys())if(!mi[p])throw new M(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let k of s.getAll(p)){if(!(k instanceof File))throw new M(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(k.size>o)throw new M(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let E=new Uint8Array(await k.arrayBuffer()),S=dr(E);if(S===null)throw new M(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:E,mime:S})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await pr(n.imageModels,u,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:p,mime:k}of c)y.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(p).toString("base64")}`});try{let p=await lr(n.clients,u,y,n.turn?re(n.turn):void 0);fr(n.turn,p),mr(e,p)}catch(p){throw cr(p)}}catch(i){if(i instanceof K){Ye(e,new M(413,i.message));return}if(i instanceof M){Ye(e,i);return}throw i}}var Xe="/v1/audio/speech";function Rr(t){return t===Xe}var yr=4096,_r=18e4,wr=5e3,hi=64*1024*1024,vr=8,br=5,kr=1024*1024,Ne="voice_applied",Ot="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function nn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Tt=class extends T{constructor(e){super(502,e)}};function Er(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ar(t){return new T(502,`the runtime's ${Ne} receipt ${JSON.stringify(t)} cannot be relayed as the ${Ot} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function gi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ir(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var yi=2;function _i(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>yi)return!1;return!0}function wi(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Sr=new WeakMap,It=new WeakMap;function vi(t,e){let n=It.get(t)??0;if(n>=vr)throw new T(503,`this model's speech queue is full \u2014 ${vr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${br}s`,void 0,br);It.set(t,n+1);let r=Sr.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Sr.set(t,i),(async()=>{await r;try{return await e()}finally{It.set(t,(It.get(t)??1)-1),o()}})()}async function bi(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof Z))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function Re(t){return t instanceof T?t:t instanceof N?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function xr(t,e,n,r,o,i,s,a){let d=a??(()=>{});return vi(e,async()=>{if(s?.()===!0)return null;let u=!1,l=!1,c=!1,y,p=new Promise(_=>{y=_}),k=[],E=()=>{l&&!c&&k.length>=o.quietRunFrames&&(c=!0,y())},S=e.onOutputAudio(_=>{let m=Buffer.from(_,"base64");if(m.byteLength===0)return;let v=_i(m);if(!u){if(v)return;u=!0}if(v){k.push(m),E();return}for(let P of k)d(P);k.length=0,d(m),E()}),f=null,h,g,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let m=new Promise(b=>{g=setTimeout(b,i.capMs)}),v=!1;for(;;){let b=A.next(),I=await Promise.race([b,m]);if(I===void 0){v=!0,b.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let D=C.error??{};throw await A.return?.(),new T(502,`speech upstream error: ${String(D.message??"upstream reported an error")}`)}if(C.type==="response.completed"){f=C.response??null,l=!0,E(),await A.return?.();break}}if(clearTimeout(g),v)throw new T(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(f===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(b=>{h=setTimeout(()=>{P=!0,b()},o.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let b=f[Ne];if(typeof b!="string"||b!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof b=="string"?`${Ne} ${JSON.stringify(b)}`:`no ${Ne} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Tt(I):new T(502,I)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&k.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return f}catch(_){throw _ instanceof Tt||await bi(t,n,A,i.returnBoundMs),_}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),S()}})}function ki(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Ot)),t.write(a,d=>{d||(i+=a.byteLength,Ir(e,i))}),t.writableLength>kr&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${kr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let d=a[Ne];if(typeof d=="string"){if(!Er(d))throw Ar(d);t.addTrailers({[Ot]:d})}}await new Promise(d=>{t.end(()=>d())})}},fail:s}}async function Si(t,e,n){let r;try{r=await t(e)}catch(o){throw Re(o)}return r?!0:(nn(n,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var xi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ri="wav, pcm";async function Or(t,e,n){let r=n.maxBodyBytes??hi,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Xe}`);let s;try{s=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(g){throw g instanceof K?new T(413,g.message):new T(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new T(400,"request body must be a JSON object");let a=s;for(let g of Object.keys(a))if(!xi[g])throw new T(400,`request field "${g}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,g);let d=a.input;if(typeof d!="string"||d.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(d.length>yr)throw new T(400,`input is ${d.length} chars \u2014 over the ${yr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Xe} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(g){throw Re(g)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof l=="string"?l:void 0;if(y!==void 0&&c.published.length>0&&!c.published.includes(y))throw new T(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ri} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let k=a.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new T(400,"speed, when present, must be a number","speed");if(k!==1)throw new T(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let E=a.instructions;if(E!==void 0){if(typeof E!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(E.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await gi(n.turn,n.clients,u);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await Si(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let f;try{f=await n.clients.speechSessionHandle(u)}catch(g){throw Re(g)}let h;try{h=await n.clients.openAudioOn(f)}catch(g){throw Re(g)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,m=>g.push(m));if(A===null||i())return;let _=Buffer.concat(g);if(y===void 0){let m=A[Ne];if(typeof m=="string"){if(!Er(m))throw Ar(m);e.setHeader(Ot,m)}}Ir(n.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([wi(_.byteLength),_]))}else{let g=ki(e,n.turn,i,y===void 0),A;try{A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,g.sink)}catch(_){let m=Re(_);if(!g.started())throw m;n.turn&&(n.turn.streamError=!0),g.fail(m);return}if(A===null)return;try{await g.finish(A)}catch(_){let m=Re(_);n.turn&&(n.turn.streamError=!0),g.fail(m);return}}}catch(g){throw Re(g)}}catch(s){if(s instanceof K){nn(e,new T(413,s.message));return}if(s instanceof T){nn(e,s);return}throw s}}var Pt="/v1/audio/transcriptions";function Tr(t){return t===Pt}var Pr="/v1/audio/models",Ei=16*1024*1024,Ai=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function rn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Cr(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Ii(t){if(!Cr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let d=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:d,bitsPerSample:l}}else if(i==="data"){let d=t.length-a;r=Math.min(s===0||s===4294967295?d:s,d)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Oi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ti(t,e){t&&(t.outputUnits=e.seconds)}async function Pi(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let d of i){if(s.push(d),d.type==="error"){let u=d.error??{},l=typeof u.type=="string"?u.type:"upstream_error",c=String(u.message??"upstream reported an error");throw new B(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(d.type==="response.completed"){a=d.response??null;break}}if(a===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Me(s,a)}function Mr(t){return t instanceof B?t:t instanceof N?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ci(t,e,n){let r;try{r=await t(e)}catch(o){throw Mr(o)}return r?!0:(rn(n,new B(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Mi=new Set(["file","model","language","response_format"]);async function $r(t,e,n){let r=n.maxBodyBytes??Ai,o=n.maxAudioPartBytes??Ei;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Pt}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(f){throw f instanceof K?new B(413,f.message):new B(400,String(f instanceof Error?f.message:f))}let a=new Map;for(let f of s.keys()){if(!Mi.has(f))throw new B(400,`form field "${f}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,f);a.set(f,(a.get(f)??0)+1)}for(let[f,h]of a)if(h>1)throw new B(400,`form field "${f}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let d=s.get("model");if(d!==null&&typeof d!="string")throw new B(400,"model must be a string field","model");let u=d===null?void 0:d,l=s.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,y=s.get("response_format")??"json";if(y!=="json")throw new B(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=s.get("file");if(!(p instanceof File))throw new B(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>o)throw new B(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await p.arrayBuffer());if(!Cr(k))throw new B(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let E=Ii(k);if(E===null)throw new B(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Oi(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ci(n.transcriptionModels,u,e))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let f=await Pi(n.clients,u,S,c,n.turn?re(n.turn):void 0);Ti(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw Mr(f)}}catch(i){if(i instanceof K){rn(e,new B(413,i.message));return}if(i instanceof B){rn(e,i);return}throw i}}var Nr="/v1/usage/requests",Lr=1e4,$i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ge=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ue=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Ur=1024*1024;function on(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ge(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ge(`"${e}" must be an array of uuid strings`);if(n.length>Lr)throw new ge(`"${e}" carries ${n.length} ids; at most ${Lr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!$i.test(i))throw new ge(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Dr(t){return on(t,"inference_ids")}function Ct(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new Ue(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new Ue(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Ut=require("@urun-sh/core");var Li=require("@urun-sh/core"),Qe=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var sn="/partners/huggingface/v1/billing/requests";function Ni(t){return on(t,"requestIds")}function Ui(t){return t>=200&&t<=399}function Di(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ui(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Fr(t,e){let n=Ni(t),r=await e(n);return Ct(r,n),Di(r)}var Fi={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Bi(t){return Fi[t]??null}var Hr=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function qi(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ji(t){return t==="surface"}function Hi(t){let e=t?.ledgerFailureReason;return Hr.includes(e)?e:"unknown"}var Vi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Br=["priced","unpriced"],Gi={written:Br,already_written:Br,skipped:Vi,failed:Hr},Bu=Object.entries(Gi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ji(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Wi(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Ki=256,qr=4096,et=12e4,zi=250,Yi=8e3,tt=[],jr=new Set,nt=0,Ze=!1;var Xi=new Set;function Qi(){return nt===0&&tt.length===0}function Zi(){if(Qi()){Ze=!1;for(let t of[...Xi])t()}}function Vr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
20
20
|
`}function es(t){Se(process.stdout,t)}function Gr(t,e){try{t(e)}catch{}}function Jr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??es,o=Bi(e.path);if(o===null)return;let i=l=>{try{n.observe(l)}catch{}},s=(l,c)=>{i({outcome:"skipped",reason:l}),Gr(r,Vr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let d;if(a.kind==="catalog")d={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}d={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...d,task:o,http_status:e.status,started_at:Wi(e),completed_at:e.ts,billable_outcome:Ji(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(tt.length>=qr){s("queue_full",`${tt.length} ledger writes are already waiting (capacity ${qr}, ${nt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}tt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),nt<Ki&&(nt+=1,ts())}async function ts(){try{for(;;){let t=ns();if(t===void 0)return;jr.add(t);try{await rs(t)}finally{jr.delete(t)}}}finally{nt-=1,Zi()}}function ns(){let t=Date.now();for(;;){let e=tt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<et)return e;De(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${et}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function rs(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);De(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=qi(o);if(i!==null){De(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Hi(o),a=Date.now()-t.queuedAt;if(Ze){De(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(ji(s)&&a<et){if(await is(os(t.attempts)),Ze||Date.now()-t.queuedAt>=et){let d=Date.now()-t.queuedAt;De(t,{outcome:"failed",reason:Ze?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ze?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:d,error:`this row's backoff outlived the ${et}ms dwell bound (waited ${d}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}De(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function os(t){return Math.min(Yi,zi*2**Math.max(0,t-1))}function is(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function De(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Gr(t.report,Vr(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var un="x-urun-profile",rt="voice";var ne=class extends Error{status=400},ss=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,as=/\s/;function us(t){return ss.test(t)}function an(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ne(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Wr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ne(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ne(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ne(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Kr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ne(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let u=n.trim();if(u==="")throw new ne(`the ${un} header is empty \u2014 the only profile this lane accepts is "${rt}" (omit the header for the ordinary lane)`);if(u!==rt)throw new ne(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${rt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==rt)throw new ne(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${rt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ne("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ne("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let d=a??{};return{flushMaxChars:Wr(d,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Wr(d,"flush_max_ms",250,{max:2147483647}),sentenceFlush:an(d,"sentence_flush",!0),includeReasoning:an(d,"include_reasoning",!1),metadata:an(d,"metadata",!1)}}var Mt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&us(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(as.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function cn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ds(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function X(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function G(t,e,n,r="invalid_request_error",o){X(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function pn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);X(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ue(t,e,n,r){X(t,e,{type:"error",error:{type:n,message:r}})}function Fe(t,e,n){if(e==="anthropic"){X(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}X(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ls=64*1024*1024,ot=class extends Error{};async function zr(t,e=ls){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new ot(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ee(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Qr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=d=>typeof d=="number"&&Number.isFinite(d)&&d>=0?d:null,o=r(n.input_tokens),i=r(n.output_tokens),s=d=>d??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let d={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:d}:{kind:"counts",usage:d}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function $t(t){let e=Qr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Yr(t){let e=$t(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function cs(t,e){let n=Qr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ps(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=d=>{let u=n[d];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function fs(t,e){let n=ps(e);n&&(t.timing=n)}function Ae(t,e){cs(t,e),fs(t,e)}async function Dt(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Zr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function ms(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Lt=class extends Error{};function hs(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Lt(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function gs(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:hs(n.role,n.content)})}return e}function dn(t){return Pe(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function ys(t,e,n,r,o,i){let s=He(i.id),a=t.stream===!0;if(i.model=ee(t),i.stream=a,await Dt(i,e,typeof t.model=="string"?t.model:void 0),a){let f;try{f=await Ge({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(h){if(h instanceof N){Fe(r,"openai",h);return}if(h instanceof oe){G(r,h.status,h.message);return}throw h}cn(r);for await(let h of f.events)h.type==="error"&&(i.streamError=!0),h.type==="response.completed"&&Ae(i,h.response),r.write(`event: ${String(h.type??"message")}
|
|
21
21
|
data: ${JSON.stringify(h)}
|
|
22
22
|
|
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
-
import { f as ProxyHandlerOptions, P as ProxyClients } from '../responses-turn-
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../responses-turn-
|
|
2
|
+
import { f as ProxyHandlerOptions, P as ProxyClients } from '../responses-turn-BFURb0jK.cjs';
|
|
3
|
+
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../responses-turn-BFURb0jK.cjs';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CO8W_hmJ.cjs';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-DUdx_Y6X.cjs';
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
-
import { f as ProxyHandlerOptions, P as ProxyClients } from '../responses-turn-
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../responses-turn-
|
|
2
|
+
import { f as ProxyHandlerOptions, P as ProxyClients } from '../responses-turn-Cxfv-oXb.js';
|
|
3
|
+
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../responses-turn-Cxfv-oXb.js';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-Ddd65sXR.js';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-DUdx_Y6X.js';
|
package/dist/proxy/index.js
CHANGED
|
@@ -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-
|
|
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-BGAV27A5.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};
|