@urun-sh/openai 0.6.34 → 0.6.36

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 (46) hide show
  1. package/dist/{ResponsesClient-_OZERUjH.d.cts → ResponsesClient-6QsC7NPJ.d.cts} +4 -1
  2. package/dist/{ResponsesClient-CSSrOYD8.d.ts → ResponsesClient-gfg7qUoE.d.ts} +4 -1
  3. package/dist/chunk-4NMMWAKD.js +1 -0
  4. package/dist/chunk-EPG5XWHE.js +64 -0
  5. package/dist/{chunk-ETX6IX25.js → chunk-GX243AIV.js} +1 -1
  6. package/dist/chunk-KKCUIOL4.js +1 -0
  7. package/dist/{chunk-CY4RJOTS.js → chunk-KXKTXZKG.js} +1 -1
  8. package/dist/chunk-OEITGJY2.js +2 -0
  9. package/dist/chunk-T6RD7TSR.js +23 -0
  10. package/dist/{composite-DGytPb8F.d.cts → composite-C6Gw4HfK.d.cts} +4 -4
  11. package/dist/gemini-live.cjs +1 -1
  12. package/dist/gemini-live.d.cts +10 -1
  13. package/dist/gemini-live.d.ts +3 -1
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +57 -47
  16. package/dist/hosted/bin.js +1 -1
  17. package/dist/hosted/index.cjs +53 -43
  18. package/dist/hosted/index.d.cts +2 -2
  19. package/dist/hosted/index.d.ts +2 -2
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/pi-extension/index.cjs +4 -4
  26. package/dist/pi-extension/index.d.cts +1 -1
  27. package/dist/pi-extension/index.d.ts +1 -1
  28. package/dist/pi-extension/index.js +1 -1
  29. package/dist/pi-extension/standalone.cjs +52 -52
  30. package/dist/pooler/bin.cjs +20 -20
  31. package/dist/pooler/bin.js +24 -24
  32. package/dist/proxy/cli.cjs +58 -54
  33. package/dist/proxy/cli.js +1 -1
  34. package/dist/proxy/conformance-probe.cjs +1 -1
  35. package/dist/proxy/conformance-probe.js +1 -1
  36. package/dist/proxy/index.cjs +33 -29
  37. package/dist/proxy/index.d.cts +2 -2
  38. package/dist/proxy/index.d.ts +2 -2
  39. package/dist/proxy/index.js +1 -1
  40. package/package.json +2 -2
  41. package/dist/chunk-2L7UL6BM.js +0 -17
  42. package/dist/chunk-AVMTHHBR.js +0 -60
  43. package/dist/chunk-EV4DZCHN.js +0 -1
  44. package/dist/chunk-LDBKLCCU.js +0 -2
  45. package/dist/chunk-PAYCMH5F.js +0 -1
  46. /package/dist/{composite-D4oZXeX4.d.ts → composite-DAZrZyLN.d.ts} +0 -0
@@ -5,7 +5,10 @@ interface ResponsesStream extends AsyncIterable<unknown> {
5
5
  }
