@urun-sh/openai 0.5.6 → 0.6.1

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.
Files changed (52) hide show
  1. package/dist/{ResponsesClient-BE3-hx3m.d.ts → ResponsesClient-CSSrOYD8.d.ts} +5 -1
  2. package/dist/{ResponsesClient-DjZWjlFH.d.cts → ResponsesClient-_OZERUjH.d.cts} +9 -1
  3. package/dist/{chunk-7M6LY6DR.js → chunk-3JWYIKHM.js} +1 -1
  4. package/dist/{chunk-BSHT6RZZ.js → chunk-6M5JK4YC.js} +1 -1
  5. package/dist/chunk-76BZLCGT.js +1 -0
  6. package/dist/chunk-7V2JKPIG.js +1 -0
  7. package/dist/{chunk-5HKWNK3O.js → chunk-K23AZPI4.js} +1 -1
  8. package/dist/chunk-T2LNHDPS.js +7 -0
  9. package/dist/chunk-TMQJY56F.js +4 -0
  10. package/dist/chunk-WEBOBE7Z.js +58 -0
  11. package/dist/chunk-X3GLH2HQ.js +1 -0
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +75 -7
  14. package/dist/gemini-live.d.ts +30 -7
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +37 -35
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +33 -31
  19. package/dist/hosted/index.d.cts +70 -4
  20. package/dist/hosted/index.d.ts +21 -4
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.cts +4 -4
  24. package/dist/index.d.ts +4 -4
  25. package/dist/index.js +1 -1
  26. package/dist/pi-extension/index.cjs +7 -7
  27. package/dist/pi-extension/index.d.cts +2 -2
  28. package/dist/pi-extension/index.d.ts +2 -2
  29. package/dist/pi-extension/index.js +1 -1
  30. package/dist/pi-extension/standalone.cjs +53 -53
  31. package/dist/proxy/cli.cjs +48 -46
  32. package/dist/proxy/cli.js +15 -14
  33. package/dist/proxy/index.cjs +25 -24
  34. package/dist/proxy/index.d.cts +142 -25
  35. package/dist/proxy/index.d.ts +22 -11
  36. package/dist/proxy/index.js +1 -1
  37. package/dist/{responses-turn-Dr37N3kH.d.ts → responses-turn-EwxfRJJg.d.ts} +187 -7
  38. package/dist/{responses-turn-tNUHq5b0.d.cts → responses-turn-vMefRdgJ.d.cts} +707 -23
  39. package/dist/{translator-Bh0Bp_Ie.d.cts → translator-CO8W_hmJ.d.cts} +1 -1
  40. package/dist/{translator-BCoRFaTs.d.ts → translator-Ddd65sXR.d.ts} +1 -1
  41. package/dist/{types-lsVTbNcH.d.cts → types-CHPtJx6d.d.cts} +13 -0
  42. package/dist/{types-lsVTbNcH.d.ts → types-CHPtJx6d.d.ts} +4 -0
  43. package/dist/{video-out-CCksIcj8.d.cts → video-out-BsuLqlID.d.cts} +1 -1
  44. package/dist/{video-out-IGQ4YQ-c.d.ts → video-out-Cawtm7SF.d.ts} +1 -1
  45. package/package.json +4 -2
  46. package/dist/chunk-2T2YYBVX.js +0 -1
  47. package/dist/chunk-3WAJD62J.js +0 -4
  48. package/dist/chunk-FP4RSAIE.js +0 -1
  49. package/dist/chunk-HR5H6S7L.js +0 -1
  50. package/dist/chunk-NY23USZF.js +0 -57
  51. package/dist/chunk-VLRMJRLS.js +0 -6
  52. /package/dist/{chunk-5CCJUNH7.js → chunk-YSFSRI3D.js} +0 -0