6
6
  declare class UrunResponses {
7
7
  private readonly transport;
8
- constructor(session: UrunSessionLike);
8
+ /** `sessionTag`: the conversation identity (see SdkTransport); `null` = none (a shared lane). */
9
+ constructor(session: UrunSessionLike, opts?: {
10
+ sessionTag?: string | null;
11
+ });
9
12
  readonly responses: {
10
13
  create: (params: {
11
14
  model?: string;
@@ -5,7 +5,10 @@ interface ResponsesStream extends AsyncIterable<unknown> {
5
5
  }
6
6
  declare class UrunResponses {
7
7
  private readonly transport;
8
- constructor(session: UrunSessionLike);
8
+
9
+ constructor(session: UrunSessionLike, opts?: {
10
+ sessionTag?: string | null;
11
+ });
9
12
  readonly responses: {
10
13
  create: (params: {
11
14
  model?: string;
@@ -0,0 +1 @@
1
+ import{f as r}from"./chunk-GX243AIV.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
@@ -0,0 +1,64 @@
1
+ import{a as Dn,c as Un,d as $e,e as It,f as te,g as Bn,h as jn,i as Hn,j as Jn,k as Gn,l as Wn,m as Vn,n as zn,r as Kn,t as Xn,u as Yn,v as Qn,w as Zn,x as er}from"./chunk-3JWYIKHM.js";import{a as rn}from"./chunk-6M5JK4YC.js";import{s as Oe}from"./chunk-KXKTXZKG.js";import{a as qn,e as ut,f as Nn,i as U,j as Q}from"./chunk-6K7NOPD5.js";import{c as P}from"./chunk-YSFSRI3D.js";P();import{randomUUID as Ts}from"crypto";import{WebSocketServer as Ps}from"ws";var Cs=256,Et=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Cs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Ms="local",lt=n=>n.slice(0,120),Ot=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),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 U){this.ws.close(Un,lt(e.message));return}if(e instanceof Q){this.ws.close(It,lt(e.message));return}if(e instanceof te){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close($e,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Bn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new te(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=zn(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Xn(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:Kn);return}this.transcript.push(...Yn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new te("setup may only be sent once, as the first client message");let t=Gn(e),r=t.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new te("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",It);if(o.model!==t.model)throw new te(`sessionResumption.handle was issued for model "${o.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new te("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(t.model),this.proxyHandle!==o.proxyHandle)throw new te(`sessionResumption.handle named pooled session "${o.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`,It);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(l=>this.send(Jn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[jn]=Hn(i.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new te("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new te("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",$e);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Zn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new te("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new te("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",$e);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new te(`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 te("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new te("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(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=Ts();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Vn(e.timeLeftMs)),this.ws.close($e,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;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}),s,o=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new te(`upstream error: ${JSON.stringify(l)}`,$e);if(l.type==="response.completed"){s=l.response,o=!0;continue}let d=Qn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new te("upstream produced no response.completed event",$e);let{messages:i,assistantItems:a}=er(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Fe=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Ls(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let o=n.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Fe(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(t&&i!==void 0&&i!=="")throw new Fe(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&&t)throw new Fe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function tr(n,e){let t=e.authenticate!==void 0;if(t&&(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(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Ps({noServer:!0}),s=new Et;n.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=Ls(i,l,t),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Fe(401,"invalid local proxy api key");c={clients:e.clients,scope:Ms}}r.handleUpgrade(i,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Fe||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
+ Connection: close\r
3
+ \r
4
+ ${f}\r
5
+ `),a.destroy())}))});let o=null;return()=>(o??=(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)))})(),o)}function pa(n,e,t=new Et){new Ot(n,e,t)}P();var Te=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},dt=class extends Te{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},sn=class extends Te{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},ge=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},nr=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let t={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(t.min)||t.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(t.max)||t.max<t.min||t.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(t.inFlightCap)||t.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(t.warmWaitMs!==void 0&&(!Number.isInteger(t.warmWaitMs)||t.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=t.min,this.opts.max=t.max,this.opts.inFlightCap=t.inFlightCap,this.opts.warmWaitMs=t.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,t=0){let r=`decision:${this.opts.replicaId}:${e}`;return t===0?r:`${r}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(t=>t.state==="paused"&&!t.opening).sort((t,r)=>t.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new dt;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let s=this.tryLease();if(s)return this.pump(),s;if(this.draining)throw new dt;let o=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!o&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+t-Date.now();if(u<=0)throw new sn(t,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new dt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();if(t)return t;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(o=>o.state==="attached"),s=this.slots.some(o=>o.dead&&!o.opening);(r||s)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let o=s.session;if(typeof o!="object"||o===null||!("whenLive"in o))return!1;let i=o.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(o,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let o of this.slots)o.state!=="attached"||o.inFlight>=this.opts.inFlightCap||(!e||o.inFlight<e.inFlight)&&(e=o);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,t),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(o=>o.state==="attached"&&o.inFlight===0&&o.idleSince!==null&&e-o.idleSince>=this.idleGraceMs).sort((o,i)=>(o.idleSince??0)-(i.idleSince??0)||i.slot.index-o.slot.index),r=this.slots.filter(o=>o.state==="attached").length,s=Math.max(0,Math.min(t.length,r-this.opts.min));for(let o of t.slice(0,s))this.endSlot(o);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,o)=>s+o.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(o=>{r=o});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};P();import{SessionFailedError as Hs}from"@urun-sh/core";P();P();var ke=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},le=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};P();import{SessionFailedError as rr}from"@urun-sh/core";var ye=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},$s=33e4;function ba(n,e=$s){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,o=new Promise((l,d)=>{s=d}),i=setTimeout(()=>s(new Tt),e),a;try{a=await Promise.race([r.next(),o])}catch(l){throw l instanceof Q||l instanceof rr&&l.kind==="transport-failed"?l:l instanceof Tt?(await r.return?.(void 0),new ye("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new ye("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new ye("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Tt=class extends Error{constructor(){super("stream idle timeout")}};function ka(n){return n instanceof ye?!1:n instanceof Q?!0:n instanceof rr?n.kind==="transport-failed":!1}var Fs=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function we(n){return!Fs.some(e=>e.test(n))}function ve(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function de(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=sr(n);return t||{message:ve(e?.inferenceId??null),redacted:!0}}function sr(n){return n instanceof Nn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof qn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof U?{message:n.message,redacted:!1}:n instanceof ke?{message:n.message,redacted:!1}:n instanceof Te?{message:n.message,redacted:!1}:n instanceof ye?we(n.message)?{message:n.message,redacted:!1}:null:n instanceof ge?{message:n.message,redacted:!1}:n instanceof le?{message:n.message,redacted:!1}:null}function We(n,e,t){let r=t??(i=>console.error(i)),s=sr(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${n} upstream failed: ${s.message}`;let o=e instanceof Error?e.message:"";return e instanceof Error&&o.length>0&&we(o)?`the ${n} upstream failed: ${o}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${n} upstream failed while serving this request`)}function xe(n){let e=n?.message;return typeof e=="string"&&e.length>0&&we(e)?e:null}function _e(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}P();import{randomUUID as qs}from"crypto";function E(n){return`${n}_${qs().replace(/-/g,"").slice(0,24)}`}var Pt=4*1024*1024,on=8*1024*1024,Ct=512,Mt=20*1024*1024;function Z(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function ze(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:E("event"),error:n}}function an(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Ns={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Ds={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Us={format:!0,voice:!0,speed:!0};function Bs(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ve(n,e){if(!Array.isArray(n)||n.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function or(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var js=10;function un(n){if(n==null)return n;let e;try{e=JSON.parse(n)}catch{return n}if(e===null||typeof e!="object"||Array.isArray(e))return n;let t=e;return t.hz!==void 0||t.cadence_ms!==void 0||!("questions"in t)&&!("question"in t)?n:JSON.stringify({...t,hz:js})}function ct(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new T("session must be an object","session","invalid_request");let s=n,o=Object.keys(s).filter(a=>!(a in Ns));if(o.length>0)throw new T(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");if(s.modalities!==void 0&&s.output_modalities!==void 0){let a=Ve(s.modalities,"modalities"),u=Ve(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(s))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new T('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new T(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ve(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new T('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Bs(u))throw new T(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new T("model must be a string or null","model");i.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");i.instructions=un(u??void 0)??void 0;break;case"voice":if(u===null){delete i.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!t.voice)throw new T("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new T(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new T("temperature must be a finite number or null","temperature");i.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new T(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new T("tools must be an array","tools");i.tools=u;break;case"tool_choice":i.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new T("metadata must be an object or null","metadata");i.metadata=u??null;break;case"turn_detection":{if(u===null){i.turnDetection=null;break}if(!t.turns)throw new T("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 l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,f]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new T(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(f!=null&&f!==c[p])throw new T(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!t.turns)throw new T("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(!u||typeof u!="object"||Array.isArray(u))throw new T("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new T(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new T(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new T("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(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Ds))throw new T(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&or(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ct({input_audio_transcription:d.transcription},i,t,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ct({turn_detection:d.turn_detection},i,t,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Us))throw new T(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&or(d.format,"audio.output.format"),d.speed!==void 0)throw new T("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new T("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new T("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Lt(n,e){return{id:e,object:"realtime.session",type:n.type??"realtime",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function ln(n,e){let t=n;if(!t||typeof t!="object")throw new T("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:E("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new T("message item content must be an array","item.content","invalid_request");let s=[];for(let o of t.content){let i=o;if(!i||typeof i!="object")throw new T("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 T(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new T("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 T("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new T(`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 t.id=="string"?t.id:E("item"),type:"message",role:r,content:s}}throw new T(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function $t(n){let e=[],t=!1;for(let r of n){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 s=[];for(let o of r.content??[]){if(o.type==="input_text"||o.type==="output_text"){s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){let i=o.transcript;if(typeof i=="string"&&i.trim().length>0){s.push({type:"input_text",text:i});continue}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Js=1001,Gs=1011,ir=n=>n.slice(0,120),Ws=/^[A-Za-z0-9+/=]*$/,Vs=2;function zs(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>Vs)return!1;return!0}var pt=class{id=E("conn");ws;binding;onClosed;operatorLog;config=an();sessionId=E("sess");conversationId=E("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:E("event"),session:Lt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Q&&this.binding.composite===!0)this.failSessionGone(r);else{let s=this.callerLine(r,"turn/transcript lane read"),o=this.pendingTranscriptItemId;o!==null?this.failPendingTranscription(o,s):this.send(G(ze("turn_lane_fault",`the backend turn/transcript lane failed: ${s}`)))}}finally{this.turnLaneIterator===t&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,t),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:e,content_index:0,transcript:t});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:E("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let r=this.items.find(o=>o.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:t},...(r.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(r=>r.id===e);t<0||this.send({type:"conversation.item.done",event_id:E("event"),previous_item_id:t>0?this.items[t-1].id:null,item:this.itemToProtocol(this.items[t])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:E("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 t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),o=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=o,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=E("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...o!==null?{transcript:o}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&o!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:i,content_index:0,transcript:o}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(Z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Pt){this.fail(Z("frame_too_large",`frame exceeds the ${Pt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(Z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Z("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let o=s;if(o&&typeof o=="object"&&o.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:o.code??"invalid_value",message:o.message,param:o.param??null}));return}this.fail(ze(null,this.callerLine(s,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let t=ct(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(Z("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:E("event"),session:Lt(this.config,this.sessionId)});return}case"conversation.item.create":{let t=ln(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(G(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:E("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(G(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(Z("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:E("event"),item_id:t.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(G(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ws.test(e.audio)){this.send(G(Z("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+t>Mt){this.send(G(Z("buffer_full",`uncommitted input audio exceeds the ${Mt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=t;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(G(Z("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let o=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,o),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:o}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(Z("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(Z("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(G(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(Z("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,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.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)");t.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(G({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,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let o=e.response??e;return r.sendResponseCreate({type:"response.create",response:o},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:o,input:i,...a}=e;return await s.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(G(Z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?Ve(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ve(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new T("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(G(Z("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,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=E("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:$t(this.items),c=un(typeof t.instructions=="string"?t.instructions:this.config.instructions),p=typeof t.temperature=="number"?t.temperature:this.config.temperature,f=t.max_output_tokens??this.config.maxOutputTokens,m=f==="inf"||f===void 0?void 0:f,k=t.tools!==void 0?t.tools:this.config.tools,S=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,y={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...m!==void 0?{max_output_tokens:m}:{},...k!==void 0?{tools:k}:{},...S!==void 0?{tool_choice:S}:{}};if(!(u&&!this.ensureVoice())){for(let g of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(g);this.inFlight=(async()=>{let g=[],h=b=>{this.responseFlushed?this.send(b):g.push(b)},_=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(a,"in_progress")});for(let b of g)this.send(b);g.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},A=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,d=$t(this.items)}let{input:b,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},O={...y,input:b,...u?this.compositeTurnAsk(t):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(O,i)}catch(I){this.upstreamTurnFault(I,a);return}try{for await(let I of x){if(this.cancelled)break;let w=I;if(w.type==="error"){let C=this.upstreamErrorBody(w);this.responseFlushed?this.send(G(C)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(a,C)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){_(),v.messageOpen||(this.beginMessageItem(a,v.nextOutputIndex++),v.messageOpen=!0),this.config.outputModalities.includes("text")&&h({type:"response.output_text.delta",event_id:E("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(v.transcriptDelta=!0,h({type:"response.output_audio_transcript.delta",event_id:E("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),v.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){_();let C=typeof w.delta=="string"?w.delta:"",N=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${v.nextOutputIndex}`,q=v.tools.get(N);if(!q){let K=typeof w.name=="string"&&w.name.length>0?w.name:void 0;q={outputIndex:v.nextOutputIndex++,name:K,args:""},v.tools.set(N,q);let B={id:N,object:"realtime.item",type:"function_call",call_id:N,name:K??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:E("event"),response_id:a,output_index:q.outputIndex,item:B}),this.emitAssistantItemAdded(B)}typeof w.name=="string"&&w.name.length>0&&(q.name=w.name),q.args+=C,h({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:N,response_id:a,output_index:q.outputIndex,call_id:N,name:q.name??"",delta:C});continue}if(w.type==="response.completed"){A=w.response??null;continue}}}catch(I){this.upstreamTurnFault(I,a);return}if(this.cancelled)return;this.closeOpenItems(a,v,l),_(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(a,l,A)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(zs(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({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:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("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:E("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,o=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=t.messageText;o?(this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:E("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:E("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:E("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:o?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];o&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,o]of t.tools){let i=o.args.length>0?o.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:s,response_id:e,output_index:o.outputIndex,call_id:s,name:o.name??"",arguments:i});let a={id:s,type:"function_call",callId:s,name:o.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:o.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,o=[];for(let i=t;i<this.items.length;i++)o.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:o,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.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 t=e.error,r=xe(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??ve(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failSessionGone(e){let t=e instanceof Error&&we(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${_e(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(ze("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Hs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=ze(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(t,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(Z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:E("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Ct&&(this.items.shift(),this.send(G({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Ct} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,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>on){this.ws.close(Js,ir("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${_e(e)}`),r.message}fail(e,t){this.send(G(e)),this.ws.close(Gs,ir(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let s=r.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>ar(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ar(this.id,e)}},dn=[];function ar(n,e){dn.push({id:n,reason:e}),dn.length>256&&dn.shift()}P();import{SessionFailedError as ur}from"@urun-sh/core";P();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ks}from"@urun-sh/core";var Xs={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ys={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function mt(n,e){let t=Ys[n.code];return e?`${t} (${e})`:t}function Ft(n){if(n==null)return null;let e=Xs[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function qt(n){if(n.kind==="create-failed")return Ft(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=Ks;return Ft(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Qs}from"ws";var pn="/v1/realtime",Zs=n=>n.slice(0,120);function eo(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
6
+ Connection: close\r
7
+ Content-Type: text/plain\r
8
+ \r
9
+ ${Zs(t)}\r
10
+ `),n.destroy()}function to(n){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...n})}
11
+ `}function no(n){Oe(process.stdout,n)}function ro(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function cn(n){return n.audioSession?.audio.sessionId??void 0}function mn(n,e){let t=new Qs({noServer:!0}),r=new Set;return n.on("upgrade",(s,o,i)=>{if(new URL(s.url??"/","http://localhost").pathname!==pn)return;r.add(o),o.on("close",()=>{r.delete(o)});let u=E("rtup"),l=ro(s),d=v=>{(e.log??no)(to(v))};d({stage:"accept",conn:u,model:l}),o.resume();let c=new AbortController,p=null,f=v=>{p??=v,c.abort(new Error(p))},m=()=>f("client socket closed"),k=()=>f("client socket closed (half-close)"),S=v=>f(`client socket error: ${v.message}`);o.once("close",m),o.once("end",k),o.once("error",S);let y=()=>{o.removeListener("close",m),o.removeListener("end",k),o.removeListener("error",S)},g=v=>{d({stage:"close",conn:u,model:l,...v})},h=v=>{let A=v,b=A.session!=null&&typeof A.session.sendResponseCreate=="function",R=A.clients!=null&&typeof A.clients.createResponse=="function";if(!b&&!R)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((O,x)=>{t.handleUpgrade(s,o,i,I=>{try{new pt({ws:I,binding:v,operatorLog:e.operatorLog,onClosed:(w,C)=>{g({while:"live",reason:C.reason})}}),d({stage:"admit",conn:u,model:l,...cn(v)===void 0?{}:{session:cn(v)}}),O()}catch(w){x(w)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s,c.signal).then(async v=>{if(c.signal.aborted){y();let A=cn(v);try{await v.release?.()}catch(b){g({while:"queued",...A===void 0?{}:{session:A},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}g({while:"queued",...A===void 0?{}:{session:A},reason:p??"client socket closed",released:!0}),o.destroy();return}y(),await h(v)}).catch(v=>{let A=v instanceof ur?qt(v):null,b=null;if(v!==null&&typeof v=="object"&&"status"in v){let I=v.status;typeof I=="number"&&(b=I)}let R=b??A?.status??502,O=v instanceof Error?v.message:String(v),x=b!==null?O:A!==null?mt(A,v instanceof ur&&v.status.sessionId?`session ${v.status.sessionId}`:void 0):de(v).message;g({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:R}}),o.destroyed||eo(o,R,x)}).finally(()=>{r.delete(o)})}),async()=>{let s=Date.now()+5e3;for(;r.size>0&&Date.now()<s;)await new Promise(o=>setTimeout(o,25));await new Promise(o=>t.close(()=>o()))}}P();P();import{randomUUID as ra}from"crypto";P();import{createServer as Oi}from"http";P();import{WebSocketServer as yo,WebSocket as _t}from"ws";P();P();import{randomUUID as so}from"crypto";var lr="Inference-Id";function ft(){return so()}function fn(n){return n==="/v1"||n.startsWith("/v1/")}function dr(n,e){if(!fn(n)||e===null)throw new Error(`no inference turn for ${n}: 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 ht(n){return`resp_${n}`}function cr(n){return`chatcmpl-${n}`}function pr(n){return`msg_${n}`}function pe(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function mr(n){let e=n.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:n.turn.id,method:n.method,path:n.path,status:n.res.headersSent?n.res.statusCode:null,delivered:n.res.writableFinished,stream_error:n.turn.streamError,model:n.turn.model,stream:n.turn.stream,org:n.turn.org,duration_ms:e()-n.turn.startedAt,ttft_ms:n.turn.stream===!0?n.turn.ttftMs:null,prompt_tokens:n.turn.promptTokens,completion_tokens:n.turn.completionTokens,output_units:n.turn.outputUnits,output_minutes:n.turn.outputMinutes,output_seconds:n.turn.outputSeconds??null,session_id:n.turn.sessionId,queue_ms:n.turn.timing?.queue_ms??null,prefill_ms:n.turn.timing?.prefill_ms??null,decode_ms:n.turn.timing?.decode_ms??null,total_ms:n.turn.timing?.total_ms??null,...n.turn.decision?{decision_resolve_ms:n.turn.decision.resolve_ms,decision_dial_ms:n.turn.decision.dial_ms,decision_first_event_ms:n.turn.decision.first_event_ms,decision_stream_ms:n.turn.decision.stream_ms,decision_question_fwd_ms:n.turn.decision.question_fwd_ms,decision_head_ms:n.turn.decision.head_ms}:{},catalog:n.turn.catalog}}function fr(n){return`${JSON.stringify(n)}
12
+ `}var oo=256,io=128;function ie(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,io)}var qe=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=r}modelEntry(e){let t=this.models[e];if(t)return t;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,t,r){let s=this,o=performance.now(),i=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),s.ttftMs.push(i-o),s.ttftMs.length>512&&s.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,s.tokensOut+=1,s.charsOut+=l.delta.length,t!==void 0&&(s.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(i??o))/1e3;a>0&&u>0&&(s.tokRates.push(a/u),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((r,s)=>r-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,r)=>t+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:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.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}}}},ao=256;function uo(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var Ne=class extends Error{},Ke=class{conversations=new Map;thread(e,t){let r=uo(t);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new Ne(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,t,r,s=!0){this.conversations.set(e,[...t,...r]);for(let o of this.conversations.keys()){if(this.conversations.size<=ao)break;this.conversations.delete(o)}}forget(e){this.conversations.delete(e)}},hr=new WeakMap;function gt(n){let e=hr.get(n);return e||(e=new Ke,hr.set(n,e)),e}function Xe(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function Se(n){return n.find(e=>e.type==="response.completed")?.response??null}function Ye(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var Pe=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),r=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},lo=["<tool_call>","<function="];function co(n){return lo.find(e=>n.includes(e))}function De(n,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 "${n}" (see catalog parser_defaults)`}function Ue(n,e,t){if(!(!n||e>0))return co(t)}function Qe(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Re(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function po(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s=r;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function hn(n,e){let t=po(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var me=class extends Error{constructor(t,r,s=400,o){super(t);this.code=r;this.status=s;this.param=o}code;status;param};function Ze(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof Ne?new me(t.message,"previous_response_not_found",400,"previous_response_id"):new me(String(t instanceof Error?t.message:t),"invalid_input")}}function gr(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function gn(n,e,t,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new me("instructions must be a string","invalid_instructions");let o=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...o!==void 0?{instructions:o}:{},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}:{},...gr(e)!==void 0?{response_format:gr(e)}:{}},s)}async function yt(n){let{body:e,clients:t,store:r,stats:s}=n,o=Ze(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(o))-Buffer.byteLength(JSON.stringify(e.input)));let i=n.responseId,a=n.remember??e.store!==!1,u=e.store!==!1,l=ie(e);s.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await gn(t,e,o,!0,c?pe(c):void 0);return{responseId:i,events:go({events:p,conversation:o,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:s,turn:n.turn})}}function mo(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],s=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),o=t.filter(u=>u.type==="message").length===s.length,i=0;return[...t.map(u=>u.type==="message"&&o?ho(s[i++],u):u),...fo(r,t)]}function fo(n,e){let t=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),s=l=>String(l.call_id??l.id??""),o=e.filter(l=>l.type==="function_call"),i=n.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=o.length===i,u=new Set(o.map(s));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(s(d)):!0})}function ho(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(n.content)?n.content:[];if(r.filter(t).length!==1)return e;let o=(Array.isArray(e.content)?e.content:[]).find(t);if(o===void 0)return e;let i={...n};return i.id=e.id,n.role===void 0&&(i.role=e.role),n.status===void 0&&(i.status=e.status),i.content=r.map(a=>t(a)?{...a,text:o.text}:a),i}async function*go(n){let{events:e,conversation:t,responseId:r,modelKey:s,requestHadTools:o,remember:i,persist:a,store:u,stats:l}=n,d=[],c=L=>L.response&&typeof L.response=="object"?{...L,response:{...L.response,id:r}}:L,p=`item_${r.slice(5)}`,f=!1,m=!1,k=0;function*S(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=[],g=(L,D)=>{y.push({output_index:L,item:D})},h=!1,_=0,v="",A=0,b="";function*R(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:v,output_index:_,content_index:0,text:b};let L={id:v,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:_,item:L},g(_,L),b=""}let O=!1,x=0,I="",w=0,C="",N="";function*q(L){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:I,output_index:x,content_index:0,text:C},yield{type:"response.content_part.done",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:C}};let D={id:I,type:"message",role:"assistant",status:L,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:x,item:D},g(x,D),C=""}let K=new Pe,B=null,Ee=-1;function*X(L){if(!B)return;let D=B;B=null,yield{type:"response.function_call_arguments.done",item_id:D.fcId,output_index:D.outputIndex,arguments:D.args};let H={id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:D.args,status:L};yield{type:"response.output_item.done",output_index:D.outputIndex,item:H},g(D.outputIndex,H)}let oe=!1;for await(let L of l.track(e,s,n.turn)){d.push(L);let D=String(L.type??"");if(D==="response.created"||D==="response.in_progress"){f=!0,yield c(L);continue}if(D==="response.output_item.added"){m=!0,yield c(L);continue}if(D==="response.reasoning_text.delta"&&!m){yield*S(),h||(h=!0,_=k++,A+=1,v=A===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${A}`,yield{type:"response.output_item.added",output_index:_,item:{id:v,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(L.delta??""),yield{type:"response.reasoning_text.delta",item_id:v,output_index:_,content_index:0,delta:L.delta};continue}if(D==="response.output_text.delta"&&!m){yield*S(),yield*R(),O||(O=!0,x=k++,w+=1,I=w===1?p:`${p}_${w}`,yield{type:"response.output_item.added",output_index:x,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:""}}),C+=String(L.delta??""),N+=String(L.delta??""),yield{type:D,item_id:I,output_index:x,content_index:0,delta:L.delta};continue}let H=m?null:Ye(L);if(H){if(yield*S(),yield*R(),yield*q("completed"),K.add(H),H.tool_index!==Ee){yield*X("completed"),Ee=H.tool_index;let Me=k++;B={fcId:`fc_${r.slice(5)}_${H.tool_index}`,outputIndex:Me,callId:H.call_id,name:H.name,args:""},yield{type:"response.output_item.added",output_index:Me,item:{id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:"",status:"in_progress"}}}B&&(H.call_id&&(B.callId=H.call_id),H.name&&(B.name=H.name),B.args+=H.delta,yield{type:"response.function_call_arguments.delta",item_id:B.fcId,output_index:B.outputIndex,delta:H.delta});continue}if(D==="response.completed"&&!m){let Me=Xe(L.response),Ge=Ue(o,K.size+Me.length,N);if(Ge){oe=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:De(s,Ge)}};break}if(yield*R(),yield*q("completed"),yield*X("completed"),K.size===0)for(let Y of Me){let he=k++,Le=Y.id??Y.call_id??`fc_${he}`,nn=Y.arguments??"",$n={id:Le,type:"function_call",call_id:Y.call_id??Le,name:Y.name??""};yield{type:"response.output_item.added",output_index:he,item:{...$n,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Le,output_index:he,delta:nn},yield{type:"response.function_call_arguments.done",item_id:Le,output_index:he,arguments:nn};let Fn={...$n,arguments:nn,status:"completed"};yield{type:"response.output_item.done",output_index:he,item:Fn},g(he,Fn)}let J=mo(y,L.response);yield J.length>0?c({...L,response:{...L.response,output:J}}):c(L);continue}yield c(L)}if(yield*R(),yield*q("incomplete"),yield*X("incomplete"),i&&!oe){let L=Se(d);u.remember(r,t,hn(L,Qe(d,L)),a)}}var _o="/v1/responses",wo=64*1024*1024,vo=8*1024*1024,bo=16,yr=32,_r=3600*1e3,ko=/^[A-Za-z0-9._-]{1,256}$/;function ae(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var xo=ae(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 wn(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}async function So(n){for(;n.bufferedAmount>vo&&n.readyState===_t.OPEN;){let{promise:e,resolve:t}=wn();setTimeout(t,5),await e}}var yn=class extends Ke{constructor(t){super();this.shared=t}shared;thread(t,r){if(t==null)return super.thread(t,r);try{return super.thread(t,r)}catch(s){if(!(s instanceof Ne))throw s;return this.shared.thread(t,r)}}remember(t,r,s,o=!0){o?this.shared.remember(t,r,s):super.remember(t,r,s)}forget(t){super.forget(t),this.shared.forget(t)}},_n=class{constructor(e,t,r,s,o){this.ws=e;this.clients=t;this.stats=r;this.statusOf=s;this.operatorLog=o;this.store=new yn(gt(t)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${_r/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},_r).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(ae(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(ae(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(ae(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=r;if(s.type!=="response.create"){this.sendFrame(ae(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(ae(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 s){this.sendFrame(ae(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let o;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!ko.test(s.stream_id)){this.sendFrame(xo);return}if(o=s.stream_id,!this.lanes.has(o)&&this.namedLaneCount()>=yr){this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${yr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},o));return}}let i=s.generate===!1?()=>this.runWarmup(s,o):()=>this.runTurn(s,o),a=o??"",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,t){if(this.closed)return;await this.acquire();let r=ft();try{let s=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",s,s);let o;try{o=await yt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ht(r)})}catch(a){this.failTurn(a,t,e,r);return}this.laneOfResponse.set(o.responseId,t??null);let i=o.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==_t.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,r));break}this.send(a,t),await So(this.ws)}}finally{this.activeTurns.delete(i)}}catch(s){this.failTurn(s,t,e,r)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let r=ft(),s=ht(r);try{let o=Ze(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(s,o,[],e.store!==!1),this.laneOfResponse.set(s,t??null),this.send({type:"response.created",response:{id:s,object:"response",status:"in_progress"}},t)}catch(o){this.failTurn(o,t,e,r)}}failTurn(e,t,r,s){this.sendFrame(this.errorFrameOf(e,t,s));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(t??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,t,r){let s=e instanceof Error?e.message:_e(e);if(e instanceof me)return ae(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof U)return ae(404,{type:"invalid_request_error",code:"model_not_found",message:s},t);if(e instanceof Q){let a=de(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),ae(503,{type:"upstream_error",code:"session_gone",message:a.message},t)}let o=this.statusOf?.(e)??null;if(o)return o.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${o.operatorDetail}`),ae(o.status,{type:o.openaiType,message:s},t);let i=de(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),ae(500,{type:"upstream_error",message:i.message},t)}upstreamErrorFrameOf(e,t,r){let s=e.error,o=s?.type??"upstream_error",i=xe(s),a=i??ve(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ae(o==="invalid_request_error"?400:502,{type:o,...s&&typeof s.code=="string"?{code:s.code}:{},message:a},t)}async acquire(){for(;this.active>=bo;){let{promise:e,resolve:t}=wn();this.waiters.push(t),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,t){if(this.closed||this.ws.readyState!==_t.OPEN)return;let r=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==_t.OPEN||this.ws.send(JSON.stringify(e))}};function Nt(n,e,t){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",s=`${t}\r
13
+ `;n.end(`HTTP/1.1 ${e} ${r}\r
14
+ Connection: close\r
15
+ Content-Type: text/plain; charset=utf-8\r
16
+ Content-Length: ${Buffer.byteLength(s)}\r
17
+ \r
18
+ ${s}`)}function wr(n,e){let t=new yo({noServer:!0,maxPayload:wo}),r=new qe,s=new Set,o=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Nt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==_o){i.add(c);return}o.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Nt(c,401,"invalid local proxy api key");return}let k;try{k=await a(d)}catch(S){let y=e.statusOf?.(S)??null;Nt(c,y?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(m=!0,t.handleUpgrade(d,c,p,S=>{o.delete(c),s.add(S),S.on("close",()=>s.delete(S));try{new _n(S,k,r,e.statusOf,e.operatorLog??(y=>console.error(y)))}catch{s.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Nt(c,500,"responses websocket upgrade failed")}).finally(()=>o.delete(c))};return n.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=wn();if(u)return c(),d;u=!0,n.off("upgrade",l);for(let f of o)f.destroy();o.clear();for(let f of i)f.destroy();i.clear();for(let f of s)f.close(1001,"server shutting down");let p=setTimeout(()=>{for(let f of s)f.readyState!==_t.CLOSED&&f.terminate()},2e3);return p.unref?.(),t.close(()=>{clearTimeout(p),c()}),d}}}P();var M=class extends Error{},fe=class extends Error{};function ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ut(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null}function et(n,e){if(n!=null)throw new M(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Dt(n){let e=Ut(n);return e!==null&&e<=1?e:null}function vr(n,e){if(!ne(n))throw new M("decisions requires a JSON object body");et(n.prompt_cache_key,"prompt_cache_key"),et(n.prompt_cache_options,"prompt_cache_options"),et(n.safety_identifier,"safety_identifier");let t=[],r=Ro(n.input,t),s=n.questions;if(!Array.isArray(s)||s.length<1||s.length>400)throw new M("decisions requires a questions array of 1 to 400 questions");let o={},i=[],a=new Set;for(let l=0;l<s.length;l++){let{entry:d,spec:c}=Oo(s[l],l,s.length,t);if(a.has(c.key))throw new M(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),o[c.key]=d,i.push(c)}let u={model:e,state:r,questions:o};return t.length>0&&(u.media=t),{systemone:u,specs:i}}function Ro(n,e){if(typeof n=="string")return n;if(!ne(n)&&!Array.isArray(n))throw new M("decisions input must be a string or an array of messages");let t=Array.isArray(n)?n:[n],r=[];for(let s of t)Io(s,r,e);return Ao(r)}function Ao(n){return n.length===0?"":n.some(e=>e.role!==void 0)?n:n.flatMap(e=>"text"in e?[e.text]:[]).join(`
19
+
20
+ `)}function Io(n,e,t){if(!ne(n))throw new M("decisions input items must be JSON objects");let r=n.role,s=n.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Eo(n,r,e,t);return}switch(s){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:s,name:n.name,call_id:n.call_id,arguments:n.arguments,input:n.input})});return}case"function_call_output":case"custom_tool_call_output":{let o=n.output;if(typeof o=="string"){e.push({text:o});return}if(Array.isArray(o)){br(o,e,t,void 0,!1);return}throw new M(`${s} output must be a string or an array of parts`)}default:throw new M(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(s??null)})`)}}function Eo(n,e,t,r){e==="assistant"&&et(n.phase,"assistant message phase");let s=n.content;if(typeof s=="string"){t.push({role:e,text:s});return}if(!Array.isArray(s))throw new M(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let o of s){if(!ne(o))throw new M("decisions assistant message parts must be JSON objects");if(o.type==="output_text"&&typeof o.text=="string")t.push({role:e,text:o.text});else if(o.type==="refusal"&&typeof o.refusal=="string")t.push({role:e,text:`[refusal] ${o.refusal}`});else throw new M(`unsupported decisions assistant message part type ${JSON.stringify(o.type??null)}`)}return}br(s,t,r,e)}function br(n,e,t,r,s=!0){for(let o of n){if(!ne(o))throw new M("decisions content parts must be JSON objects");switch(et(o.prompt_cache_breakpoint,"prompt_cache_breakpoint"),o.type){case"input_text":{if(typeof o.text!="string")throw new M("input_text requires a string text");e.push({role:r,text:o.text});break}case"input_json":{if(!s)throw new M("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=o.data;if(!ne(i)&&!(Array.isArray(i)&&i.every(ne)))throw new M("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{t.push(kr(o));break}default:throw new M(`unsupported decisions content part type ${JSON.stringify(o.type??null)}`)}}}function kr(n){let e=n.image_url;if(typeof e!="string"||e==="")throw new M("input_image requires a string image_url");let t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(t===null)throw new M("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,s]=t;if(s==="")throw new M("input_image data URL carries no image data");let o=s.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(s)||(o?s.length%4!==0:s.length%4===1))throw new M("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=n.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new M("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:s};return(i==="low"||i==="high")&&(a.detail=i),a}function Oo(n,e,t,r){if(!ne(n))throw new M(`questions[${e}] must be a JSON object`);let s=n.type;if(s!=="predicate"&&s!=="choice"&&s!=="score")throw new M(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(s??null)})`);let o=n.name;if(o!==void 0&&typeof o!="string")throw new M(`questions[${e}] name must be a string`);let i=o??null,a=i??`q${e}`,u=To(n.instructions,e,t,r);switch(s){case"predicate":return{entry:{kind:"noul",prompt:u,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:s,key:a,name:i}};case"choice":{let l=n.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new M(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let k of l){if(!ne(k))throw new M(`questions[${e}] choices must be JSON objects`);let S=k.value;if(typeof S!="string"&&typeof S!="boolean")throw new M(`questions[${e}] choice value must be a string or boolean`);let y=String(S);if(c.has(y))throw new M(`questions[${e}] has duplicate choice value ${JSON.stringify(y)} (choices must be unique)`);c.add(y);let g=k.description;if(g!==void 0&&typeof g!="string")throw new M(`questions[${e}] choice description must be a string`);d.push(S),p.push(g)}let f=l.map((k,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:u,options:f},spec:{type:s,key:a,name:i,choiceValues:d}}}case"score":{let l=n.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new M(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let f of l){if(!ne(f)||typeof f.label!="string")throw new M(`questions[${e}] score levels must carry a string label`);if(d.includes(f.label))throw new M(`questions[${e}] has duplicate level label ${JSON.stringify(f.label)}`);d.push(f.label);let m=f.description;if(m!==void 0&&typeof m!="string")throw new M(`questions[${e}] score level description must be a string`);let k=m!==void 0?`${f.label}: ${m}`:f.label;if(c.includes(k))throw new M(`questions[${e}] has duplicate score criterion ${JSON.stringify(k)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(k)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:s,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function To(n,e,t,r){if(typeof n=="string")return n;if(!Array.isArray(n))throw new M(`questions[${e}] instructions must be a string or an array of input parts`);let s=[];for(let o of n){if(!ne(o))throw new M(`questions[${e}] instruction parts must be JSON objects`);switch(et(o.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),o.type){case"input_text":{if(typeof o.text!="string")throw new M(`questions[${e}] input_text requires a string text`);s.push(o.text);break}case"input_image":{if(t>1)throw new M(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(kr(o));break}case"input_json":{let i=o.data;if(!ne(i)&&!(Array.isArray(i)&&i.every(ne)))throw new M(`questions[${e}] input_json data must be an object or an array of objects`);s.push(JSON.stringify(i));break}default:throw new M(`unsupported decisions instruction part type ${JSON.stringify(o.type??null)}`)}}return s.join(`
21
+
22
+ `)}function xr(n,e){if(!ne(e))throw new fe("decision answer was not a JSON object");let t=e.choices;if(!ne(t))throw new fe("decision answer carried no choices object");let r=[];for(let s of n){let o=t[s.key];if(!ne(o)||o.skipped===!0){r.push({type:"refusal",name:s.name});continue}let i=ne(o.probabilities)?o.probabilities:{};switch(s.type){case"predicate":{let a=Dt(i.yes),u=Dt(i.no),l=a??(u!==null?1-u:null);if(l===null)throw new fe(`the predicate answer for "${s.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:s.name,probability:l});continue}case"choice":{let a=s.choiceValues??[],u=o.choice;if(typeof u!="string")throw new fe(`the choice answer for "${s.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new fe(`the choice answer for "${s.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=Ut(o.confidence);if(d===null)throw new fe(`the choice answer for "${s.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let f=Dt(i[String(p)]);f!==null&&c.push({value:p,probability:f})}r.push({type:"choice",name:s.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=s.levelLabels??[],u=s.scoreCriteria??[],l=Ut(o.score);if(l===null)throw new fe(`the score answer for "${s.key}" carries no numeric score to translate`);let d=Ut(o.confidence);if(d===null)throw new fe(`the score answer for "${s.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let f=Dt(i[u[p]]);f!==null&&c.push({value:p,label:a[p],probability:f})}r.push({type:"score",name:s.name,score:l,confidence:d,probabilities:c});continue}}}return r}P();P();var re=class extends Error{};async function Bt(n,e){let t=Number(n.headers["content-length"]??"0");if(Number.isFinite(t)&&t>e)throw new re(`request body exceeds the ${e}-byte limit`);let r=[],s=0;for await(let o of n){let i=o;if(s+=i.length,s>e)throw new re(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function jt(n,e){let t=n[Symbol.asyncIterator](),r=0,s=new ReadableStream({async pull(i){try{let a=await t.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new re(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){t.return?.()}}),o;try{let i=new Headers;for(let[l,d]of Object.entries(n.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let a={method:"POST",headers:i,body:s,duplex:"half"};o=await new Request(`https://proxy.internal${n.url??"/"}`,a).formData()}catch(i){throw i instanceof re?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return o}var Sr="/v1/images/generations",Ht="/v1/images/edits";function Rr(n){return n===Sr||n===Ht}var Ar="/v1/images/models";async function Ir(n,e,t){if(n){if(n.model=ie({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.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(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var F=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}},Po=16*1024*1024,Er=64*1024*1024;function Or(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":null}function wt(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Tr(n,e,t,r,s,o){let i=o??(m=>console.error(m)),a=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},r),u=null;for await(let m of a){if(m.type==="error"){let k=m.error??{},S=typeof k.message=="string"&&k.message.length>0&&we(k.message)?k.message:null;throw S===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new F(502,"the image upstream failed while serving this request")):new F(502,`image upstream error: ${S}`)}if(m.type==="response.completed"){u=m.response??null;break}}if(u===null)throw new F(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");s&&(s.outputSeconds=Re(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new F(502,`image upstream returned ${Array.isArray(l)?l.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 d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Or(p)===null)throw new F(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Pr(n,e){if(n instanceof F)return n;if(n instanceof ke)throw n;return n instanceof U?new F(404,n.message):new F(502,We("image",n,e))}async function Cr(n,e,t,r){if(await n(e,t))return!0;let s=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return wt(r,new F(404,e===void 0?`no image-capable default model is configured for this caller (${s}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${s}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Mr(n,e){n&&(n.outputUnits=e.images.length)}function Lr(n,e){n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(t=>({b64_json:t}))}))}var Co={model:!0,prompt:!0,response_format:!0,n:!0};async function $r(n,e,t){let r=t.operatorLog??(o=>console.error(o)),s=t.maxBodyBytes??Er;try{if(n.method!=="POST")throw new F(405,`${String(n.method)} is not supported on ${Sr}`);let o;try{o=JSON.parse((await Bt(n,s)).toString("utf8")||"{}")}catch(p){throw p instanceof re?new F(413,p.message):new F(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new F(400,"request body must be a JSON object");let i=o;for(let p of Object.keys(i))if(!Co[p])throw new F(400,`request field "${p}" 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.`,p);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new F(400,"prompt is required and must be a non-empty string","prompt");let u=i.model===void 0?void 0:i.model;if(u!==void 0&&typeof u!="string")throw new F(400,"model must be a string","model");await Ir(t.turn,t.clients,u);let l=i.n??1;if(l!==1)throw new F(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new F(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(t.stats?.request("images_generations",a.length,a.length),!await Cr(t.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Tr(t.clients,u,c,t.turn?pe(t.turn):void 0,t.turn,r);Mr(t.turn,p),Lr(e,p)}catch(p){throw Pr(p,r)}}catch(o){if(o instanceof re){wt(e,new F(413,o.message));return}if(o instanceof F){wt(e,o);return}throw o}}var Mo={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Fr(n,e,t){let r=t.operatorLog??(i=>console.error(i)),s=t.maxBodyBytes??Er,o=t.maxImagePartBytes??Po;try{if(n.method!=="POST")throw new F(405,`${String(n.method)} is not supported on ${Ht}`);let i=String(n.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await jt(n,s)}catch(m){throw m instanceof re?new F(413,m.message):new F(400,String(m instanceof Error?m.message:m))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new F(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new F(400,"model must be a string field","model");let d=l===null?void 0:l;await Ir(t.turn,t.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new F(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 m of a.keys())if(!Mo[m])throw new F(400,`form field "${m}" 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[]).`,m);let p=[];for(let m of["image","image[]"])for(let k of a.getAll(m)){if(!(k instanceof File))throw new F(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(k.size>o)throw new F(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let S=new Uint8Array(await k.arrayBuffer()),y=Or(S);if(y===null)throw new F(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:S,mime:y})}if(p.length===0)throw new F(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",u.length,u.length),!await Cr(t.imageModels,d,"edit",e))return;let f=[{type:"input_text",text:u}];for(let{bytes:m,mime:k}of p)f.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Tr(t.clients,d,f,t.turn?pe(t.turn):void 0,t.turn,r);Mr(t.turn,m),Lr(e,m)}catch(m){throw Pr(m,r)}}catch(i){if(i instanceof re){wt(e,new F(413,i.message));return}if(i instanceof F){wt(e,i);return}throw i}}P();var vt="/v1/audio/speech";function Gr(n){return n===vt}var qr=4096,Nr=18e4,Dr=5e3,Lo=64*1024*1024,Ur=8,Br=5,jr=1024*1024,tt="voice_applied",Gt="X-Urun-Voice-Applied",$=class extends Error{status;param;retryAfterSeconds;constructor(e,t,r,s){super(t),this.status=e,this.param=r,this.retryAfterSeconds=s}};function vn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&n.setHeader("retry-after",String(e.retryAfterSeconds)),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Wt=class extends ${constructor(e){super(502,e)}};function Wr(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t!==9&&!(t>=32&&t<=126)&&!(t>=128&&t<=255))return!1}return!0}function Vr(n){return new $(502,`the runtime's ${tt} receipt ${JSON.stringify(n)} cannot be relayed as the ${Gt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function $o(n,e,t){if(n){if(n.model=ie({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.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(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function zr(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}var Fo=2;function qo(n){for(let e=0;e+1<n.byteLength;e+=2)if(Math.abs(n.readInt16LE(e))>Fo)return!1;return!0}function No(n){let e=24e3,t=2,r=1,s=Buffer.alloc(44);return s.write("RIFF",0,"ascii"),s.writeUInt32LE(36+n,4),s.write("WAVE",8,"ascii"),s.write("fmt ",12,"ascii"),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(r,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t,28),s.writeUInt16LE(r*t,32),s.writeUInt16LE(16,34),s.write("data",36,"ascii"),s.writeUInt32LE(n,40),s}var Hr=new WeakMap,Jt=new WeakMap;function Do(n,e){let t=Jt.get(n)??0;if(t>=Ur)throw new $(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 ${Br}s`,void 0,Br);Jt.set(n,t+1);let r=Hr.get(n)??Promise.resolve(),s,o=new Promise(i=>{s=i});return Hr.set(n,o),(async()=>{await r;try{return await e()}finally{Jt.set(n,(Jt.get(n)??1)-1),s()}})()}async function Uo(n,e,t,r){if(typeof n.evictSpeechSession!="function")throw new $(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 n.evictSpeechSession(e)}catch(i){if(!(i instanceof Q))throw i}if(t?.return===void 0)return;let s=Promise.resolve(t.return()).then(()=>{},()=>{}),o;await Promise.race([s,new Promise(i=>{o=setTimeout(i,r)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}function Be(n,e){if(n instanceof $)return n;if(n instanceof ke)throw n;return n instanceof U?new $(404,n.message):new $(502,We("speech",n,e))}async function Jr(n,e,t,r,s,o,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Do(e,async()=>{if(i?.()===!0)return null;let p=!1,f=!1,m=!1,k,S=new Promise(R=>{k=R}),y=[],g=()=>{f&&!m&&y.length>=s.quietRunFrames&&(m=!0,k())},h=e.onOutputAudio(R=>{let O=Buffer.from(R,"base64");if(O.byteLength===0)return;let x=qo(O);if(!p){if(x)return;p=!0}if(x){y.push(O),g();return}for(let I of y)c(I);y.length=0,c(O),g()}),_=null,v,A,b;try{b=(await n.createResponseOn(t,{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 O=new Promise(w=>{A=setTimeout(w,o.capMs)}),x=!1;for(;;){let w=b.next(),C=await Promise.race([w,O]);if(C===void 0){x=!0,w.catch(()=>{});break}if(C.done)break;let N=C.value;if(N.type==="error"){let q=N.error??{};await b.return?.();let K=typeof q.message=="string"&&q.message.length>0&&we(q.message)?q.message:null;throw K===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(N)}`),new $(502,"the speech upstream failed while serving this request")):new $(502,`speech upstream error: ${K}`)}if(N.type==="response.completed"){_=N.response??null,f=!0,u?.(_),g(),await b.return?.();break}}if(clearTimeout(A),x)throw new $(504,`the speech turn produced no terminal event within ${o.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(_===null)throw new $(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([S,new Promise(w=>{v=setTimeout(()=>{I=!0,w()},s.capMs)})]),v!==void 0&&clearTimeout(v),r.voice!==void 0){let w=_[tt];if(typeof w!="string"||w!==r.voice){let C=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof w=="string"?`${tt} ${JSON.stringify(w)}`:`no ${tt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new Wt(C):new $(502,C)}}if(!p)throw new $(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!m&&y.length<1)throw new $(502,`the upstream audio stream did not quiesce within ${s.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return _}catch(R){throw R instanceof Wt||await Uo(n,t,b,o.returnBoundMs),R}finally{v!==void 0&&clearTimeout(v),A!==void 0&&clearTimeout(A),h()}})}function Bo(n,e,t,r){let s=!1,o=0,i=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(s||(s=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),r&&n.setHeader("trailer",Gt)),n.write(a,u=>{u||(o+=a.byteLength,zr(e,o))}),n.writableLength>jr&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${jr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>s,async finish(a){if(!t()){if(r){let u=a[tt];if(typeof u=="string"){if(!Wr(u))throw Vr(u);n.addTrailers({[Gt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:i}}async function jo(n,e,t,r){let s;try{s=await n(e)}catch(o){throw Be(o,r)}return s?!0:(vn(t,new $(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 Ho={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Jo="wav, pcm";async function Kr(n,e,t){let r=t.operatorLog??(a=>console.error(a)),s=t.maxBodyBytes??Lo,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(n.method!=="POST")throw new $(405,`${String(n.method)} is not supported on ${vt}`);let a;try{a=JSON.parse((await Bt(n,s)).toString("utf8")||"{}")}catch(_){throw _ instanceof re?new $(413,_.message):new $(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new $(400,"request body must be a JSON object");let u=a;for(let _ of Object.keys(u))if(!Ho[_])throw new $(400,`request field "${_}" 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.`,_);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new $(400,"input is required and must be a non-empty string","input");if(l.length>qr)throw new $(400,`input is ${l.length} chars \u2014 over the ${qr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new $(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new $(400,"voice must be a non-empty string","voice");if(typeof t.clients.speechVoices!="function")throw new $(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 ${vt} against a stale copy of the list`);let p;try{p=await t.clients.speechVoices(d)}catch(_){throw Be(_,r)}if(p.defect!==null)throw new $(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let f=typeof c=="string"?c:void 0;if(f!==void 0&&p.published.length>0&&!p.published.includes(f))throw new $(400,`voice ${JSON.stringify(f)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=u.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new $(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Jo} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new $(400,"stream_format, when present, must be a string","stream_format");let k=u.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new $(400,"speed, when present, must be a number","speed");if(k!==1)throw new $(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let S=u.instructions;if(S!==void 0){if(typeof S!="string")throw new $(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new $(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 $o(t.turn,t.clients,d);let y=Buffer.byteLength(JSON.stringify(u));if(t.stats?.request("audio_speech",y,y),!await jo(t.speechModels,d,e,r))return;if(typeof t.clients.openAudioOn!="function")throw new $(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 t.clients.speechSessionHandle!="function")throw new $(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 t.clients.evictSpeechSession!="function")throw new $(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let g;try{g=await t.clients.speechSessionHandle(d)}catch(_){throw Be(_,r)}let h;try{h=await t.clients.openAudioOn(g)}catch(_){throw Be(_,r)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(m==="wav"){let _=[],v=await Jr(t.clients,h,g,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Nr,returnBoundMs:t.turnReturnBoundMs??Dr},i,b=>_.push(b),b=>{t.turn&&(t.turn.outputSeconds=Re(b))},r);if(v===null||i())return;let A=Buffer.concat(_);if(f===void 0){let b=v[tt];if(typeof b=="string"){if(!Wr(b))throw Vr(b);e.setHeader(Gt,b)}}zr(t.turn,A.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([No(A.byteLength),A]))}else{let _=Bo(e,t.turn,i,f===void 0),v;try{v=await Jr(t.clients,h,g,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Nr,returnBoundMs:t.turnReturnBoundMs??Dr},i,_.sink,A=>{t.turn&&(t.turn.outputSeconds=Re(A))},r)}catch(A){let b=Be(A,r);if(!_.started())throw b;t.turn&&(t.turn.streamError=!0),_.fail(b);return}if(v===null)return;try{await _.finish(v)}catch(A){let b=Be(A,r);t.turn&&(t.turn.streamError=!0),_.fail(b);return}}}catch(_){throw Be(_,r)}}catch(a){if(a instanceof re){vn(e,new $(413,a.message));return}if(a instanceof $){vn(e,a);return}throw a}}P();var Vt="/v1/audio/transcriptions";function Xr(n){return n===Vt}var Yr="/v1/audio/models",Go=16*1024*1024,Wo=64*1024*1024,z=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}};function bn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Qr(n){return n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===65&&n[10]===86&&n[11]===69}function Vo(n){if(!Qr(n))return null;let e=12,t=null,r=null;for(;e+8<=n.length;){let o=String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),i=(n[e+4]|n[e+5]<<8|n[e+6]<<16|n[e+7]<<24)>>>0,a=e+8;if(o==="fmt "&&a+16<=n.length){let u=n[a+2]|n[a+3]<<8,l=(n[a+4]|n[a+5]<<8|n[a+6]<<16|n[a+7]<<24)>>>0,d=n[a+14]|n[a+15]<<8;t={sampleRate:l,channels:u,bitsPerSample:d}}else if(o==="data"){let u=n.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(t===null||r===null||r===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let s=r/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(s)||s<0?null:{seconds:s,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function zo(n,e,t){if(n){if(n.model=ie({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.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(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ko(n,e){n&&(n.outputUnits=e.seconds)}async function Xo(n,e,t,r,s,o,i){let a=i??(c=>console.error(c)),u=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...r!==void 0?{language:r}:{}},s),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},f=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&we(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new z(f==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new z(f==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new z(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return o&&(o.outputSeconds=Re(d)),Qe(l,d)}function Zr(n,e){if(n instanceof z)return n;if(n instanceof ke)throw n;return n instanceof U?new z(404,n.message):new z(502,We("transcription",n,e))}async function Yo(n,e,t,r){let s;try{s=await n(e)}catch(o){throw Zr(o,r)}return s?!0:(bn(t,new z(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 Qo=new Set(["file","model","language","response_format"]);async function es(n,e,t){let r=t.operatorLog??(i=>console.error(i)),s=t.maxBodyBytes??Wo,o=t.maxAudioPartBytes??Go;try{if(n.method!=="POST")throw new z(405,`${String(n.method)} is not supported on ${Vt}`);let i=String(n.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new z(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await jt(n,s)}catch(g){throw g instanceof re?new z(413,g.message):new z(400,String(g instanceof Error?g.message:g))}let u=new Map;for(let g of a.keys()){if(!Qo.has(g))throw new z(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);u.set(g,(u.get(g)??0)+1)}for(let[g,h]of u)if(h>1)throw new z(400,`form field "${g}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,g);let l=a.get("model");if(l!==null&&typeof l!="string")throw new z(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new z(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,f=a.get("response_format")??"json";if(f!=="json")throw new z(400,`response_format ${JSON.stringify(f)} 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 m=a.get("file");if(!(m instanceof File))throw new z(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>o)throw new z(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await m.arrayBuffer());if(!Qr(k))throw new z(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 S=Vo(k);if(S===null)throw new z(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 zo(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",k.length,k.length),!await Yo(t.transcriptionModels,d,e,r))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let g=await Xo(t.clients,d,y,p,t.turn?pe(t.turn):void 0,t.turn,r);Ko(t.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw Zr(g,r)}}catch(i){if(i instanceof re){bn(e,new z(413,i.message));return}if(i instanceof z){bn(e,i);return}throw i}}P();var os="/v1/usage/requests",ts=1e4,Zo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ce=class extends Error{constructor(t,r=400){super(t);this.status=r;this.name="UsageRequestError"}status},ee=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},zt=class extends ee{constructor(e){super(e),this.name="UsageWithholdingError"}},is=1024*1024;function Sn(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new Ce(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new Ce(`"${e}" must be an array of uuid strings`);if(t.length>ts)throw new Ce(`"${e}" carries ${t.length} ids; at most ${ts} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],s=new Set;for(let o of t){if(typeof o!="string"||!Zo.test(o))throw new Ce(`"${e}" contains ${JSON.stringify(o)}, 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`);s.has(o)||(s.add(o),r.push(o))}return r}function as(n){return Sn(n,"inference_ids")}var ei=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function nt(n,e,t){let r=n[e];if(typeof r!="string"||r==="")throw new ee(`${t}: ${e} is not a non-empty string (got ${st(r)})`);return r}function kn(n,e,t){let r=n[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new ee(`${t}: ${e} is neither null nor a non-empty string (got ${st(r)})`);return r}function rt(n,e,t,r){let s=n[e];if(s===null)return null;let o=typeof s=="number"?s:typeof s=="string"&&/^-?\d+(\.\d+)?$/.test(s.trim())?Number(s.trim()):NaN;if(!Number.isFinite(o))throw new ee(`${t}: ${e} is not a number (got ${st(s)})`);if(r&&!Number.isSafeInteger(o))throw new ee(`${t}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(o<0)throw new ee(`${t}: ${e} is negative`);return Object.is(o,-0)?0:o}var ti=40,ns=64,rs=600;function us(n){let e=Object.keys(n).sort(),r=e.slice(0,ti).map(s=>s.length>ns?`${s.slice(0,ns)}\u2026`:s).join(", ");return r.length>rs&&(r=`${r.slice(0,rs)}\u2026`),`${e.length} keys present: [${r}]`}function st(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function xn(n){Oe(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
23
+ `)}function ni(n,e){let t;try{t=n(e)}catch{ss(n,e);return}ri(t)&&Promise.resolve(t).catch(()=>{ss(n,e)})}function ri(n){return typeof n?.then=="function"}function ss(n,e){if(n!==xn)try{xn(e)}catch{}}function zu(n,e=xn){let t=n?.requests;if(!Array.isArray(t)){let s=n!==null&&typeof n=="object"&&!Array.isArray(n)?us(n):st(n);throw new ee(`the usage surface answered without a "requests" array: got ${st(t)} (${s})`)}let r=[];for(let s=0;s<t.length;s++){let o=`usage.requests[${s}]`;try{r.push(si(t[s],o))}catch(i){if(i instanceof zt||!(i instanceof ee))throw i;ni(e,{where:o,reason:i.message})}}if(t.length>0&&r.length===0)throw new ee(`the usage surface returned ${t.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 si(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new ee(`${e} is not an object: got ${st(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new zt(`${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 s of ei)if(!Object.hasOwn(t,s))throw new ee(`${e} has no "${s}" column (${us(t)})`);let r=rt(t,"http_status",e,!0);if(r===null)throw new ee(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:nt(t,"inference_id",e),model_id:nt(t,"model_id",e),identity_kind:nt(t,"identity_kind",e),variant:kn(t,"variant",e),task:nt(t,"task",e),http_status:r,started_at:nt(t,"started_at",e),completed_at:nt(t,"completed_at",e),prompt_tokens:rt(t,"prompt_tokens",e,!0),completion_tokens:rt(t,"completion_tokens",e,!0),output_units:rt(t,"output_units",e,!1),output_minutes:rt(t,"output_minutes",e,!1),cost_nano_usd:rt(t,"cost_nano_usd",e,!0),price_version:kn(t,"price_version",e),priced_at:kn(t,"priced_at",e)}}function Kt(n,e){let t=new Set(e),r=new Set;for(let s=0;s<n.length;s++){let o=n[s];if(!t.has(o.inference_id))throw new ee(`the usage surface returned an id at validated answer position ${s} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(o.inference_id))throw new ee(`the usage surface returned ${o.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(o.inference_id)}}import{SessionAllocationError as Ti,SessionFailedError as Pi}from"@urun-sh/core";P();var Rn="/partners/huggingface/v1/billing/requests";function oi(n){return Sn(n,"requestIds")}function ii(n){return n>=200&&n<=399}function ai(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&ii(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function ls(n,e){let t=oi(n),r=await e(t);return Kt(r,t),ai(r)}P();var ui={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function li(n){return ui[n]??null}var ps=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function di(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ci(n){return n==="surface"}function pi(n){let e=n?.ledgerFailureReason;return ps.includes(e)?e:"unknown"}var mi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ds=["priced","unpriced"],fi={written:ds,already_written:ds,skipped:mi,failed:ps},tl=Object.entries(fi).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function hi(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function gi(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var yi=256,cs=4096,bt=12e4,_i=250,wi=8e3,Ae=[],An=new Set,kt=0,ot=!1;function nl(){return Ae.length}function rl(n=Date.now()){let e=Ae[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Xt=new Set;function ms(){return kt===0&&Ae.length===0}function fs(){if(ms()){ot=!1;for(let n of[...Xt])n()}}async function sl(n=hs){return ms()?!0:await new Promise(e=>{let t=null,r=()=>{Xt.delete(r),t&&clearTimeout(t),e(!0)};Xt.add(r),t=setTimeout(()=>{Xt.delete(r),e(!1)},n),t.unref?.()})}function ol(){ot=!0;let n=[...Ae.splice(0,Ae.length),...An];for(let e of n)e.settled||je(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 ${hs}ms drain \u2014 the request was served and answered, and its billing row was never written`});return fs(),n.length}var hs=5e3;function gs(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
24
+ `}function vi(n){Oe(process.stdout,n)}function ys(n,e){try{n(e)}catch{}}function _s(n){let{record:e,ledger:t}=n;if(t===null)return;let r=t.report??vi,s=li(e.path);if(s===null)return;let o=d=>{try{t.observe(d)}catch{}},i=(d,c)=>{o({outcome:"skipped",reason:d}),ys(r,gs("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let 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 l={inference_id:e.inference_id,...u,task:s,http_status:e.status,started_at:gi(e),completed_at:e.ts,billable_outcome:hi(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,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(Ae.length>=cs){i("queue_full",`${Ae.length} ledger writes are already waiting (capacity ${cs}, ${kt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ae.push({entry:l,req:n.req,record:e,ledger:t,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),kt<yi&&(kt+=1,bi())}async function bi(){try{for(;;){let n=ki();if(n===void 0)return;An.add(n);try{await xi(n)}finally{An.delete(n)}}}finally{kt-=1,fs()}}function ki(){let n=Date.now();for(;;){let e=Ae.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<bt)return e;je(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${t}ms for the control plane (bound ${bt}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 xi(n){let{entry:e,record:t,ledger:r}=n;for(;;){n.attempts+=1;try{let s=await r.write(n.req,e);je(n,{outcome:"written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:s.inference_id,path:t.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:t.org,session_id:e.session_id,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,unpriced_reason:s.unpriced_reason,attempts:n.attempts});return}catch(s){let o=di(s);if(o!==null){je(n,{outcome:"already_written",reason:o.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:o.cost_nano_usd,price_version:o.price_version,attempts:n.attempts});return}let i=pi(s),a=Date.now()-n.queuedAt;if(ot){je(n,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:n.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: ${s instanceof Error?s.message:String(s)}`});return}if(ci(i)&&a<bt){if(await Ri(Si(n.attempts)),ot||Date.now()-n.queuedAt>=bt){let u=Date.now()-n.queuedAt;je(n,{outcome:"failed",reason:ot?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ot?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${bt}ms dwell bound (waited ${u}ms over ${n.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${s instanceof Error?s.message:String(s)}`});return}continue}je(n,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:n.attempts,waited_ms:a,error:s instanceof Error?s.message:String(s)});return}}}function Si(n){return Math.min(wi,_i*2**Math.max(0,n-1))}function Ri(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function je(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:r,...s}=t;ys(n.report,gs(r,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...s}))}P();var En="x-urun-profile",xt="voice";var ue=class extends Error{status=400},Ai=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Ii=/\s/;function Ei(n){return Ai.test(n)}function In(n,e,t){let r=n[e];if(r===void 0)return t;if(typeof r!="boolean")throw new ue(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ws(n,e,t,r={}){let s=n[e];if(s===void 0)return t;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new ue(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(s)})`);if(r.min!==void 0&&s<r.min)throw new ue(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(s)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&s>r.max)throw new ue(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(s)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return s}function vs(n,e){let t=Array.isArray(n)?n[0]:n,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ue(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let s=r,o=s?.profile,i=!1;if(t!=null){let l=t.trim();if(l==="")throw new ue(`the ${En} header is empty \u2014 the only profile this lane accepts is "${xt}" (omit the header for the ordinary lane)`);if(l!==xt)throw new ue(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${xt}"`);i=!0}if(o!==void 0){if(typeof o!="string"||o!==xt)throw new ue(`unknown profile ${JSON.stringify(o)} \u2014 the only profile this lane accepts is "${xt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ue("the voice profile is streaming-only \u2014 send stream: true");let a=s?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ue("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:ws(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:ws(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:In(u,"sentence_flush",!0),includeReasoning:In(u,"include_reasoning",!1),metadata:In(u,"metadata",!1)}}var it=class{constructor(e,t){this.config=e;this.sink=t}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let t=this.boundedCut();this.sink(this.buffer.slice(0,t)),this.buffer=this.buffer.slice(t)}(this.buffer.length>=e||this.config.sentenceFlush&&Ei(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let s=e-1;s>0;s--)if(Ii.test(this.buffer[s]))return s+1;let t=Math.max(1,e),r=this.buffer.charCodeAt(t-1);return r>=55296&&r<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Pn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ci(n){n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),n.flushHeaders(),n.socket?.setNoDelay(!0)}function se(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function j(n,e,t,r="invalid_request_error",s){se(n,e,{error:s?{message:t,type:r,code:s}:{message:t,type:r}})}function Cn(n,e,t){let r=e.error,s=r?.type??"upstream_error",o=t?.operatorError??(d=>console.error(d)),i=xe(r),a=i??ve(t?.inferenceId??null);i===null&&o(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=s==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&n.setHeader("retry-after","30"),se(n,l,{error:{message:a,type:s,code:u}})}function be(n,e,t,r){se(n,e,{type:"error",error:{type:t,message:r}})}function at(n,e,t){if(e==="anthropic"){se(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}se(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Mi=64*1024*1024,St=class extends Error{};async function bs(n,e=Mi){let t=[],r=0;for await(let o of n){if(r+=o.length,r>e)throw new St(`request body exceeds ${e} bytes`);t.push(o)}let s=Buffer.concat(t).toString("utf8");return s?JSON.parse(s):{}}function He(n,e,t,r){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:r}]}}function Ss(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,s=r(t.input_tokens),o=r(t.output_tokens),i=u=>u??0,a=r(t.total_tokens)??i(s)+i(o);if(i(s)>0||i(o)>0){let u={input_tokens:i(s),output_tokens:i(o),total_tokens:a};return s===null||o===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return s===null||o===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Yt(n){let e=Ss(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ks(n){let e=Yt(n);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Li(n)},completion_tokens_details:{reasoning_tokens:0}}}function Li(n){let e=n?.usage;if(!e||typeof e!="object")return 0;let t=e.input_tokens_details;if(!t||typeof t!="object")return 0;let r=t.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function $i(n,e){let t=Ss(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function Fi(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,r=u=>{let l=t[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},s=r("queue_ms"),o=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return s===null||o===null||i===null||a===null?null:{queue_ms:s,prefill_ms:o,decode_ms:i,total_ms:a}}function qi(n,e){let t=Fi(e);t&&(n.timing=t),n.outputSeconds=Re(e)}function Je(n,e){$i(n,e),qi(n,e)}async function en(n,e,t){if(typeof e.catalogIdentity!="function"){n.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(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Rs(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let s of r.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function Ni(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Qt=class extends Error{};function Di(n,e){return Array.isArray(e)?e.map(t=>{let r=t;if(r.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let s=r.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Qt(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ui(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let r of t.tool_calls){let s=r.function??{};e.push({type:"function_call",call_id:r.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:Di(t.role,t.content)})}return e}function On(n){return Xe(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Bi(n,e,t,r,s,o,i){let a=ht(o.id),u=n.stream===!0;if(o.model=ie(n),o.stream=u,await en(o,e,typeof n.model=="string"?n.model:void 0),u){let g;try{g=await yt({body:n,clients:e,store:t,stats:s,responseId:a,turn:o})}catch(h){if(h instanceof U){at(r,"openai",h);return}if(h instanceof me){j(r,h.status,h.message);return}if(h instanceof ge||h instanceof le){r.setHeader("retry-after","2"),j(r,503,h.message,"capacity_error");return}throw h}Pn(r);for await(let h of g.events){if(h.type==="error"){o.streamError=!0;let _=h.error,v=xe(_),A=v??ve(o.id);v===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),r.write(`event: error
25
+ data: ${JSON.stringify({error:{message:A,type:_?.type??"upstream_error",code:_?.code??null}})}
26
+
27
+ `),r.end();return}h.type==="response.completed"&&Je(o,h.response),r.write(`event: ${String(h.type??"message")}
28
+ data: ${JSON.stringify(h)}
29
+
30
+ `)}r.write(`data: [DONE]
31
+
32
+ `),r.end();return}let l;try{l=Ze(t,n)}catch(g){if(g instanceof me){j(r,g.status,g.message);return}throw g}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(n.input)));let d=n.store!==!1,c=ie(n);s.model(c);let p=Array.isArray(n.tools)&&n.tools.length>0,f;try{f=await gn(e,n,l,!1,pe(o))}catch(g){if(g instanceof U){at(r,"openai",g);return}if(g instanceof me){j(r,g.status,g.message);return}if(g instanceof ge||g instanceof le){r.setHeader("retry-after","2"),j(r,503,g.message,"capacity_error");return}throw g}let m=[],k=null;for await(let g of s.track(f,c,o)){if(m.push(g),g.type==="error"){Cn(r,g,{inferenceId:o.id,operatorError:i});return}g.type==="response.completed"&&(k=g.response)}if(k==null){j(r,502,"upstream produced no response.completed event","upstream_error");return}Je(o,k);let S=Qe(m,k),y=Ue(p,Xe(k).length,S);if(y){j(r,502,De(c,y),"upstream_error");return}d&&t.remember(a,l,hn(k,S),d),se(r,200,{...k,id:a})}async function ji(n,e,t,r,s,o,i){let a=n.messages;if(!Array.isArray(a)){j(t,400,"chat/completions requires a messages array");return}let u;try{u=vs(o,n)}catch(x){if(x instanceof ue){j(t,x.status,x.message);return}throw x}let l=String(n.model??"urun"),d=cr(s.id),c;try{c=Ui(a)}catch(x){if(x instanceof Qt){j(t,400,x.message);return}throw x}let p=ie(n);r.model(p),s.model=p,s.stream=n.stream===!0,await en(s,e,typeof n.model=="string"?n.model:void 0);let f=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await e.createResponse({model:n.model,input:c,stream:!0,tools:Ni(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{},...n.response_format!==void 0?{response_format:n.response_format}:{}},pe(s))}catch(x){if(x instanceof U){at(t,"openai",x);return}if(x instanceof ge||x instanceof le){t.setHeader("retry-after","2"),j(t,503,x.message,"capacity_error");return}throw x}if(n.stream===!0){u?Ci(t):Pn(t);let x=[],I=new Pe,w="",C=u?new it(u,q=>{t.write(`data: ${JSON.stringify(He(d,l,{content:q},null))}
33
+
34
+ `)}):null,N=q=>{C?.flush(),t.write(q),t.end()};try{u?.metadata&&t.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
35
+
36
+ `),t.write(`data: ${JSON.stringify(He(d,l,{role:"assistant"},null))}
37
+
38
+ `);for await(let X of r.track(m,p,s)){x.push(X);let oe=Ye(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")w+=X.delta,C?C.push(X.delta):t.write(`data: ${JSON.stringify(He(d,l,{content:X.delta},null))}
39
+
40
+ `);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")(!u||u.includeReasoning)&&t.write(`data: ${JSON.stringify(He(d,l,{reasoning_content:X.delta},null))}
41
+
42
+ `);else if(oe){C?.flush();let{call:L,isNew:D}=I.add(oe),H=D?{index:oe.tool_index,id:L.id??`call_${oe.tool_index}`,type:"function",function:{name:L.name??"",arguments:oe.delta}}:{index:oe.tool_index,function:{arguments:oe.delta}};t.write(`data: ${JSON.stringify(He(d,l,{tool_calls:[H]},null))}
43
+
44
+ `)}else if(X.type==="error"){s.streamError=!0;let L=X.error??{},D=xe(L),H=D??ve(s.id);D===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(X)}`),N(`data: ${JSON.stringify({error:{message:H,type:L.type??"upstream_error",code:L.code??null}})}
45
+
46
+ `);return}}let q=On(Se(x)),K=Ue(f,I.size+q.length,w);if(K){s.streamError=!0,N(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:De(p,K)}})}
47
+
48
+ `);return}C?.flush(),I.size===0&&q.length>0&&t.write(`data: ${JSON.stringify(He(d,l,{tool_calls:q},null))}
49
+
50
+ `);let B=I.size>0||q.length>0;t.write(`data: ${JSON.stringify(He(d,l,{},B?"tool_calls":"stop"))}
51
+
52
+ `);let Ee=Yt(Se(x));Je(s,Se(x)),Ee&&t.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:ks(Se(x))})}
53
+
54
+ `),t.write(`data: [DONE]
55
+
56
+ `),t.end();return}finally{C?.flush(),C?.dispose()}}let k="",S="",y=[],g=new Pe;for await(let x of r.track(m,p,s)){y.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(k+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(S+=x.delta);let I=Ye(x);if(I&&g.add(I),x.type==="error"){Cn(t,x,{inferenceId:s.id,operatorError:i});return}}let h=Se(y);Je(s,h);let _=On(h),v=_.length>0?_:On({output:g.items()}),A=Ue(f,v.length,k);if(A){j(t,502,De(p,A),"upstream_error");return}let b=v.map(({index:x,...I})=>I),R={role:"assistant",content:k||null},O=S||Rs(h);O&&(R.reasoning_content=O),b.length>0&&(R.tool_calls=b),se(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:R,finish_reason:b.length>0?"tool_calls":"stop"}],usage:ks(h)})}var As="sense-latest";async function Hi(n,e,t,r,s,o){if(n===null||typeof n!="object"||Array.isArray(n)){j(t,400,"systemone requires a JSON object body");return}delete n.key;let i=typeof n.model=="string"&&n.model?n.model:As,a=ie({model:i});if(s.model=a,s.stream=!1,n.state===void 0||n.state===null){j(t,400,"systemone requires a state (string or JSON structure)");return}let u=n.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){j(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){j(t,400,"systemone media, when present, must be an array");return}let l=await Is(n,i,a,e,t,r,s,o);l!==null&&se(t,200,l.answer)}async function Is(n,e,t,r,s,o,i,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=u;let l=performance.now();o.model(t),await en(i,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},pe(i))}catch(y){if(y instanceof U)return at(s,"openai",y),null;if(y instanceof ge||y instanceof le)return s.setHeader("retry-after","2"),j(s,503,y.message,"capacity_error"),null;throw y}u.dial_ms=Math.round(performance.now()-c);let p=[],f=null;try{for await(let y of o.track(d,t,i))if(f===null&&(f=performance.now(),u.first_event_ms=Math.round(f-c)),p.push(y),y.type==="error")return Cn(s,y,{inferenceId:i.id,operatorError:a}),null}catch(y){if(y instanceof U)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),at(s,"openai",y),null;if(y instanceof ge||y instanceof le)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),s.setHeader("retry-after","2"),j(s,503,y.message,"capacity_error"),null;throw f!==null&&(u.stream_ms=Math.round(performance.now()-f)),y}f!==null&&(u.stream_ms=Math.round(performance.now()-f));let m=Se(p);if(m==null)return j(s,502,"upstream produced no response.completed event","upstream_error"),null;Je(i,m);let k=Qe(p,m),S;try{S=JSON.parse(k)}catch{return j(s,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return j(s,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let y=S.timing;if(typeof y=="object"&&y!==null&&!Array.isArray(y)&&"question_fwd_ms"in y&&"head_ms"in y){let g=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=g(y.question_fwd_ms),u.head_ms=g(y.head_ms)}}return{answer:S,completed:m}}async function Ji(n,e,t,r,s,o){if(n===null||typeof n!="object"||Array.isArray(n)){j(t,400,"decisions requires a JSON object body");return}let i=typeof n.model=="string"&&n.model?n.model:As,a=ie({model:i});s.model=a,s.stream=!1;let u;try{u=vr(n,i)}catch(p){if(p instanceof M){j(t,400,p.message);return}throw p}let l=await Is(u.systemone,i,a,e,t,r,s,o);if(l===null)return;let d;try{d=xr(u.specs,l.answer)}catch(p){if(p instanceof fe){j(t,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;se(t,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function Gi(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Rt=class extends Error{};function Zt(n){return new Rt(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Wi(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Vi(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new Rt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function zi(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw Zt(typeof n);let e="";for(let t of n){let r=String(t.type??"");if(r!=="text")throw Zt(`tool_result > ${r}`);e+=String(t.text??"")}return e}function Ki(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Zt(typeof t);let r=[],s="",o=()=>{s&&(r.push({role:e,content:s}),s="")};for(let i of t){let a=String(i.type??"");if(a==="text")s+=String(i.text??"");else if(a==="tool_use")o(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")o(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:zi(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Zt(a)}}return o(),r}function Tn(n){return Xe(n).map((e,t)=>{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_${t}`,name:e.name??"",input:r}})}async function Xi(n,e,t,r,s,o){let i=n.messages;if(!Array.isArray(i)){be(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){be(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){be(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(R=>typeof R!="string"))){be(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(n.model??"urun"),u=pr(s.id),l=[],d;try{n.system&&l.push({role:"system",content:Gi(n.system)});for(let R of i)l.push(...Ki(R));d=Vi(n.tool_choice)}catch(R){if(R instanceof Rt){be(t,400,"invalid_request_error",R.message);return}throw R}let c=ie(n);r.model(c),s.model=c,s.stream=n.stream===!0,await en(s,e,typeof n.model=="string"?n.model:void 0);let p=Array.isArray(n.tools)&&n.tools.length>0,f;try{f=await e.createResponse({model:n.model,input:l,stream:!0,tools:Wi(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},pe(s))}catch(R){if(R instanceof U){at(t,"anthropic",R);return}if(R instanceof ge||R instanceof le){t.setHeader("retry-after","2"),be(t,503,"capacity_error",R.message);return}throw R}let m=(R,O)=>{t.destroyed||t.write(`event: ${R}
57
+ data: ${JSON.stringify({type:R,...O})}
58
+
59
+ `)};if(n.stream===!0){let R=r.track(f,c,s);Pn(t),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,x="",I=0,w="none",C=()=>w,N=-1,q=-1,K=new Pe,B=[],Ee=()=>{w!=="none"&&(w="none",m("content_block_stop",{index:N}))},X=(J,Y)=>{Ee(),w=J,N=I++,m("content_block_start",{index:N,content_block:Y})};for await(let J of R){if(t.destroyed)break;B.push(J);let Y=Ye(J);if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:N,delta:{type:"thinking_delta",thinking:J.delta}});else if(J.type==="response.output_text.delta"&&typeof J.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),O+=1,x+=J.delta,m("content_block_delta",{index:N,delta:{type:"text_delta",text:J.delta}});else if(Y){let{call:he}=K.add(Y);(C()!=="tool"||Y.tool_index!==q)&&(q=Y.tool_index,X("tool",{type:"tool_use",id:he.id??`call_${Y.tool_index}`,name:he.name??"",input:{}})),Y.delta&&m("content_block_delta",{index:N,delta:{type:"input_json_delta",partial_json:Y.delta}})}else if(J.type==="error"){s.streamError=!0;let he=J.error,Le=xe(he);Le===null&&o(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(J)}`),m("error",{error:{type:"api_error",message:Le??ve(s.id)}}),t.end();return}}if(t.destroyed)return;let oe=Se(B),L=Xe(oe),D=Ue(p,K.size+L.length,x);if(D){s.streamError=!0,m("error",{error:{type:"api_error",message:De(c,D)}}),t.end();return}Ee();let H=[];if(K.size===0)try{H=Tn(oe)}catch(J){s.streamError=!0;let Y=de(J,{inferenceId:s.id});Y.redacted&&o(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(J instanceof Error?J.message:J)}`),m("error",{error:{type:"api_error",message:Y.message}}),t.end();return}I===0&&H.length===0&&(X("text",{type:"text",text:""}),Ee()),H.forEach(J=>{let Y=I++;m("content_block_start",{index:Y,content_block:{...J,input:{}}}),m("content_block_delta",{index:Y,delta:{type:"input_json_delta",partial_json:JSON.stringify(J.input??{})}}),m("content_block_stop",{index:Y})});let Me=K.size>0||H.length>0,Ge=Yt(oe);Je(s,oe),m("message_delta",{delta:{stop_reason:Me?"tool_use":"end_turn"},usage:Ge?{input_tokens:Ge.input_tokens,output_tokens:Ge.output_tokens}:{output_tokens:O}}),m("message_stop",{}),t.end();return}let k="",S="",y=[],g=new Pe;for await(let R of r.track(f,c,s)){y.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(k+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(S+=R.delta);let O=Ye(R);if(O&&g.add(O),R.type==="error"){let x=R.error,I=x?.type==="invalid_request_error",w=xe(x);w===null&&o(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),be(t,I?400:502,I?"invalid_request_error":"api_error",w??ve(s.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=Se(y);Je(s,h);let _;try{_=Tn(h),_.length===0&&g.size>0&&(_=Tn({output:g.items()}))}catch(R){let O=de(R,{inferenceId:s.id});O.redacted&&o(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),be(t,502,"api_error",O.message);return}let v=Ue(p,_.length,k);if(v){be(t,502,"api_error",De(c,v));return}let A=[],b=S||Rs(h);b&&A.push({type:"thinking",thinking:b}),(k||_.length===0)&&A.push({type:"text",text:k}),A.push(..._),se(t,200,{id:u,type:"message",role:"assistant",content:A,model:a,stop_reason:_.length>0?"tool_use":"end_turn",usage:Yt(h)??{input_tokens:0,output_tokens:0}})}function Yi(n){Oe(process.stdout,n)}function Qi(n){let{clients:e,apiKey:t,identity:r,statusOf:s}=n,o=typeof e=="function"?e:()=>e,i=n.requestLog??Yi,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new qe;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),f=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(h,_,v,A,b)=>f?be(c,h,A,_):j(c,h,_,v,b),k=fn(p.pathname),S=p.pathname.startsWith("/partners/"),y=k||S?{id:ft(),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,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;y&&(c.setHeader(lr,y.id),c.once("close",()=>{let h=mr({turn:y,method:d.method??"",path:p.pathname,res:c});i(fr(h)),u?.(h),_s({record:h,ledger:n.ledger??null,req:d})}));let g=()=>dr(p.pathname,y);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){se(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){se(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===os?"canonical":p.pathname===Rn?"huggingface":null;if(h){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=n.usage;if(!b){m(501,`${p.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 R=b.authorize(d),O;try{O=await bs(d,is)}catch(w){if(w instanceof St){m(413,w.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=w=>b.lookup(R,w),I;try{if(h==="canonical"){let w=as(O),C=await x(w);Kt(C,w),I={requests:C}}else I=await ls(O,x)}catch(w){if(w instanceof Ce){m(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}se(c,200,I);return}if(d.method==="GET"&&p.pathname===ut){let b=await o(d);if(y&&(y.org=b.tenant??null),!b.openRouterModels){m(501,`GET ${ut} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}se(c,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Rn} and GET ${ut}`,"invalid_request_error","not_found_error");return}let _=await o(d);if(y&&(y.org=_.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ut}),c.end();return}se(c,200,await _.listModels());return}if(d.method==="GET"&&p.pathname===Ar){if(!_.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}se(c,200,await _.listImageModels());return}if(Rr(p.pathname)){if(!_.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:_,imageModels:_.supportsImages,stats:l,turn:g(),operatorLog:a};p.pathname===Ht?await Fr(d,c,b):await $r(d,c,b);return}if(d.method==="GET"&&p.pathname===Yr){if(!_.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}se(c,200,await _.listSpeechToTextModels());return}if(Xr(p.pathname)){if(!_.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Vt}`,"not_implemented","not_implemented_error");return}let b={clients:_,transcriptionModels:_.supportsTranscription,stats:l,turn:g(),operatorLog:a};await es(d,c,b);return}if(Gr(p.pathname)){if(!_.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${vt}`,"not_implemented","not_implemented_error");return}let b={clients:_,speechModels:_.supportsSpeech,stats:l,turn:g(),operatorLog:a};await Kr(d,c,b);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let v;try{v=await bs(d)}catch(b){if(b instanceof St){m(413,b.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let A=Buffer.byteLength(JSON.stringify(v));if(p.pathname==="/v1/responses"){l.request("responses",A,A),await Bi(v,_,gt(_),c,l,g(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",A,A),await ji(v,_,c,l,g(),d.headers[En],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",A,A),await Hi(v,_,c,l,g(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",A,A),await Ji(v,_,c,l,g(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",A,A),await Xi(v,_,c,l,g(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",A,A),be(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let _=String(h instanceof Error?h.message:h);if(!c.headersSent){let b=s?.(h)??null;if(b){b.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${b.operatorDetail}`),m(b.status,_,b.openaiType,b.anthropicType,b.code);return}if(h instanceof Ti){let O=Ft(h.code);if(O){let x=h.retryAfterSeconds??(O.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),m(O.status,mt(O,h.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(h instanceof Pi){let O=qt(h);if(O){let x=O.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),m(O.status,mt(O,h.status.sessionId?`session ${h.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(h instanceof ee){m(502,_,"upstream_error","api_error");return}if(h instanceof ye){h.retryable&&c.setHeader("Retry-After","1");let O=de(h,{inferenceId:y?.id??null});O.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:_e(h)}`),m(502,O.message,"upstream_error","api_error",h.code);return}if(h instanceof Te){c.setHeader("Retry-After",String(h.retryAfterSeconds)),m(h.status,_,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let R=de(h,{inferenceId:y?.id??null});R.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:_e(h)}`),m(500,R.message,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0);let v=h instanceof ye?h.code:null,A=de(h,{inferenceId:y?.id??null});A.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:_e(h)}`),c.destroyed||(f?c.write(`event: error
60
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:A.message}})}
61
+
62
+ `):c.write(`data: ${JSON.stringify({error:{message:A.message,type:"upstream_error",code:v}})}
63
+
64
+ `)),c.end()})}}function Fl(n){let{clients:e,apiKey:t}=n,r=Oi(Qi(n)),s=wr(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),o=mn(r,{resolver:xs(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),tr(r,{clients:e,apiKey:t}),r}P();var Ie=(n,e)=>Object.assign(new Error(e),{status:n}),ta='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ln=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Mn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof U?Ie(404,t.message):t}};async function Es(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ie(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ta}`);if(s==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let o=await Mn(n,t.stt),i=await Mn(n,e),a=await Mn(n,t.tts),u=await n.openAudioOn(o,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,na({clients:n,chatHandle:i,ttsHandle:a,chatModel:e,companions:t},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(o,p)}catch(f){throw f instanceof Q?Ln("stt",t.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Os(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var tn=class extends Error{};async function*na(n,e,t,r){let{clients:s,chatHandle:o,ttsHandle:i,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,S=[],y=null,g=new Promise((I,w)=>{t&&t.addEventListener("abort",()=>w(new tn),{once:!0})}),h=()=>f||t?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await s.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(N){throw N instanceof Q?Ln("tts",u.tts,N):N}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let N=C.next(),q;try{q=await Promise.race([N,g])}catch(B){if(N.catch(()=>{}),B instanceof tn)return;throw B}if(q.done)return;let K=q.value;if(K.type==="error"){let B=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${B}`)}if(K.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;S.length>0&&!h();){let I=S.shift();await _(I)}},A=I=>{if(I===""||h()||(S.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),m??=C})},b=()=>{f=!0,S.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},R=async()=>{for(;S.length>0||y!==null;){let I=y;if(I===null){await _(S.shift());continue}await I}},O=p?new it({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>A(I)):null,x=null;try{let I;try{I=await s.createResponseOn(o,d)}catch(w){throw w instanceof Q?Ln("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}O?.flush(),O?.dispose(),p&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),b();try{if(m instanceof Q)throw m}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function sa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function oa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var ia='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function aa(n,e,t,r){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await n.supportsAudio(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(!s){let d=null;if(n.realtimeCompanionsFor)try{d=await n.realtimeCompanionsFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!==null)return await Es(n,e,d,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ia}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await n.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let a=`conn_${ra()}`,u={audio:await n.openAudioOn(i,t,a)},l={clients:{createResponse:async d=>await n.createResponseOn(i,d,a)},voice:s,audioSession:u};return o&&(l.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),n.releaseSessionHandle&&(l.release=()=>n.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function xs(n,e,t){let r=Os(n,t);return{resolve:async(s,o)=>{if(e!==void 0){let i=s.headers.authorization,a=typeof i=="string"?i.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw ce(401,"invalid local proxy api key")}return aa(r,sa(s),o,oa(s))}}}export{Et as a,tr as b,pa as c,ke as d,le as e,nr as f,$s as g,ba as h,ka as i,_o as j,wr as k,pt as l,pn as m,mn as n,Os as o,sa as p,oa as q,aa as r,xs as s,os as t,ee as u,zu as v,Rn as w,tl as x,nl as y,rl as z,sl as A,ol as B,As as C,Qi as D,Fl as E};
@@ -1 +1 @@
1
- import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var w="llm-resp";async function*v(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*l(e,t){let o=`${w}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*v(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var k=class{constructor(t,o=15e3){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),l(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),l(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,v as d,l as e,k as f};
1
+ import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var w="llm-resp";async function*v(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*g(e,t){let o=`${w}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*v(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var k=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,v as d,g as e,k as f};