@@ -0,0 +1,58 @@
1
+ import{c as cn,d as $,e as le,i as Tt}from"./chunk-TMQJY56F.js";import{a as ln,c as pn,d as we,e as rt,f as z,g as mn,h as fn,i as gn,j as hn,k as yn,l as _n,m as wn,n as vn,r as bn,t as xn,u as kn,v as Rn,w as Sn,x as En}from"./chunk-3JWYIKHM.js";import{a as Ot}from"./chunk-6M5JK4YC.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{randomUUID as Gr}from"crypto";import{WebSocketServer as Hr}from"ws";var Jr=256,ot=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Jr;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Wr="local",Be=t=>t.slice(0,120),st=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof $){this.ws.close(pn,Be(e.message));return}if(e instanceof le){this.ws.close(rt,Be(e.message));return}if(e instanceof z){this.ws.close(e.closeCode,Be(e.message));return}this.ws.close(we,Be(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=mn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new z(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=vn(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=xn(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:bn);return}this.transcript.push(...kn(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new z("setup may only be sent once, as the first client message");let n=yn(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new z("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",rt);if(s.model!==n.model)throw new z(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new z("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new z(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,rt);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(hn(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[fn]=gn(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new z("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new z("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",we);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Sn(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new z("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new z("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",we);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new z(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new z("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new z("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=Gr();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(_n(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(wn(e.timeLeftMs)),this.ws.close(we,Be(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new z(`upstream error: ${JSON.stringify(d)}`,we);if(d.type==="response.completed"){o=d.response,s=!0;continue}let c=Rn(d);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new z("upstream produced no response.completed event",we);let{messages:i,assistantItems:a}=En(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ve=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Vr(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new ve(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new ve(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new ve(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function In(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Hr({noServer:!0}),o=new ot;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===ln&&(a.on("error",()=>{}),(async()=>{let c=Vr(i,d,n),l;if(e.authenticate)l=await e.authenticate(c,i);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new ve(401,"invalid local proxy api key");l={clients:e.clients,scope:Wr}}r.handleUpgrade(i,a,u,v=>{new st(v,l,o)})})().catch(c=>{let l=502;(c instanceof ve||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let v=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",p=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${v}\r
2
+ Connection: close\r
3
+ \r
4
+ ${p}\r
5
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}function Ci(t,e,n=new ot){new st(t,e,n)}A();import zr from"os";import Yr from"path";import{fileURLToPath as Xr}from"url";import{format as Qr}from"util";var An="0.6.1";var Tn=4141,Zr=An,ji={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 eo(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 Gi(t,e,n){let r={...t,...eo(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,delete r.URUN_SESSION_TOKEN_SECRET,r}function Hi(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(c=>c==="-m"||c==="--model"||c.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function Ji(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Wi(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Vi(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=Xr(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 Pn(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 Ki(t){if(t[0]!=="--port")return null;let e=Pn(t[1]);return t.splice(0,2),e}function zi(t){let e=t.indexOf("--port");if(e===-1)return Tn;let n=Pn(t[e+1]);return t.splice(e,2),n}function Yi(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 Pt(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 Xi(t){let e=to(Pt(t,"URUN_BASE_URL")),n=Pt(t,"URUN_ORG_ID"),r=Pt(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?On(s,"URUN_API_URL"):cn,a=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"jwt",jwt:u}};let d=(t.URUN_API_KEY??"").trim();if(d){let c=(t.URUN_GATEWAY_URL??"").trim(),l=c?On(c):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"api-key",apiKey:d,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 to(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 On(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 Qi(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Zr}}function no(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 ro=250;async function oo(t,e=ro){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Cn=2e3;async function so(t,e=Cn){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 Zi(t,e,n=Tn,r=Cn){if(t!=null)return{mode:"spawn",port:t};let o=await oo(n);if(o!==null&&no(o,e)){let s=await so(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 ea(t,e=zr.homedir()){return Yr.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Ct=["log","info","warn","error","debug","trace"];function ta(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Ct.map(a=>[a,n[a]]));for(let a of Ct)n[a]=(...u)=>{t.write(`${Qr(...u)}
6
+ `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of Ct)n[a]=i[a]}}var io=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ln(t){let e=t?.code;return typeof e=="string"&&io.has(e)}function he(t,e){try{return t.write(e),!0}catch(n){if(Ln(n))return!1;throw n}}function na(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Ln(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
7
+ `)}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 ra(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}
8
+ `)}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}
9
+ `)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
10
+ `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function oa(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}A();import{SessionFailedError as po}from"@urun-sh/core";A();import{randomUUID as ao}from"crypto";function k(t){return`${t}_${ao().replace(/-/g,"").slice(0,24)}`}var it=4*1024*1024,Lt=8*1024*1024,at=512,ut=20*1024*1024;function D(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ae(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:k("event"),error:t}}function Mt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},uo={model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},co={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},lo={format:!0,voice:!0,speed:!0};function Mn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function qe(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new E("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in uo));if(o.length>0)throw new E(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new E("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new E("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new E("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new E(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new E("voice must be a string or null","voice");if(!n.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new E(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new E("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new E(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new E("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new E("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new E("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new E(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new E("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in co))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Mn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=qe({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let c=qe({turn_detection:d.turn_detection},s,n);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in lo))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Mn(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function dt(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function $t(t,e){let n=t;if(!n||typeof n!="object")throw new E("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:k("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new E("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new E("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new E(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new E(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:k("item"),type:"message",role:r,content:o}}throw new E(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ut(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var mo=1001,fo=1011,$n=t=>t.slice(0,120),go=/^[A-Za-z0-9+/=]*$/,ho=2;function yo(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ho)return!1;return!0}var De=class{id=k("conn");ws;binding;onClosed;config=Mt();sessionId=k("sess");conversationId=k("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:k("event"),session:dt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:k("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(U(Ae("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:k("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:k("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=k("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:k("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:k("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:k("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(D("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>it){this.fail(D("frame_too_large",`frame exceeds the ${it}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(D("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(D("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Ae(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=qe(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:k("event"),session:dt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=$t(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(U(D("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:k("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(U(D("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:k("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(U(D("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:k("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(U(D("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!go.test(e.audio)){this.send(U(D("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>ut){this.send(U(D("buffer_full",`uncommitted input audio exceeds the ${ut}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:k("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(D("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=k("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:k("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(U(D("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(D("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(D("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(U({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(D("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(R=>R!=="text"&&R!=="audio")){this.send(U(D("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(U(D("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=k("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Ut(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,c=n.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,v=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...l!==void 0?{max_output_tokens:l}:{},...v!==void 0?{tools:v}:{},...p!==void 0?{tool_choice:p}:{}};for(let R of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R);this.inFlight=(async()=>{let R=[],x=S=>{this.responseFlushed?this.send(S):R.push(S)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:k("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:k("event"),response:this.responseObject(o,"in_progress")});for(let S of R)this.send(S);R.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let S;try{S=await this.upstreamStream(w,r)}catch(f){this.upstreamTurnFault(f,o);return}try{for await(let f of S){if(this.cancelled)break;let _=f;if(_.type==="error"){let m=this.upstreamErrorBody(_);this.responseFlushed?this.send(U(m)):this.send({type:"response.failed",event_id:k("event"),response:this.failedResponse(o,m)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(o,y.nextOutputIndex++),y.messageOpen=!0),x({type:"response.output_text.delta",event_id:k("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:_.delta}),y.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){g();let m=typeof _.delta=="string"?_.delta:"",b=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${o}_fc_${y.nextOutputIndex}`,I=y.tools.get(b);if(!I){let O=typeof _.name=="string"&&_.name.length>0?_.name:void 0;I={outputIndex:y.nextOutputIndex++,name:O,args:""},y.tools.set(b,I),x({type:"response.output_item.added",event_id:k("event"),response_id:o,output_index:I.outputIndex,item:{id:b,object:"realtime.item",type:"function_call",call_id:b,name:O??"",arguments:"",status:"in_progress"}})}typeof _.name=="string"&&_.name.length>0&&(I.name=_.name),I.args+=m,x({type:"response.function_call_arguments.delta",event_id:k("event"),item_id:b,response_id:o,output_index:I.outputIndex,call_id:b,name:I.name??"",delta:m});continue}if(_.type==="response.completed"){h=_.response??null;continue}}}catch(f){this.upstreamTurnFault(f,o);return}if(this.cancelled)return;this.closeOpenItems(o,y,s),g(),this.send({type:"response.done",event_id:k("event"),response:this.doneResponse(o,s,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(yo(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:k("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:k("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:k("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:k("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:k("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:k("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:k("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:k("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:k("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:k("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:k("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:k("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:k("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Ae("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof le){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof po&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ae(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:k("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(D("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:k("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>at&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${at} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Lt){this.ws.close(mo,$n("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(U(e)),this.ws.close(fo,$n(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Un(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Un(this.id,e)}}},Nt=[];function Un(t,e){Nt.push({id:t,reason:e}),Nt.length>256&&Nt.shift()}A();import{SessionFailedError as bo}from"@urun-sh/core";A();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as _o}from"@urun-sh/core";var wo={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},vo={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"};function Bt(t,e){let n=vo[t.code];return e?`${n} (${e})`:n}function ct(t){if(t==null)return null;let e=wo[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function lt(t){if(t.kind==="create-failed")return ct(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=_o;return ct(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as xo}from"ws";var Dt="/v1/realtime",ko=t=>t.slice(0,120);function Ro(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
11
+ Connection: close\r
12
+ Content-Type: text/plain\r
13
+ \r
14
+ ${ko(n)}\r
15
+ `),t.destroy()}function So(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
16
+ `}function Eo(t){he(process.stdout,t)}function Io(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function qt(t){return t.audioSession?.audio.sessionId??void 0}function Ft(t,e){let n=new xo({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Dt)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=k("rtup"),d=Io(o),c=f=>{(e.log??Eo)(So(f))};c({stage:"accept",conn:u,model:d}),s.resume();let l=new AbortController,v=null,p=f=>{v??=f,l.abort(new Error(v))},w=()=>p("client socket closed"),R=()=>p("client socket closed (half-close)"),x=f=>p(`client socket error: ${f.message}`);s.once("close",w),s.once("end",R),s.once("error",x);let g=()=>{s.removeListener("close",w),s.removeListener("end",R),s.removeListener("error",x)},y=f=>{c({stage:"close",conn:u,model:d,...f})},h=f=>{let _=f,m=_.session!=null&&typeof _.session.sendResponseCreate=="function",b=_.clients!=null&&typeof _.clients.createResponse=="function";if(!m&&!b)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((I,O)=>{n.handleUpgrade(o,s,i,C=>{try{new De({ws:C,binding:f,onClosed:(V,X)=>{y({while:"live",reason:X.reason})}}),c({stage:"admit",conn:u,model:d,...qt(f)===void 0?{}:{session:qt(f)}}),I()}catch(V){O(V)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,l.signal).then(async f=>{if(l.signal.aborted){g();let _=qt(f);try{await f.release?.()}catch(m){y({while:"queued",..._===void 0?{}:{session:_},reason:v??"client socket closed",release_failed:m instanceof Error?m.message:String(m)});return}y({while:"queued",..._===void 0?{}:{session:_},reason:v??"client socket closed",released:!0}),s.destroy();return}g(),await h(f)}).catch(f=>{let _=f instanceof bo?lt(f):null,m=null;if(f!==null&&typeof f=="object"&&"status"in f){let O=f.status;typeof O=="number"&&(m=O)}let b=m??_?.status??502,I=f instanceof Error?f.message:String(f);y({while:"queued",...l.signal.aborted?{reason:v??"client socket closed"}:{reason:I,status:b}}),s.destroyed||Ro(s,b,I)}).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()))}}A();A();A();import{createServer as oi}from"http";A();import{WebSocketServer as Do,WebSocket as Je}from"ws";A();A();import{randomUUID as Ao}from"crypto";var Nn="Inference-Id";function Fe(){return Ao()}function jt(t){return t==="/v1"||t.startsWith("/v1/")}function Bn(t,e){if(!jt(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function je(t){return`resp_${t}`}function qn(t){return`chatcmpl-${t}`}function Dn(t){return`msg_${t}`}function ne(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Fn(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function jn(t){return`${JSON.stringify(t)}
17
+ `}var Oo=256,To=128;function ee(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,To)}var be=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Oo?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Po=256;function Co(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var xe=class extends Error{},Oe=class{conversations=new Map;thread(e,n){let r=Co(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new xe(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Po)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Gn=new WeakMap;function Ge(t){let e=Gn.get(t);return e||(e=new Oe,Gn.set(t,e)),e}function Te(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function oe(t){return t.find(e=>e.type==="response.completed")?.response??null}function Pe(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var ye=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Lo=["<tool_call>","<function="];function Mo(t){return Lo.find(e=>t.includes(e))}function ke(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Re(t,e,n){if(!(!t||e>0))return Mo(n)}function Ce(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function $o(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Gt(t,e){let n=$o(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var re=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Le(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof xe?new re(n.message,"previous_response_not_found",400,"previous_response_id"):new re(String(n instanceof Error?n.message:n),"invalid_input")}}function Hn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ht(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new re("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Hn(e)!==void 0?{response_format:Hn(e)}:{}},o)}async function He(t){let{body:e,clients:n,store:r,stats:o}=t,s=Le(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=ee(e);o.model(d);let c=Array.isArray(e.tools)&&e.tools.length>0,l=t.turn,v=await Ht(n,e,s,!0,l?ne(l):void 0);return{responseId:i,events:qo({events:v,conversation:s,responseId:i,modelKey:d,requestHadTools:c,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Uo(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Bo(o[i++],u):u),...No(r,n)]}function No(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let c=d;return c.type==="message"?!n:c.type==="reasoning"?!r:c.type==="function_call"?!a&&!u.has(o(c)):!0})}function Bo(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*qo(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,c=[],l=P=>P.response&&typeof P.response=="object"?{...P,response:{...P.response,id:r}}:P,v=`item_${r.slice(5)}`,p=!1,w=!1,R=0;function*x(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let g=[],y=(P,M)=>{g.push({output_index:P,item:M})},h=!1,S=0,f="",_=0,m="";function*b(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:f,output_index:S,content_index:0,text:m};let P={id:f,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:m}],status:"completed"};yield{type:"response.output_item.done",output_index:S,item:P},y(S,P),m=""}let I=!1,O=0,C="",V=0,X="",K="";function*Q(P){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:C,output_index:O,content_index:0,text:X},yield{type:"response.content_part.done",item_id:C,output_index:O,content_index:0,part:{type:"output_text",text:X}};let M={id:C,type:"message",role:"assistant",status:P,content:[{type:"output_text",text:X}]};yield{type:"response.output_item.done",output_index:O,item:M},y(O,M),X=""}let ue=new ye,q=null,de=-1;function*fe(P){if(!q)return;let M=q;q=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let H={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:P};yield{type:"response.output_item.done",output_index:M.outputIndex,item:H},y(M.outputIndex,H)}let tt=!1;for await(let P of d.track(e,o,t.turn)){c.push(P);let M=String(P.type??"");if(M==="response.created"||M==="response.in_progress"){p=!0,yield l(P);continue}if(M==="response.output_item.added"){w=!0,yield l(P);continue}if(M==="response.reasoning_text.delta"&&!w){yield*x(),h||(h=!0,S=R++,_+=1,f=_===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${_}`,yield{type:"response.output_item.added",output_index:S,item:{id:f,type:"reasoning",summary:[],content:[],status:"in_progress"}}),m+=String(P.delta??""),yield{type:"response.reasoning_text.delta",item_id:f,output_index:S,content_index:0,delta:P.delta};continue}if(M==="response.output_text.delta"&&!w){yield*x(),yield*b(),I||(I=!0,O=R++,V+=1,C=V===1?v:`${v}_${V}`,yield{type:"response.output_item.added",output_index:O,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:O,content_index:0,part:{type:"output_text",text:""}}),X+=String(P.delta??""),K+=String(P.delta??""),yield{type:M,item_id:C,output_index:O,content_index:0,delta:P.delta};continue}let H=w?null:Pe(P);if(H){if(yield*x(),yield*b(),yield*Q("completed"),ue.add(H),H.tool_index!==de){yield*fe("completed"),de=H.tool_index;let ce=R++;q={fcId:`fc_${r.slice(5)}_${H.tool_index}`,outputIndex:ce,callId:H.call_id,name:H.name,args:""},yield{type:"response.output_item.added",output_index:ce,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(H.call_id&&(q.callId=H.call_id),H.name&&(q.name=H.name),q.args+=H.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:H.delta});continue}if(M==="response.completed"&&!w){let ce=Te(P.response),N=Re(s,ue.size+ce.length,K);if(N){tt=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(o,N)}};break}if(yield*b(),yield*Q("completed"),yield*fe("completed"),ue.size===0)for(let ge of ce){let Ie=R++,nt=ge.id??ge.call_id??`fc_${Ie}`,At=ge.arguments??"",un={id:nt,type:"function_call",call_id:ge.call_id??nt,name:ge.name??""};yield{type:"response.output_item.added",output_index:Ie,item:{...un,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:nt,output_index:Ie,delta:At},yield{type:"response.function_call_arguments.done",item_id:nt,output_index:Ie,arguments:At};let dn={...un,arguments:At,status:"completed"};yield{type:"response.output_item.done",output_index:Ie,item:dn},y(Ie,dn)}let Z=Uo(g,P.response);yield Z.length>0?l({...P,response:{...P.response,output:Z}}):l(P);continue}yield l(P)}if(yield*b(),yield*Q("incomplete"),yield*fe("incomplete"),i&&!tt){let P=oe(c);u.remember(r,n,Gt(P,Ce(c,P)),a)}}var Fo="/v1/responses",jo=64*1024*1024,Go=8*1024*1024,Ho=16,Jn=32,Wn=3600*1e3,Jo=/^[A-Za-z0-9._-]{1,256}$/;function te(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Wo=te(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Vt(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Vo(t){for(;t.bufferedAmount>Go&&t.readyState===Je.OPEN;){let{promise:e,resolve:n}=Vt();setTimeout(n,5),await e}}var Jt=class extends Oe{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof xe))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Wt=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Jt(Ge(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(te(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Wn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Wn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(te(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(te(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(te(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(te(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(te(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(te(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Jo.test(o.stream_id)){this.sendFrame(Wo);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Jn){this.sendFrame(te(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Jn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await He({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:je(Fe())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Je.OPEN)break;this.send(i,n),await Vo(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=je(Fe());try{let o=Le(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof re)return te(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof $)return te(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof le)return te(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?te(o.status,{type:o.openaiType,message:r},n):te(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Ho;){let{promise:e,resolve:n}=Vt();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Je.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Je.OPEN||this.ws.send(JSON.stringify(e))}};function pt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
18
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
19
+ Connection: close\r
20
+ Content-Type: text/plain; charset=utf-8\r
21
+ Content-Length: ${Buffer.byteLength(o)}\r
22
+ \r
23
+ ${o}`)}function Vn(t,e){let n=new Do({noServer:!0,maxPayload:jo}),r=new be,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(c,l,v)=>{let p;try{p=new URL(c.url??"/","http://localhost")}catch{pt(l,400,"malformed upgrade URL");return}if(l.on("error",()=>l.destroy()),l.on("close",()=>i.delete(l)),p.pathname!==Fo){i.add(l);return}s.add(l);let w=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){pt(l,401,"invalid local proxy api key");return}let R;try{R=await a(c)}catch(x){let g=e.statusOf?.(x)??null;pt(l,g?.status??500,"upstream resolver rejected the connection");return}u||l.destroyed||(w=!0,n.handleUpgrade(c,l,v,x=>{s.delete(l),o.add(x),x.on("close",()=>o.delete(x));try{new Wt(x,R,r,e.statusOf)}catch{o.delete(x),x.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!w&&!l.destroyed&&pt(l,500,"responses websocket upgrade failed")}).finally(()=>s.delete(l))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:c,resolve:l}=Vt();if(u)return l(),c;u=!0,t.off("upgrade",d);for(let p of s)p.destroy();s.clear();for(let p of i)p.destroy();i.clear();for(let p of o)p.close(1001,"server shutting down");let v=setTimeout(()=>{for(let p of o)p.readyState!==Je.CLOSED&&p.terminate()},2e3);return v.unref?.(),n.close(()=>{clearTimeout(v),l()}),c}}}A();A();var Y=class extends Error{};async function mt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Y(`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 Y(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function ft(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Y(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,c]of Object.entries(t.headers))if(typeof c=="string")i.set(d,c);else if(Array.isArray(c))for(let l of c)i.append(d,l);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Y?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Kn="/v1/images/generations",gt="/v1/images/edits";function zn(t){return t===Kn||t===gt}var Yn="/v1/images/models";async function Xn(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 L=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ko=16*1024*1024,Qn=64*1024*1024;function Zn(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 We(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 er(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let l of o){if(l.type==="error"){let v=l.error??{};throw new L(502,`image upstream error: ${String(v.message??"upstream reported an error")}`)}if(l.type==="response.completed"){s=l.response??null;break}}if(s===null)throw new L(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 L(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 a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(Zn(d)===null)throw new L(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function tr(t){return t instanceof L?t:t instanceof $?new L(404,t.message):new L(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function nr(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 We(r,new L(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 rr(t,e){t&&(t.outputUnits=e.images.length)}function or(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 zo={model:!0,prompt:!0,response_format:!0,n:!0};async function sr(t,e,n){let r=n.maxBodyBytes??Qn;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${Kn}`);let o;try{o=JSON.parse((await mt(t,r)).toString("utf8")||"{}")}catch(l){throw l instanceof Y?new L(413,l.message):new L(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new L(400,"request body must be a JSON object");let s=o;for(let l of Object.keys(s))if(!zo[l])throw new L(400,`request field "${l}" 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.`,l);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new L(400,"model must be a string","model");await Xn(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new L(400,`n=${JSON.stringify(u)} 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 L(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 nr(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:i}];try{let l=await er(n.clients,a,c,n.turn?ne(n.turn):void 0);rr(n.turn,l),or(e,l)}catch(l){throw tr(l)}}catch(o){if(o instanceof Y){We(e,new L(413,o.message));return}if(o instanceof L){We(e,o);return}throw o}}var Yo={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ir(t,e,n){let r=n.maxBodyBytes??Qn,o=n.maxImagePartBytes??Ko;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${gt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new L(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ft(t,r)}catch(p){throw p instanceof Y?new L(413,p.message):new L(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new L(400,"model must be a string field","model");let d=u===null?void 0:u;await Xn(n.turn,n.clients,d);let c=i.get("response_format")??"b64_json";if(c!=="b64_json")throw new L(400,`response_format ${JSON.stringify(c)} 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 i.keys())if(!Yo[p])throw new L(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 l=[];for(let p of["image","image[]"])for(let w of i.getAll(p)){if(!(w instanceof File))throw new L(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(w.size>o)throw new L(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let R=new Uint8Array(await w.arrayBuffer()),x=Zn(R);if(x===null)throw new L(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);l.push({bytes:R,mime:x})}if(l.length===0)throw new L(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await nr(n.imageModels,d,"edit",e))return;let v=[{type:"input_text",text:a}];for(let{bytes:p,mime:w}of l)v.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(p).toString("base64")}`});try{let p=await er(n.clients,d,v,n.turn?ne(n.turn):void 0);rr(n.turn,p),or(e,p)}catch(p){throw tr(p)}}catch(s){if(s instanceof Y){We(e,new L(413,s.message));return}if(s instanceof L){We(e,s);return}throw s}}A();var Ke="/v1/audio/speech";function lr(t){return t===Ke}var ar=4096,Xo=18e4,Qo=5e3,Zo=64*1024*1024,ur=8,dr=5,yt="voice_applied",es="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 Kt(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 _t=class extends T{constructor(e){super(502,e)}};async function ts(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 ns(t,e){t&&(t.outputUnits=e/(24e3*2))}var rs=2;function os(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>rs)return!1;return!0}function ss(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 cr=new WeakMap,ht=new WeakMap;function is(t,e){let n=ht.get(t)??0;if(n>=ur)throw new T(503,`this model's speech queue is full \u2014 ${ur} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${dr}s`,void 0,dr);ht.set(t,n+1);let r=cr.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return cr.set(t,s),(async()=>{await r;try{return await e()}finally{ht.set(t,(ht.get(t)??1)-1),o()}})()}async function as(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(i){if(!(i instanceof le))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 Ve(t){return t instanceof T?t:t instanceof $?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function us(t,e,n,r,o,s,i){return is(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,c=!1,l=!1,v,p=new Promise(S=>{v=S}),w=()=>{c&&!l&&d>=o.quietRunFrames&&(l=!0,v())},R=e.onOutputAudio(S=>{let f=Buffer.from(S,"base64");if(f.byteLength===0)return;let _=os(f);if(!u){if(_)return;u=!0}a.push(f),d=_?d+1:0,w()}),x=null,g,y,h;try{h=(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 f=new Promise(I=>{y=setTimeout(I,s.capMs)}),_=!1;for(;;){let I=h.next(),O=await Promise.race([I,f]);if(O===void 0){_=!0,I.catch(()=>{});break}if(O.done)break;let C=O.value;if(C.type==="error"){let V=C.error??{};throw await h.return?.(),new T(502,`speech upstream error: ${String(V.message??"upstream reported an error")}`)}if(C.type==="response.completed"){x=C.response??null,c=!0,w(),await h.return?.();break}}if(clearTimeout(y),_)throw new T(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(x===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let m=!1;if(await Promise.race([p,new Promise(I=>{g=setTimeout(()=>{m=!0,I()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let I=x[yt];if(typeof I!="string"||I!==r.voice){let O=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${yt} ${JSON.stringify(I)}`:`no ${yt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw l?new _t(O):new T(502,O)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(m&&!l&&d<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`);let b=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(b),completed:x}}catch(S){throw S instanceof _t||await as(t,n,h,s.returnBoundMs),S}finally{g!==void 0&&clearTimeout(g),y!==void 0&&clearTimeout(y),R()}})}async function ds(t,e,n){let r;try{r=await t(e)}catch(o){throw Ve(o)}return r?!0:(Kt(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 cs={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ls="wav, pcm";async function pr(t,e,n){let r=n.maxBodyBytes??Zo,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Ke}`);let i;try{i=JSON.parse((await mt(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof Y?new T(413,h.message):new T(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new T(400,"request body must be a JSON object");let a=i;for(let h of Object.keys(a))if(!cs[h])throw new T(400,`request field "${h}" 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.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(u.length>ar)throw new T(400,`input is ${u.length} chars \u2014 over the ${ar}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new T(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.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 ${Ke} against a stale copy of the list`);let l;try{l=await n.clients.speechVoices(d)}catch(h){throw Ve(h)}if(l.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${l.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let v=typeof c=="string"?c:void 0;if(v!==void 0&&l.published.length>0&&!l.published.includes(v))throw new T(400,`voice ${JSON.stringify(v)} is not one of the voices this model publishes \u2014 accepted voices: ${l.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 ${ls} \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 w=a.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new T(400,"speed, when present, must be a number","speed");if(w!==1)throw new T(400,`speed=${JSON.stringify(w)} 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 R=a.instructions;if(R!==void 0){if(typeof R!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(R.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 ts(n.turn,n.clients,d);let x=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",x,x),!await ds(n.speechModels,d,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(s())return;let g;try{g=await n.clients.speechSessionHandle(d)}catch(h){throw Ve(h)}let y;try{y=await n.clients.openAudioOn(g)}catch(h){throw Ve(h)}n.turn&&(n.turn.sessionId=y.sessionId);try{let h=await us(n.clients,y,g,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Xo,returnBoundMs:n.turnReturnBoundMs??Qo},s);if(h===null||s())return;if(ns(n.turn,h.pcm.byteLength),e.statusCode=200,v===void 0){let S=h.completed[yt];typeof S=="string"&&e.setHeader(es,S)}p==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ss(h.pcm.byteLength),h.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(h.pcm))}catch(h){throw Ve(h)}}catch(i){if(i instanceof Y){Kt(e,new T(413,i.message));return}if(i instanceof T){Kt(e,i);return}throw i}}A();var wt="/v1/audio/transcriptions";function mr(t){return t===wt}var fr="/v1/audio/models",ps=16*1024*1024,ms=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function zt(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 gr(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 fs(t){if(!gr(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,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,c=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:c}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+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 gs(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 hs(t,e){t&&(t.outputUnits=e.seconds)}async function ys(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=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},c=typeof d.type=="string"?d.type:"upstream_error",l=String(d.message??"upstream reported an error");throw new B(c==="invalid_request_error"?400:502,`transcription upstream error: ${l}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Ce(i,a)}function hr(t){return t instanceof B?t:t instanceof $?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function _s(t,e,n){let r;try{r=await t(e)}catch(o){throw hr(o)}return r?!0:(zt(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 ws=new Set(["file","model","language","response_format"]);async function yr(t,e,n){let r=n.maxBodyBytes??ms,o=n.maxAudioPartBytes??ps;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${wt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ft(t,r)}catch(g){throw g instanceof Y?new B(413,g.message):new B(400,String(g instanceof Error?g.message:g))}let a=new Map;for(let g of i.keys()){if(!ws.has(g))throw new B(400,`form field "${g}" 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.`,g);a.set(g,(a.get(g)??0)+1)}for(let[g,y]of a)if(y>1)throw new B(400,`form field "${g}" appears ${y} 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`,g);let u=i.get("model");if(u!==null&&typeof u!="string")throw new B(400,"model must be a string field","model");let d=u===null?void 0:u,c=i.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let l=c===null?void 0:c,v=i.get("response_format")??"json";if(v!=="json")throw new B(400,`response_format ${JSON.stringify(v)} 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=i.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 w=new Uint8Array(await p.arrayBuffer());if(!gr(w))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 R=fs(w);if(R===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 gs(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await _s(n.transcriptionModels,d,e))return;let x=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let g=await ys(n.clients,d,x,l,n.turn?ne(n.turn):void 0);hs(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw hr(g)}}catch(s){if(s instanceof Y){zt(e,new B(413,s.message));return}if(s instanceof B){zt(e,s);return}throw s}}A();var xr="/v1/usage/requests",_r=1e4,vs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_e=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},J=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},vt=class extends J{constructor(e){super(e),this.name="UsageWithholdingError"}},kr=1024*1024;function Qt(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new _e(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new _e(`"${e}" must be an array of uuid strings`);if(n.length>_r)throw new _e(`"${e}" carries ${n.length} ids; at most ${_r} 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"||!vs.test(s))throw new _e(`"${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 Rr(t){return Qt(t,"inference_ids")}var bs=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","cost_nano_usd","price_version","priced_at"];function Me(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new J(`${n}: ${e} is not a non-empty string (got ${$e(r)})`);return r}function Yt(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new J(`${n}: ${e} is neither null nor a non-empty string (got ${$e(r)})`);return r}function ze(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new J(`${n}: ${e} is not a number (got ${$e(o)})`);if(r&&!Number.isSafeInteger(s))throw new J(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new J(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var xs=40,wr=64,vr=600;function Sr(t){let e=Object.keys(t).sort(),r=e.slice(0,xs).map(o=>o.length>wr?`${o.slice(0,wr)}\u2026`:o).join(", ");return r.length>vr&&(r=`${r.slice(0,vr)}\u2026`),`${e.length} keys present: [${r}]`}function $e(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Xt(t){he(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
24
+ `)}function ks(t,e){let n;try{n=t(e)}catch{br(t,e);return}Rs(n)&&Promise.resolve(n).catch(()=>{br(t,e)})}function Rs(t){return typeof t?.then=="function"}function br(t,e){if(t!==Xt)try{Xt(e)}catch{}}function lu(t,e=Xt){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Sr(t):$e(t);throw new J(`the usage surface answered without a "requests" array: got ${$e(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Ss(n[o],s))}catch(i){if(i instanceof vt||!(i instanceof J))throw i;ks(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new J(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Ss(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new J(`${e} is not an object: got ${$e(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new vt(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of bs)if(!Object.hasOwn(n,o))throw new J(`${e} has no "${o}" column (${Sr(n)})`);let r=ze(n,"http_status",e,!0);if(r===null)throw new J(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Me(n,"inference_id",e),model_id:Me(n,"model_id",e),identity_kind:Me(n,"identity_kind",e),variant:Yt(n,"variant",e),task:Me(n,"task",e),http_status:r,started_at:Me(n,"started_at",e),completed_at:Me(n,"completed_at",e),prompt_tokens:ze(n,"prompt_tokens",e,!0),completion_tokens:ze(n,"completion_tokens",e,!0),output_units:ze(n,"output_units",e,!1),cost_nano_usd:ze(n,"cost_nano_usd",e,!0),price_version:Yt(n,"price_version",e),priced_at:Yt(n,"priced_at",e)}}function bt(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 J(`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 J(`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)}}import{SessionAllocationError as si,SessionFailedError as ii}from"@urun-sh/core";A();var Zt="/partners/huggingface/v1/billing/requests";function Es(t){return Qt(t,"requestIds")}function Is(t){return t>=200&&t<=399}function As(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Is(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Er(t,e){let n=Es(t),r=await e(n);return bt(r,n),As(r)}A();var Os={"/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 Ts(t){return Os[t]??null}var Or=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Ps(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Cs(t){return t==="surface"}function Ls(t){let e=t?.ledgerFailureReason;return Or.includes(e)?e:"unknown"}var Ms=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ir=["priced","unpriced"],$s={written:Ir,already_written:Ir,skipped:Ms,failed:Or},_u=Object.entries($s).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Us(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Ns(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 Bs=256,Ar=4096,Ye=12e4,qs=250,Ds=8e3,pe=[],en=new Set,Xe=0,Ue=!1;function wu(){return pe.length}function vu(t=Date.now()){let e=pe[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var xt=new Set;function Tr(){return Xe===0&&pe.length===0}function Pr(){if(Tr()){Ue=!1;for(let t of[...xt])t()}}async function bu(t=Cr){return Tr()?!0:await new Promise(e=>{let n=null,r=()=>{xt.delete(r),n&&clearTimeout(n),e(!0)};xt.add(r),n=setTimeout(()=>{xt.delete(r),e(!1)},t),n.unref?.()})}function xu(){Ue=!0;let t=[...pe.splice(0,pe.length),...en];for(let e of t)e.settled||Se(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Cr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Pr(),t.length}var Cr=5e3;function Lr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
25
+ `}function Fs(t){he(process.stdout,t)}function Mr(t,e){try{t(e)}catch{}}function $r(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Fs,o=Ts(e.path);if(o===null)return;let s=c=>{try{n.observe(c)}catch{}},i=(c,l)=>{s({outcome:"skipped",reason:c}),Mr(r,Lr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:l}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Ns(e),completed_at:e.ts,billable_outcome:Us(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(pe.length>=Ar){i("queue_full",`${pe.length} ledger writes are already waiting (capacity ${Ar}, ${Xe} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}pe.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Xe<Bs&&(Xe+=1,js())}async function js(){try{for(;;){let t=Gs();if(t===void 0)return;en.add(t);try{await Hs(t)}finally{en.delete(t)}}}finally{Xe-=1,Pr()}}function Gs(){let t=Date.now();for(;;){let e=pe.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Ye)return e;Se(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 ${Ye}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 Hs(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Se(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=Ps(o);if(s!==null){Se(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=Ls(o),a=Date.now()-t.queuedAt;if(Ue){Se(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(Cs(i)&&a<Ye){if(await Ws(Js(t.attempts)),Ue||Date.now()-t.queuedAt>=Ye){let u=Date.now()-t.queuedAt;Se(t,{outcome:"failed",reason:Ue?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ue?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${Ye}ms dwell bound (waited ${u}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}Se(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Js(t){return Math.min(Ds,qs*2**Math.max(0,t-1))}function Ws(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Se(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Mr(t.report,Lr(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}A();import*as tn from"crypto";var Vs="urun-runtime-key-v1";function Ks(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return tn.createHmac("sha256",t).update(`${Vs}|${e}`,"ascii").digest("base64url")}var zs="decision-intake",kt=6e4,Ys=kt/1e3+5,Ur=3,nn=15;function Xs(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:zs,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=tn.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function Qs(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function Zs(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(kt)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new se(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${kt}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!Qs(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=nn)}var ei=nn*1e3,ti=nn*500,ni=256,Nr=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new se("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new se(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let c=null;for(let l=0;l<Ur;l++){let v=this.pick(d);if(v===null)throw new se(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let p=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,w=Xs(Ks(this.opts.secret,p),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},Ys);try{return{...await this.post(v,e,w),target:{...r,fnName:s}}}catch(R){if(R instanceof Ee)throw R;c=R;let x=this.replicas.get(v)??{outstanding:0,cooldownUntil:0};x.cooldownUntil=this.nowMs()+5e3,this.replicas.set(v,x);let g=this.presenceCache.get(u);g&&(g.rows=g.rows.filter(y=>y.address!==v),g.rows.length===0&&this.presenceCache.delete(u))}}throw new se(`no runtime for app=${o} answered within ${Ur} attempts: ${String(c instanceof Error?c.message:c)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>ei)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>ti&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=ni;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return Zs({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??kt)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ee(s.status,i);return{status:s.status,body:i,completed:ri(i)}}finally{o.outstanding-=1}}};function ri(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ee=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},se=class extends Error{};function sn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function F(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function W(t,e,n,r="invalid_request_error",o){F(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function an(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);F(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ie(t,e,n,r){F(t,e,{type:"error",error:{type:n,message:r}})}function ae(t,e,n){if(e==="anthropic"){F(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}F(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ai=64*1024*1024,Qe=class extends Error{};async function Br(t,e=ai){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Qe(`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 Fr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Rt(t){let e=Fr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function qr(t){let e=Rt(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 ui(t,e){let n=Fr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function di(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function ci(t,e){let n=di(e);n&&(t.timing=n)}function me(t,e){ui(t,e),ci(t,e)}async function It(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 jr(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 li(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 St=class extends Error{};function pi(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 St(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function mi(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:pi(n.role,n.content)})}return e}function rn(t){return Te(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 fi(t,e,n,r,o,s){let i=je(s.id),a=t.stream===!0;if(s.model=ee(t),s.stream=a,await It(s,e,typeof t.model=="string"?t.model:void 0),a){let g;try{g=await He({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(y){if(y instanceof $){ae(r,"openai",y);return}if(y instanceof re){W(r,y.status,y.message);return}throw y}sn(r);for await(let y of g.events)y.type==="error"&&(s.streamError=!0),y.type==="response.completed"&&me(s,y.response),r.write(`event: ${String(y.type??"message")}
26
+ data: ${JSON.stringify(y)}
27
+
28
+ `);r.write(`data: [DONE]
29
+
30
+ `),r.end();return}let u;try{u=Le(n,t)}catch(g){if(g instanceof re){W(r,g.status,g.message);return}throw g}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ee(t);o.model(c);let l=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await Ht(e,t,u,!1,ne(s))}catch(g){if(g instanceof $){ae(r,"openai",g);return}if(g instanceof re){W(r,g.status,g.message);return}throw g}let p=[],w=null;for await(let g of o.track(v,c,s)){if(p.push(g),g.type==="error"){an(r,g);return}g.type==="response.completed"&&(w=g.response)}if(w==null){W(r,502,"upstream produced no response.completed event","upstream_error");return}me(s,w);let R=Ce(p,w),x=Re(l,Te(w).length,R);if(x){W(r,502,ke(c,x),"upstream_error");return}d&&n.remember(i,u,Gt(w,R),d),F(r,200,{...w,id:i})}async function gi(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){W(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=qn(o.id),u;try{u=mi(s)}catch(m){if(m instanceof St){W(n,400,m.message);return}throw m}let d=ee(t);r.model(d),o.model=d,o.stream=t.stream===!0,await It(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let m;try{m=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(b){if(b instanceof $){ae(n,"openai",b);return}throw b}if(m!==null){try{let b=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=Tt(b.target),me(o,b.completed),F(n,200,{...b.body,id:a})}catch(b){if(b instanceof $){ae(n,"openai",b);return}if(b instanceof Ee){F(n,b.status,b.body);return}if(b instanceof se){W(n,503,b.message,"upstream_error");return}throw b}return}}let l;try{l=await e.createResponse({model:t.model,input:u,stream:!0,tools:li(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},ne(o))}catch(m){if(m instanceof $){ae(n,"openai",m);return}throw m}if(t.stream===!0){sn(n);let m=[],b=new ye,I="";n.write(`data: ${JSON.stringify(Ne(a,i,{role:"assistant"},null))}
31
+
32
+ `);for await(let K of r.track(l,d,o)){m.push(K);let Q=Pe(K);if(K.type==="response.output_text.delta"&&typeof K.delta=="string")I+=K.delta,n.write(`data: ${JSON.stringify(Ne(a,i,{content:K.delta},null))}
33
+
34
+ `);else if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")n.write(`data: ${JSON.stringify(Ne(a,i,{reasoning_content:K.delta},null))}
35
+
36
+ `);else if(Q){let{call:ue,isNew:q}=b.add(Q),de=q?{index:Q.tool_index,id:ue.id??`call_${Q.tool_index}`,type:"function",function:{name:ue.name??"",arguments:Q.delta}}:{index:Q.tool_index,function:{arguments:Q.delta}};n.write(`data: ${JSON.stringify(Ne(a,i,{tool_calls:[de]},null))}
37
+
38
+ `)}else if(K.type==="error"){o.streamError=!0,n.write(`data: ${JSON.stringify({error:K})}
39
+
40
+ `),n.end();return}}let O=rn(oe(m)),C=Re(c,b.size+O.length,I);if(C){o.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(d,C)}})}
41
+
42
+ `),n.end();return}b.size===0&&O.length>0&&n.write(`data: ${JSON.stringify(Ne(a,i,{tool_calls:O},null))}
43
+
44
+ `);let V=b.size>0||O.length>0;n.write(`data: ${JSON.stringify(Ne(a,i,{},V?"tool_calls":"stop"))}
45
+
46
+ `);let X=Rt(oe(m));me(o,oe(m)),X&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:qr(oe(m))})}
47
+
48
+ `),n.write(`data: [DONE]
49
+
50
+ `),n.end();return}let v="",p="",w=[],R=new ye;for await(let m of r.track(l,d,o)){w.push(m),m.type==="response.output_text.delta"&&typeof m.delta=="string"&&(v+=m.delta),m.type==="response.reasoning_text.delta"&&typeof m.delta=="string"&&(p+=m.delta);let b=Pe(m);if(b&&R.add(b),m.type==="error"){an(n,m);return}}let x=oe(w);me(o,x);let g=rn(x),y=g.length>0?g:rn({output:R.items()}),h=Re(c,y.length,v);if(h){W(n,502,ke(d,h),"upstream_error");return}let S=y.map(({index:m,...b})=>b),f={role:"assistant",content:v||null},_=p||jr(x);_&&(f.reasoning_content=_),S.length>0&&(f.tool_calls=S),F(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:f,finish_reason:S.length>0?"tool_calls":"stop"}],usage:qr(x)})}var hi="reflex-latest";async function yi(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){W(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:hi,i=ee({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){W(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){W(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){W(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await It(o,e,s),e.stateless?.enabled){let p;try{p=await e.stateless.targetFor(s)}catch(w){if(w instanceof $){ae(n,"openai",w);return}throw w}if(p!==null){try{let w=await e.stateless.decide(t,s);o.catalog=Tt(w.target),me(o,w.completed),F(n,200,w.body)}catch(w){if(w instanceof $){ae(n,"openai",w);return}if(w instanceof Ee){F(n,w.status,w.body);return}if(w instanceof se){W(n,503,w.message,"upstream_error");return}throw w}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ne(o))}catch(p){if(p instanceof $){ae(n,"openai",p);return}throw p}let d=[];try{for await(let p of r.track(u,i,o))if(d.push(p),p.type==="error"){an(n,p);return}}catch(p){if(p instanceof $){ae(n,"openai",p);return}throw p}let c=oe(d);if(c==null){W(n,502,"upstream produced no response.completed event","upstream_error");return}me(o,c);let l=Ce(d,c),v;try{v=JSON.parse(l)}catch{W(n,502,"systemone answer was not valid JSON","upstream_error");return}if(v===null||typeof v!="object"||Array.isArray(v)){W(n,502,"systemone answer was not a JSON object","upstream_error");return}F(n,200,v)}function _i(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Ze=class extends Error{};function Et(t){return new Ze(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function wi(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function vi(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Ze(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function bi(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Et(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Et(`tool_result > ${r}`);e+=String(n.text??"")}return e}function xi(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Et(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:bi(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Et(a)}}return s(),r}function on(t){return Te(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function ki(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){ie(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){ie(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ie(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(m=>typeof m!="string"))){ie(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=Dn(o.id),u=[],d;try{t.system&&u.push({role:"system",content:_i(t.system)});for(let m of s)u.push(...xi(m));d=vi(t.tool_choice)}catch(m){if(m instanceof Ze){ie(n,400,"invalid_request_error",m.message);return}throw m}let c=ee(t);r.model(c),o.model=c,o.stream=t.stream===!0,await It(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await e.createResponse({model:t.model,input:u,stream:!0,tools:wi(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ne(o))}catch(m){if(m instanceof $){ae(n,"anthropic",m);return}throw m}let p=(m,b)=>{n.destroyed||n.write(`event: ${m}
51
+ data: ${JSON.stringify({type:m,...b})}
52
+
53
+ `)};if(t.stream===!0){let m=r.track(v,c,o);sn(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let b=0,I="",O=0,C="none",V=()=>C,X=-1,K=-1,Q=new ye,ue=[],q=()=>{C!=="none"&&(C="none",p("content_block_stop",{index:X}))},de=(N,Z)=>{q(),C=N,X=O++,p("content_block_start",{index:X,content_block:Z})};for await(let N of m){if(n.destroyed)break;ue.push(N);let Z=Pe(N);if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")V()!=="thinking"&&de("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:X,delta:{type:"thinking_delta",thinking:N.delta}});else if(N.type==="response.output_text.delta"&&typeof N.delta=="string")V()!=="text"&&de("text",{type:"text",text:""}),b+=1,I+=N.delta,p("content_block_delta",{index:X,delta:{type:"text_delta",text:N.delta}});else if(Z){let{call:ge}=Q.add(Z);(V()!=="tool"||Z.tool_index!==K)&&(K=Z.tool_index,de("tool",{type:"tool_use",id:ge.id??`call_${Z.tool_index}`,name:ge.name??"",input:{}})),Z.delta&&p("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:Z.delta}})}else if(N.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(N)}}),n.end();return}}if(n.destroyed)return;let fe=oe(ue),tt=Te(fe),P=Re(l,Q.size+tt.length,I);if(P){o.streamError=!0,p("error",{error:{type:"api_error",message:ke(c,P)}}),n.end();return}q();let M=[];if(Q.size===0)try{M=on(fe)}catch(N){o.streamError=!0,p("error",{error:{type:"api_error",message:String(N instanceof Error?N.message:N)}}),n.end();return}O===0&&M.length===0&&(de("text",{type:"text",text:""}),q()),M.forEach(N=>{let Z=O++;p("content_block_start",{index:Z,content_block:{...N,input:{}}}),p("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:JSON.stringify(N.input??{})}}),p("content_block_stop",{index:Z})});let H=Q.size>0||M.length>0,ce=Rt(fe);me(o,fe),p("message_delta",{delta:{stop_reason:H?"tool_use":"end_turn"},usage:ce?{input_tokens:ce.input_tokens,output_tokens:ce.output_tokens}:{output_tokens:b}}),p("message_stop",{}),n.end();return}let w="",R="",x=[],g=new ye;for await(let m of r.track(v,c,o)){x.push(m),m.type==="response.output_text.delta"&&typeof m.delta=="string"&&(w+=m.delta),m.type==="response.reasoning_text.delta"&&typeof m.delta=="string"&&(R+=m.delta);let b=Pe(m);if(b&&g.add(b),m.type==="error"){let I=m.error,O=I?.type==="invalid_request_error";ie(n,O?400:502,O?"invalid_request_error":"api_error",I?.message??JSON.stringify(m));return}if(n.destroyed)break}if(n.destroyed)return;let y=oe(x);me(o,y);let h;try{h=on(y),h.length===0&&g.size>0&&(h=on({output:g.items()}))}catch(m){ie(n,502,"api_error",String(m instanceof Error?m.message:m));return}let S=Re(l,h.length,w);if(S){ie(n,502,"api_error",ke(c,S));return}let f=[],_=R||jr(y);_&&f.push({type:"thinking",thinking:_}),(w||h.length===0)&&f.push({type:"text",text:w}),f.push(...h),F(n,200,{id:a,type:"message",role:"assistant",content:f,model:i,stop_reason:h.length>0?"tool_use":"end_turn",usage:Rt(y)??{input_tokens:0,output_tokens:0}})}function Ri(t){he(process.stdout,t)}function Si(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Ri,a=t.observe,u=new be;return(d,c)=>{let l=new URL(d.url??"/","http://localhost"),v=l.pathname==="/v1/messages"||l.pathname.startsWith("/v1/messages/"),p=(y,h,S,f,_)=>v?ie(c,y,f,h):W(c,y,h,S,_),w=jt(l.pathname),R=l.pathname.startsWith("/partners/"),x=w||R?{id:Fe(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,sessionId:null,timing:null}:null;x&&(c.setHeader(Nn,x.id),c.once("close",()=>{let y=Fn({turn:x,method:d.method??"",path:l.pathname,res:c});i(jn(y)),a?.(y),$r({record:y,ledger:t.ledger??null,req:d})}));let g=()=>Bn(l.pathname,x);(async()=>{if(d.method==="GET"&&l.pathname==="/healthz"){F(c,200,{ok:!0});return}if(d.method==="GET"&&l.pathname==="/stats"){F(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let y=l.pathname===xr?"canonical":l.pathname===Zt?"huggingface":null;if(y){if(d.method!=="POST"){p(405,`${l.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let _=t.usage;if(!_){p(501,`${l.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let m=_.authorize(d),b;try{b=await Br(d,kr)}catch(C){if(C instanceof Qe){p(413,C.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=C=>_.lookup(m,C),O;try{if(y==="canonical"){let C=Rr(b),V=await I(C);bt(V,C),O={requests:V}}else O=await Er(b,I)}catch(C){if(C instanceof _e){p(C.status,C.message,"invalid_request_error","invalid_request_error");return}throw C}F(c,200,O);return}if(l.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${d.method} ${l.pathname} \u2014 the partner surface currently carries ${Zt}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(x&&(x.org=h.tenant??null),d.method==="GET"&&l.pathname==="/v1/models"){if(l.searchParams.get("format")==="openrouter"){if(!h.openRouterModels){p(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}F(c,200,await h.openRouterModels());return}F(c,200,await h.listModels());return}if(d.method==="GET"&&l.pathname===Yn){if(!h.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}F(c,200,await h.listImageModels());return}if(zn(l.pathname)){if(!h.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${l.pathname}`,"not_implemented","not_implemented_error");return}let _={clients:h,imageModels:h.supportsImages,stats:u,turn:g()};l.pathname===gt?await ir(d,c,_):await sr(d,c,_);return}if(d.method==="GET"&&l.pathname===fr){if(!h.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}F(c,200,await h.listSpeechToTextModels());return}if(mr(l.pathname)){if(!h.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${wt}`,"not_implemented","not_implemented_error");return}let _={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:g()};await yr(d,c,_);return}if(lr(l.pathname)){if(!h.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ke}`,"not_implemented","not_implemented_error");return}let _={clients:h,speechModels:h.supportsSpeech,stats:u,turn:g()};await pr(d,c,_);return}if(d.method!=="POST"){p(404,`no route for ${d.method} ${l.pathname}`,"invalid_request_error","not_found_error");return}let S;try{S=await Br(d)}catch(_){if(_ instanceof Qe){p(413,_.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let f=Buffer.byteLength(JSON.stringify(S));if(l.pathname==="/v1/responses"){u.request("responses",f,f),await fi(S,h,Ge(h),c,u,g());return}if(l.pathname==="/v1/chat/completions"){u.request("chat_completions",f,f),await gi(S,h,c,u,g());return}if(l.pathname==="/v1/systemone"){u.request("systemone",f,f),await yi(S,h,c,u,g());return}if(l.pathname==="/v1/messages"){u.request("messages",f,f),await ki(S,h,c,u,g());return}if(l.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",f,f),ie(c,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${l.pathname}`,"invalid_request_error","not_found_error")})().catch(y=>{let h=String(y instanceof Error?y.message:y);if(!c.headersSent){let S=o?.(y)??null;if(S){p(S.status,h,S.openaiType,S.anthropicType);return}if(y instanceof si){let f=ct(y.code);if(f){let _=y.retryAfterSeconds??(f.status===429?30:void 0);_!==void 0&&c.setHeader("Retry-After",String(_)),p(f.status,Bt(f,y.code??void 0),f.openaiType,f.anthropicType,f.code);return}}if(y instanceof ii){let f=lt(y);if(f){let _=f.status===429?30:void 0;_!==void 0&&c.setHeader("Retry-After",String(_)),p(f.status,Bt(f,y.status.sessionId?`session ${y.status.sessionId}`:void 0),f.openaiType,f.anthropicType,f.code);return}}if(y instanceof J){p(502,h,"upstream_error","api_error");return}p(500,h,"proxy_error","api_error","proxy_error");return}x&&(x.streamError=!0),c.destroyed||(v?c.write(`event: error
54
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
55
+
56
+ `):c.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
57
+
58
+ `)),c.end()})}}function Wu(t){let{clients:e,apiKey:n}=t,r=oi(Si(t)),o=Vn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),s=Ft(r,{resolver:Dr(e,n)}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(a))),In(r,{clients:e,apiKey:n}),r}var et=(t,e)=>Object.assign(new Error(e),{status:t});function Ei(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function Ii(t,e,n){if(!t.supportsAudio)throw et(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 r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof $?et(404,a.message):a}if(!r)throw et(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 et(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}function Dr(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 et(401,"invalid local proxy api key")}return Ii(t,Ei(n),r)}}}export{ot as a,In as b,Ci as c,Fo as d,Vn as e,ji as f,eo as g,Gi as h,Hi as i,Ji as j,Wi as k,Vi as l,Ki as m,zi as n,Yi as o,Xi as p,to as q,On as r,Qi as s,oo as t,Zi as u,ea as v,ta as w,he as x,na as y,ra as z,oa as A,De as B,Dt as C,Ft as D,Ei as E,Ii as F,Dr as G,xr as H,J as I,lu as J,Zt as K,_u as L,wu as M,vu as N,bu as O,xu as P,Nr as Q,Si as R,Wu as S};
@@ -0,0 +1 @@
1
+ import{a as T}from"./chunk-K23AZPI4.js";import{a as I}from"./chunk-76BZLCGT.js";import{a as D,b as M,e as A,f as U,g as _,h as $,j}from"./chunk-TMQJY56F.js";import{c as C,f as x,g as F,p as G}from"./chunk-6M5JK4YC.js";import{c as y}from"./chunk-YSFSRI3D.js";y();import{App as B,createClientToken as ee}from"@urun-sh/core";y();import{SessionFailedError as J}from"@urun-sh/core";var P=2;function Q(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function X(e){let t=e?.type;return t==="response.completed"||t==="error"}function W(e){return async function(i,p){return(async function*(){for(let d=1;d<=P;d++){let{app:c,entry:l,identity:r}=await e.sessionFor(i.model);p?.({sessionId:e.sessionIdOf?.(l)??null,identity:r});let w=!1,a=!1;try{let f=await e.createStream(l,i);for await(let g of f){if(X(g)&&(w=!0),Q(g)){if(d>1)continue}else a=!0;yield g}}catch(f){if(f instanceof J&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(c,l,f)}catch{}throw f}if(d<P&&!a){await e.evict(c,l);continue}throw f}if(w)return;if(d<P&&!a){await e.evict(c,l);continue}return}})()}}y();var Y=3,z="llm",Z=new Set(["paused","error"]);function N(e,t){let i=e.doc(z),p=typeof i.onConnectionState=="function",u=typeof e.onPhase=="function";if(!p&&!u)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let d=null,c=!1,l=new Set,r=[],w=a=>{if(!d){d=a;for(let f of[...l])f(a);l.clear()}};return p&&r.push(i.onConnectionState(a=>{c&&(a.consecutiveFailures<Y||w(new A(`the pooled session for app "${t}" is gone: its doc backhaul failed ${a.consecutiveFailures} consecutive times (last close ${a.lastCloseCode===null?"by provider liveness reap":`code ${a.lastCloseCode}`}${a.lastCloseReason?`, reason ${JSON.stringify(a.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),u&&r.push(e.onPhase(a=>{if(a.name==="live"){c=!0;return}c&&Z.has(a.name)&&w(new A(`the pooled session for app "${t}" lost its compute binding (phase "${a.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>d,onGone(a){return d?(a(d),()=>{}):(l.add(a),()=>l.delete(a))},dispose(){l.clear();for(let a of r.splice(0))a()}}}async function*O(e,t){let i=t.gone();if(i)throw i;let p=e[Symbol.asyncIterator](),u,d=new Promise((c,l)=>{u=t.onGone(r=>l(r))});d.catch(()=>{});try{for(;;){let c=await Promise.race([p.next(),d]);if(c.done)return;yield c.value}}finally{u?.(),p.return?.(void 0)}}function q(e,t,i,p){let u=e[i];if(typeof u!="function")throw new Error(`app "${t}" has no function "${i}" (set URUN_FUNCTION)`);let d=p?u(void 0,p):u();if(typeof d.end!="function")throw new Error(`app "${t}" function "${i}" returned a session without end()`);return d}function ne(e,t,i){let{baseUrl:p,orgId:u,auth:d}=e,c=typeof e.subject=="function"?e.subject():e.subject,l=i.startsWith(_)&&c!==void 0?`${c}:speech`:c,r=t.fnName??e.fnName,w=e.sessionStartOptions?.(i),a=t.sharedApp?{sharedApp:!0,...w}:w,f=o=>({session:o,responses:new I(o),gone:N(o,i)});if(d.lane==="jwt"){let o=B(t.appSlug,{baseUrl:p,orgId:u,jwt:d.jwt});return f(q(o,t.appSlug,r,a))}let{apiKey:g,gatewayUrl:n}=d,s=B(t.appSlug,{baseUrl:p,orgId:u,getAccessToken:async()=>(await ee(g,{baseUrl:n,expiresIn:300,allowedFunctions:[`${t.appSlug}/${r}`],...l===void 0?{}:{subject:l},...t.sharedApp?{sharedApp:!0}:{}})).token});return f(q(s,t.appSlug,r,a))}function oe(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}function se(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,i=e.status.error?.code;return t===410||t===409&&(i==="cancelled"||i==="expired")?!0:i==="client_ended"}var te=new Set(["error","paused"]);function Ae(e){let{auth:t,catalog:i}=e,p=null,u=(c,l)=>{let r=ne(e,c,l);return e.onSessionOpen&&typeof r.session.id=="string"&&r.session.id!==""&&e.onSessionOpen(l,r.session.id),r.gone.onGone(()=>{p?.evict(l,r)}),r},d=new j({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async c=>{if(c.gone.dispose(),e.release==="detach"){if(typeof c.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');c.session.detach();return}await c.session.end()},listApps:t.lane==="api-key"?()=>U({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:i?()=>T(i):null,listPrices:i?()=>M(i):null,shared:t.lane==="api-key"?()=>D({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:oe});return p=d,e.defaultApp!==null&&e.statelessDirect!==!0&&d.seed(e.defaultApp,u({appSlug:e.defaultApp},$({appSlug:e.defaultApp}))),d}async function E(e,t){let i=e.whenLive;if(typeof i!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await i.call(e,t===void 0?void 0:{signal:t})}async function K(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function k(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Pe(e,t=F,i,p){let u=new WeakMap,d=new WeakMap,c=new WeakMap,l=new WeakMap,r=new WeakMap,w=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},a=n=>{let s=u.get(n);if(!s){let o={waiting:0,gone:new AbortController};r.set(n,o),s=(async()=>{if(await E(n.session,o.gone.signal),o.gone.signal.aborted)throw k(o.gone.signal);r.get(n)===o&&r.delete(n);let h=await C(n.session,await t());return Object.assign(h,{sessionId:n.session.id})})(),u.set(n,s),s.catch(()=>{u.get(n)===s&&u.delete(n)}),s.then(()=>{r.get(n)===o&&r.delete(n)},()=>{r.get(n)===o&&r.delete(n)})}return s},f=n=>{let s=l.get(n);return s||(s=(async()=>{let o=await a(n);return{appendInputAudio:h=>o.appendInputAudio(h),onOutputAudio:h=>o.onOutputAudio(h),sessionId:w(n)}})(),l.set(n,s),s.catch(()=>{l.get(n)===s&&l.delete(n)})),s},g=async(n,s,o)=>{if(o?.aborted){let S=r.get(n);throw(u.get(n)===void 0||S!==void 0&&S.waiting===0)&&await K(n.session),k(o)}let h=s(n),m=r.get(n);return m!==void 0&&m.waiting++,o===void 0?h:new Promise((S,v)=>{let R=()=>{m!==void 0&&--m.waiting===0&&r.get(n)===m&&(m.gone.abort(),r.delete(n),u.delete(n),l.delete(n),K(n.session).catch(()=>{})),v(k(o))};o.addEventListener("abort",R,{once:!0});let L=()=>o.removeEventListener("abort",R);h.then(b=>{L(),S(b)},b=>{L(),v(b)})})};return{createResponse:W({sessionFor:n=>e.sessionFor(n),sessionIdOf:n=>w(n),evict:(n,s)=>e.evict(n,s),onAdmissionVerdict:(n,s,o)=>{se(o)&&(e.evict(n,s),i?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>(await E(n.session),O(await n.responses.responses.create(s),n.gone))}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{entry:o}=await e.sessionFor(n);return await g(o,a,s)},openAudioOn:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n);return await g(o,f,s)},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=d.get(s);return o||(o=x(s.session),d.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=c.get(s);return o||(o=G(s.session),c.set(s,o)),o},sessionHandle:async n=>(await e.handleFor(n)).handle,speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n);return await E(o.session),O(await o.responses.responses.create(s),o.gone)},onSessionEnd:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n),h=o.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let m=!1;return h.onPhase(S=>{if(m||!te.has(S.name))return;m=!0;let v=h.endsAt??null;s({timeLeftMs:v?Math.max(0,v.getTime()-Date.now()):null,reason:S.reason??`session ${S.name}`})})},...p?{stateless:p}:{}}}export{Ae as a,Pe as b};