@urun-sh/openai 0.6.41 → 0.6.43

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 (62) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-2EsjJUz1.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BIcQ6p6Z.d.cts} +1 -1
  3. package/dist/{chunk-ILYHXVNZ.js → chunk-27HP3RMZ.js} +1 -1
  4. package/dist/chunk-2NKCALKY.js +22 -0
  5. package/dist/chunk-2RO722HS.js +2 -0
  6. package/dist/chunk-7DUSLXPG.js +1 -0
  7. package/dist/chunk-BFIKVTQB.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-FF3RWDFM.js} +1 -1
  9. package/dist/chunk-GDH2D3S6.js +1 -0
  10. package/dist/chunk-J3KCHTSA.js +6 -0
  11. package/dist/{chunk-QTHFMDZY.js → chunk-JMSVHETI.js} +1 -1
  12. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  13. package/dist/chunk-MOX5FG2R.js +1 -0
  14. package/dist/chunk-YRBUHHI3.js +2 -0
  15. package/dist/chunk-ZCF6EV4Y.js +65 -0
  16. package/dist/{composite-B-F2J0NK.d.cts → composite-BoS9-74g.d.cts} +320 -4
  17. package/dist/{composite-B--rGI5m.d.ts → composite-D4_XPSas.d.ts} +91 -4
  18. package/dist/gemini-live.cjs +2 -2
  19. package/dist/gemini-live.d.cts +4 -4
  20. package/dist/gemini-live.d.ts +4 -4
  21. package/dist/gemini-live.js +1 -1
  22. package/dist/hosted/bin.cjs +44 -43
  23. package/dist/hosted/bin.js +1 -1
  24. package/dist/hosted/index.cjs +43 -42
  25. package/dist/hosted/index.d.cts +54 -10
  26. package/dist/hosted/index.d.ts +11 -5
  27. package/dist/hosted/index.js +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +4 -4
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +1 -1
  32. package/dist/pi-extension/index.cjs +7 -7
  33. package/dist/pi-extension/index.d.cts +2 -2
  34. package/dist/pi-extension/index.d.ts +2 -2
  35. package/dist/pi-extension/index.js +1 -1
  36. package/dist/pi-extension/standalone.cjs +55 -55
  37. package/dist/pooler/bin.cjs +40 -41
  38. package/dist/pooler/bin.js +39 -40
  39. package/dist/proxy/cli.cjs +54 -53
  40. package/dist/proxy/cli.js +1 -1
  41. package/dist/proxy/conformance-probe.cjs +1 -1
  42. package/dist/proxy/conformance-probe.js +1 -1
  43. package/dist/proxy/index.cjs +33 -32
  44. package/dist/proxy/index.d.cts +37 -214
  45. package/dist/proxy/index.d.ts +17 -65
  46. package/dist/proxy/index.js +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-BemK1Of5.d.ts} +1 -1
  48. package/dist/{translator-Dox25ky9.d.cts → translator-PsmsZT62.d.cts} +1 -1
  49. package/dist/{types-CHPtJx6d.d.cts → types-CxWQ84Ew.d.cts} +5 -0
  50. package/dist/{types-CHPtJx6d.d.ts → types-CxWQ84Ew.d.ts} +2 -0
  51. package/dist/{video-out-DnCKUUO2.d.cts → video-out-DPLqpGbQ.d.cts} +17 -3
  52. package/dist/{video-out-REmiQMBJ.d.ts → video-out-DkMqKSOi.d.ts} +6 -2
  53. package/package.json +2 -2
  54. package/dist/chunk-7KRHHEKZ.js +0 -1
  55. package/dist/chunk-G7CSAISC.js +0 -1
  56. package/dist/chunk-GX243AIV.js +0 -1
  57. package/dist/chunk-HBKAN6PP.js +0 -2
  58. package/dist/chunk-HPUX2H65.js +0 -6
  59. package/dist/chunk-KKCUIOL4.js +0 -1
  60. package/dist/chunk-PAAFRUQZ.js +0 -64
  61. package/dist/chunk-VVQSFACF.js +0 -23
  62. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -1,90 +1,91 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var wa=Object.create;var Yr=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var va=Object.getOwnPropertyNames;var ba=Object.getPrototypeOf,Sa=Object.prototype.hasOwnProperty;var ka=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of va(e))!Sa.call(t,o)&&o!==n&&Yr(t,o,{get:()=>e[o],enumerable:!(r=_a(e,o))||r.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?wa(ba(t)):{},ka(e||!t||!t.__esModule?Yr(n,"default",{value:t,enumerable:!0}):n,t));var xa=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,C=xa();var Jr=require("child_process"),Ee=require("fs"),Wr=nt(require("path"),1),U=nt(require("process"),1);var ne=require("@urun-sh/core");async function Xr(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}function Qr(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Zr(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function eo(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Ra="llm-resp";async function*Ea(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield eo(s);return}}}async function*qn(t,e){let n=`${Ra}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Ea(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var zt=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Zr(e,n,this.consumerId);return this.write(r),qn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Qr(e,n,r,this.consumerId);return this.write(o),qn(this.session,r)})}async writeGated(e,n){try{await Xr(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var to=0;function Ia(){return to+=1,`req_${Date.now().toString(36)}_${to.toString(36)}`}var vt=class{transport;constructor(e,n){this.transport=new zt(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Ia(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var ro="audio",jn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function oo(t,e,n=1e4){let r=new jn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(ro);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Oa(t,n);return await r.startInbound(i),r}function Oa(t,e){let n=t.stream(ro);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var no="rt-video-in",St=256e3;function Bn(t){let e=t.stream(no),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${no}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>St)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${St}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Ta=24e3,bt=480,Pa=111;async function Ca(){let t=await import("opusscript"),e=t.default??t;return new e(Ta,1,2048)}async function Yt(){let t=await import("werift"),e=await Ca();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=bt;){let d=a.subarray(l,l+bt);l+=bt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,bt);o=o+1&65535,s=s+bt>>>0;let m=new t.RtpHeader({version:2,payloadType:Pa,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(m,p);n.writeRtp(h)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r}}}async function so(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var Xt=require("@urun-sh/core"),Hn="rt-video-out";var $a="h264";function Ma(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function La(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ma(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var io="urun.videoOut.v2-ws";function ao(t){let e=t.stream(Hn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Hn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Hn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=La(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:$a,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var uo={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},rt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function lo(t){let e=t.t;if(typeof e!="string"||!(e in uo))throw new rt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(uo).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Na(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new rt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new rt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return lo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new rt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return lo(t)}function co(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Ua(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function po(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw co(e);let s=o.next();if(e!==void 0&&await Ua(s,e)==="aborted")throw s.catch(()=>{}),co(e);let i=await s;if(i.done)return;yield Na(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var fo=require("@urun-sh/core"),Gn=2;function Da(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Fa(t){let e=t?.type;return e==="response.completed"||e==="error"}function mo(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Gn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(Fa(m)&&(d=!0),Da(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof fo.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Gn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Gn&&!c){await t.evict(u,a);continue}return}})()}}var ar=require("crypto");var me=class extends Error{name="ModelPriceError"},Vn="per_million_input_tokens",Jn="per_million_output_tokens",ho="model_id,variant,unit,price_usd,effective_at,expires_at",go={per_request:!0,per_minute:!0,per_output_unit:!0},qa=5e3;function ja(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new me(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function yo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new me(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ba(t,e,n){return t===null?null:yo(t,e,n)}function Ha(t,e){if(t===Vn)return"input";if(t===Jn)return"output";if(typeof t=="string"&&Object.hasOwn(go,t))return null;throw new me(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Vn} | ${Jn}) nor a known GPU-time unit (${Object.keys(go).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Ga(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function Wn(t,e){return`${t}\0${e}`}function Va(t){if(!Array.isArray(t))throw new me(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new me(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of ho.split(","))if(!Object.hasOwn(s,l))throw new me(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Ha(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new me(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new me(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:ja(s.price_usd,o),effective_at:yo(s.effective_at,o,"effective_at"),expires_at:Ba(s.expires_at,o,"expires_at")})}return e}function wo(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,h)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let k=Ga(v,m);return"reason"in k?k:k.rate.usd===0?m==="output"&&h!==null&&n?.has(Wn(a,h))?k.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:k.rate};for(let[p,m]of o.get(a)){let h=l.get(p),v=c(h?.input,"input",m),k=c(h?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:a,variant:m,reason:v.reason});continue}if(k!==null&&"reason"in k){i.push({model_id:a,variant:m,reason:k.reason});continue}v===null||k===null||s.push({model_id:a,variant:m,pricing:{input:v.usd,output:k.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function kt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var xt={prices:[],refusals:[]};async function _o(t){let e=t.fetchImpl??fetch,n=`${Vn},${Jn}`,r=await e(`${t.catalogUrl}/model_prices?select=${ho}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(qa)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Va(await r.json())}var $o=require("crypto");var z=class extends Error{},Ja=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Wa(t){if(typeof t!="string")return!1;let e=Ja.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function Ka(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new z(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new z(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new z(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new z(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new z(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new z(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new z(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",Wa(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new z(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new z(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new z(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new z(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function ot(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function vo(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new z(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Kn(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new z(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function bo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new z(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Ka(await r.json())}function de(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Et="/partners/openrouter/models",za={chat:!0,code:!0,agent:!0,vl:!0},So={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ya(t){let e=t.toLowerCase();return Object.hasOwn(So,e)?So[e]:null}var ko={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Xa(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ko,o)?ko[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var xo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ro={2:"Llama2",3:"Llama3"};function Qa(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(xo,s))return xo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ro,i))return Ro[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Za=["context_length","max_model_len"];function eu(t){let e=Za.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function Qt(t){let e=t.map(eu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function tu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function zn(t){if(t.length===0)return null;let e=t.map(tu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Yn(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function nu(t,e){let n=e.filter(s=>de(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rt(n);let r=e.filter(s=>de(s.model_id)===t);if(r.length>0)return Rt(r);let o=Yn(t,e);return o.length>0?Rt(o):null}function Rt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ru(t),matches:t}:null}function ru(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var Me=class extends Error{name="ModelCreatedError"};function st(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new Me(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new Me(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function He(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function Zt(t,e,n){let r=nu(t,e);if(!r)return He({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Qt(s),u=st(s),a=kt(o.model_id,o.variant,n),l=Io(o,s),d=zn(s);return He({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ou=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Io(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...ou],defect:o}:{published:[],defect:o}}function Xn(t){let e=t.length>0?Rt(t):null;return e===null?{published:[],defect:null}:Io(e.row,e.matches)}function Eo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ao(t){return{input:[{type:"prompt",unit:"token",cost_usd:Eo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Eo(t.output)}]}}function su(t,e,n,r){if(e.length===0)return null;let o=Rt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||za[s.task]!==!0)return null;let u=Qt(i),a=kt(s.model_id,s.variant,n),l=Qa(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:st(i),quantization:Ya(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:Ao(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:Ao(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Oo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?ot(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Xa(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=su(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Mo="https://api.urun.sh/v1",F=class extends Error{},j=class extends Error{},Zn="urs1.";function It(t,e){return Zn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ot(t){if(!t.startsWith(Zn))return null;try{let e=JSON.parse(Buffer.from(t.slice(Zn.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Lo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function To(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=lu(t);return e===null?[]:[e]}function iu(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var Ra=Object.create;var to=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Aa=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,Oa=Object.prototype.hasOwnProperty;var Ta=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Aa(e))!Oa.call(t,o)&&o!==n&&to(t,o,{get:()=>e[o],enumerable:!(r=Ea(e,o))||r.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?Ra(Ia(t)):{},Ta(e||!t||!t.__esModule?to(n,"default",{value:t,enumerable:!0}):n,t));var Pa=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,C=Pa();var Xr=require("child_process"),Ae=require("fs"),Qr=nt(require("path"),1),F=nt(require("process"),1);var re=require("@urun-sh/core");async function no(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}function ro(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function oo(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function so(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var io=require("@urun-sh/core/internal");function ao(t,e){let n=t.delete;if(typeof n=="function"){(0,io.gcRequest)({get:r=>t.get(r),delete:r=>n.call(t,r),on:(r,o)=>t.on(r,o)},e);return}t.set({requests:{[e]:null}})}var Ca="llm-resp";async function*Ma(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield so(s);return}}}async function*Hn(t,e){let n=`${Ca}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Ma(e,t.stream(n).messages())}finally{try{ao(t.doc("llm"),e)}catch{}}}var Xt=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=oo(e,n,this.consumerId);return this.write(r),Hn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=ro(e,n,r,this.consumerId);return this.write(o),Hn(this.session,r)})}async writeGated(e,n){try{await no(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var uo=0;function La(){return uo+=1,`req_${Date.now().toString(36)}_${uo.toString(36)}`}var vt=class{transport;constructor(e,n){this.transport=new Xt(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=La(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var co="audio",Gn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function po(t,e,n=1e4){try{return await Na(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Na(t,e,n){let r=new Gn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(co);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ua(t,n);return await r.startInbound(i),r}function Ua(t,e){let n=t.stream(co);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var lo="rt-video-in",St=256e3;function Jn(t){let e=t.stream(lo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${lo}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>St)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${St}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Da=24e3,bt=480,Fa=111,qa=50,Qt=null;async function Ba(){if(Qt)return;let t=await import("opusscript");Qt=t.default??t}function ja(){if(!Qt)throw new Error("[opus-guard] opusscript module not loaded");return new Qt(Da,1,2048)}var Vn=class{constructor(e=ja){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=qa}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function Zt(){let t=await import("werift");await Ba();let e=new Vn;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=bt;){let d=a.subarray(l,l+bt);l+=bt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,bt);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+bt>>>0;let m=new t.RtpHeader({version:2,payloadType:Fa,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(m,p);n.writeRtp(g)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch(a){if(e.wedged)throw a;return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function fo(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var en=require("@urun-sh/core"),Wn="rt-video-out";var Ha="h264";function Ga(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function Va(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ga(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var mo="urun.videoOut.v2-ws";function go(t){let e=t.stream(Wn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Wn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Wn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Va(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:Ha,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var ho={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},rt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function yo(t){let e=t.t;if(typeof e!="string"||!(e in ho))throw new rt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ho).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Ja(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new rt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new rt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return yo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new rt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return yo(t)}function wo(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Wa(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function _o(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw wo(e);let s=o.next();if(e!==void 0&&await Wa(s,e)==="aborted")throw s.catch(()=>{}),wo(e);let i=await s;if(i.done)return;yield Ja(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var vo=require("@urun-sh/core"),Kn=2;function Ka(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function za(t){let e=t?.type;return e==="response.completed"||e==="error"}function bo(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Kn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(za(m)&&(d=!0),Ka(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof vo.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Kn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Kn&&!c){await t.evict(u,a);continue}return}})()}}var pr=require("crypto");var ge=class extends Error{name="ModelPriceError"},zn="per_million_input_tokens",Yn="per_million_output_tokens",ko="model_id,variant,unit,price_usd,effective_at,expires_at",So={per_request:!0,per_minute:!0,per_output_unit:!0},Ya=5e3;function Xa(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ge(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function xo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ge(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Qa(t,e,n){return t===null?null:xo(t,e,n)}function Za(t,e){if(t===zn)return"input";if(t===Yn)return"output";if(typeof t=="string"&&Object.hasOwn(So,t))return null;throw new ge(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${zn} | ${Yn}) nor a known GPU-time unit (${Object.keys(So).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function eu(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function Xn(t,e){return`${t}\0${e}`}function tu(t){if(!Array.isArray(t))throw new ge(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ge(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of ko.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Za(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new ge(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new ge(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:Xa(s.price_usd,o),effective_at:xo(s.effective_at,o,"effective_at"),expires_at:Qa(s.expires_at,o,"expires_at")})}return e}function Ro(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,g)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let x=eu(v,m);return"reason"in x?x:x.rate.usd===0?m==="output"&&g!==null&&n?.has(Xn(a,g))?x.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:x.rate};for(let[p,m]of o.get(a)){let g=l.get(p),v=c(g?.input,"input",m),x=c(g?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:a,variant:m,reason:v.reason});continue}if(x!==null&&"reason"in x){i.push({model_id:a,variant:m,reason:x.reason});continue}v===null||x===null||s.push({model_id:a,variant:m,pricing:{input:v.usd,output:x.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function kt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var xt={prices:[],refusals:[]};async function Eo(t){let e=t.fetchImpl??fetch,n=`${zn},${Yn}`,r=await e(`${t.catalogUrl}/model_prices?select=${ko}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Ya)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return tu(await r.json())}var qo=require("crypto");var X=class extends Error{},nu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ru(t){if(typeof t!="string")return!1;let e=nu.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function ou(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new X(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new X(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new X(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new X(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new X(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new X(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new X(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",ru(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new X(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new X(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new X(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new X(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function ot(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Ao(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new X(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Qn(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new X(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function Io(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new X(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ou(await r.json())}function ce(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Et="/partners/openrouter/models",su={chat:!0,code:!0,agent:!0,vl:!0},Oo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function iu(t){let e=t.toLowerCase();return Object.hasOwn(Oo,e)?Oo[e]:null}var To={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function au(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(To,o)?To[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Po={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Co={2:"Llama2",3:"Llama3"};function uu(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(Po,s))return Po[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Co,i))return Co[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var lu=["context_length","max_model_len"];function du(t){let e=lu.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function tn(t){let e=t.map(du),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function cu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Zn(t){if(t.length===0)return null;let e=t.map(cu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function er(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function pu(t,e){let n=e.filter(s=>ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rt(n);let r=e.filter(s=>ce(s.model_id)===t);if(r.length>0)return Rt(r);let o=er(t,e);return o.length>0?Rt(o):null}function Rt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:fu(t),matches:t}:null}function fu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var $e=class extends Error{name="ModelCreatedError"};function st(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new $e(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new $e(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new $e(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new $e(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function He(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function nn(t,e,n){let r=pu(t,e);if(!r)return He({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=tn(s),u=st(s),a=kt(o.model_id,o.variant,n),l=Lo(o,s),d=Zn(s);return He({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var mu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Lo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...mu],defect:o}:{published:[],defect:o}}function tr(t){let e=t.length>0?Rt(t):null;return e===null?{published:[],defect:null}:Lo(e.row,e.matches)}function Mo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function $o(t){return{input:[{type:"prompt",unit:"token",cost_usd:Mo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Mo(t.output)}]}}function gu(t,e,n,r){if(e.length===0)return null;let o=Rt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||su[s.task]!==!0)return null;let u=tn(i),a=kt(s.model_id,s.variant,n),l=uu(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:st(i),quantization:iu(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:$o(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:$o(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function No(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?ot(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:au(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=gu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Bo="https://api.urun.sh/v1",G=class extends Error{},V=class extends Error{},rr="urs1.";function Ot(t,e){return rr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Tt(t){if(!t.startsWith(rr))return null;try{let e=JSON.parse(Buffer.from(t.slice(rr.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function jo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Uo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=_u(t);return e===null?[]:[e]}function hu(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let u=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(u)||u<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
- `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function au(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||de(`${r.model_id}-${r.variant}`)===e.appSlug||de(r.model_id)===e.appSlug)),n?iu(n.engine_args?.pool):null}function Qn(t,e,n,r,o){if(!o)throw new z(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new z(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new z(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Po(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new z(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var No="shared:",Co="speech:",tr="realtime:";function Ne(t){return t.sharedApp?No+t.appSlug:t.appSlug}function tn(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function er(t,e){let n=e.filter(s=>de(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>de(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function uu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function lu(t){let e=t.map(uu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var du={stt:"stt",tts:"tts"};function Le(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:du[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Uo(t,e){let n=er(t,e);return n.length>0?n:Yn(t,e)}function At(t,e){return Uo(t.appSlug,e)}function cu(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new z(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var en=6e4,nn=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??en):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??en):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??en):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??en;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof me)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
- `),xt}let r=wo(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
6
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Wn(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(No)||o.startsWith(Co)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new F(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Kn(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,u=de(s),a=n.endpoints.filter(c=>de(c.model_id)===u&&(i===void 0||c.variant===i)),l=new Set(a.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:Kn(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=de(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),u=this.servable(i);if(u.includes(o))return{appSlug:o};let a=u.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new F(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new F(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let u=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===de(a.model_id)||o===de(`${a.model_id}-${a.variant}`));if(u)throw new F(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${u.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=tn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return au(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ne(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ne(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Co+Ne(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,tr+(0,$o.randomUUID)())}async evictHandle(e){let n=Ot(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:tn(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:It(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:It(n,this.keyOf(r))}}async sessionForHandle(e){let n=Ot(e);if(!n)throw new j(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(u=>u,()=>null):null;if(i===null)throw new j(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o&&this.mintedIds.get(i)!==o)throw new j(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:xt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
7
- `);let a=(n?ot(n):[]).map(l=>{let d=s.filter(b=>b.model_id===l.model_id&&b.variant===l.variant),c=Qt(d),p=st(d),m=zn(d),h=kt(l.model_id,l.variant,i),v=Xn(d);return He({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>Zt(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Oo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=Qn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Po(`${r.modelId}:${r.variant}`,s).includes(n)}return To(er(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Le(At(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Le(At(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Le(At(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):At(n,r);return cu(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):At(n,r);return Xn(o)}async imageModelList(){let e=await this.catalogRows(),n=xt,r=[];for(let s of await this.availableIds()){let i=To(er(s,e));i.length!==0&&r.push(He({...Zt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=Qn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Po(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=He({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=xt,r=[];for(let s of await this.availableIds())Le(Uo(s,e))==="stt"&&r.push(Zt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=Qn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Le(i)!=="stt")continue;let u=He({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Ue=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Tt=class extends Ue{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},nr=class extends Ue{constructor(e,n=!1){super("acquire_timeout",429,30,n?"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")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},rn=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 n={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(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.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(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.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 n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Tt;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new Tt;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand();continue}let a=r+n-Date.now();if(a<=0)throw new nr(n,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,a)})])}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 Tt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&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 n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!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 n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){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,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.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,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var rr=require("@urun-sh/core"),ve=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},sn=33e4;function Do(t,e=sn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new on),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof j||l instanceof rr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof on?(await r.return?.(void 0),new ve("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 ve("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var on=class extends Error{constructor(){super("stream idle timeout")}};function Fo(t){return t instanceof ve?!1:t instanceof j?!0:t instanceof rr.SessionFailedError?t.kind==="transport-failed":!1}var qo=require("@urun-sh/core"),pu="audio";function jo(t){let e=t.streamEndpoint(pu);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,qo.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var Bo=require("@urun-sh/core"),fu="rt-video-in";function Ho(t){let e=t.streamEndpoint(fu);return{sendInputFrame:async n=>{e.send((0,Bo.encodeStreamEnvelope)(n))}}}var mu=3,gu="llm",hu=new Set(["paused","error"]);function Go(t,e,n){let r=t.doc(gu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<mu||d(new j(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&hu.has(c.name)&&d(new j(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*or(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var wu=0,_u=4,vu=4;function Vo(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):wu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,_u));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",vu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Jo(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return sn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function sr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Wo(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new vt(v),gone:Go(v,n)});if(i.lane==="jwt"){let v=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(sr(v,e.appSlug,u,l))}if(i.lane==="machine"){let{machineToken:v,gatewayUrl:k}=i,b=(typeof t.subject=="function"?t.subject():t.subject)??(0,ar.randomUUID)(),w=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ne.createClientToken)(v,{baseUrl:k,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:b,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(sr(w,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,ar.randomUUID)(),h=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ne.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(sr(h,e.appSlug,u,l))}function Ko(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function ur(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var bu=new Set(["error","paused"]);function zo(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=Wo(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new nn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Lo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>so(n):null),listPrices:n?()=>_o(n):null,shared:e.lane==="api-key"?()=>bo({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return vo(i)}:null,sessionKey:Ko});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ne({appSlug:t.defaultApp}))),s}function Yo(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
8
- `)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new rn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let v=Wo(t,d,c,{concurrencyKey:h.concurrencyKey});return v.gone.onGone(()=>m.markSessionDead(v)),await un(v.session),u(`slot attached pool=${c} slot=${h.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,v)=>u(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${v}`),terminalOpenFailure:h=>h instanceof ne.SessionFailedError&&ur(h)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ne(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ne(c),m=a(c,p);await l(c,p);let h=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(h.entry)??[];return v.push(h),i.set(h.entry,v),{app:p,entry:h.entry,identity:tn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ne(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Su(t){return(0,ne.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ne.DEFAULT_WHEN_LIVE_TIMEOUT_MS:ne.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:ne.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function un(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Su(t.phase),signal:e})}async function ir(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function an(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Xo(t,e=Yt,n,r,o=sn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",m=f=>{let g=Ot(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new j(`the lane behind this handle (${g.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:g.key,entry:y}},h=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await un(f.session,y.gone.signal),y.gone.signal.aborted)throw an(y.gone.signal);d.get(f)===y&&d.delete(f);let _=await oo(f.session,await e());return Object.assign(_,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},k=f=>{let g=l.get(f);return g||(g=(async()=>{let y=await v(f);return{appendInputAudio:_=>y.appendInputAudio(_),onOutputAudio:_=>y.onOutputAudio(_),sessionId:c(f)}})(),l.set(f,g),g.catch(()=>{l.get(f)===g&&l.delete(f)})),g},b=async(f,g,y)=>{if(y?.aborted){let R=d.get(f);throw(i.get(f)===void 0||R!==void 0&&R.waiting===0)&&await ir(f.session),an(y)}let _=g(f),S=d.get(f);return S!==void 0&&S.waiting++,y===void 0?_:new Promise((R,I)=>{let E=()=>{S!==void 0&&--S.waiting===0&&d.get(f)===S&&(S.gone.abort(),d.delete(f),i.delete(f),l.delete(f),ir(f.session).catch(()=>{})),I(an(y))};y.addEventListener("abort",E,{once:!0});let O=()=>y.removeEventListener("abort",E);_.then(x=>{O(),R(x)},x=>{O(),I(x)})})},w=async(f,g,y)=>{try{return await y}catch(_){throw(_ instanceof j||_ instanceof ne.SessionFailedError&&ur(_))&&(t.evict(f,g),_ instanceof ne.SessionFailedError&&n?.(f,_.kind==="never-live"?"never-live":"create-failed")),_}};return{createResponse:mo({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{ur(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await un(f.session);let y=Do(or(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let _=f;return(async function*(){try{yield*y}catch(R){throw Fo(R)&&(s&&s.owns(_)?s.evict(_):r&&(R instanceof j?r.markSessionDead(_):r.evict(_))),R}finally{s&&s.owns(_)?s.release(_):r?.end(_)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,g)=>{let{app:y,entry:_}=await t.sessionFor(f);return await w(y,_,b(_,v,g))},openAudioOn:async(f,g,y)=>{let _=m(f);if(_){let I=_.entry.session;return jo(I)}let{app:S,entry:R}=await t.sessionForHandle(f);return await w(S,R,b(R,k,g))},openTurnsOn:async function*(f,g){if(g?.aborted)throw an(g);let y=await h(f);yield*po(y.session,g)},openVideoOn:async f=>{let g=m(f);if(g)return Ho(g.entry.session);let{entry:y}=await t.sessionForHandle(f),_=u.get(y);return _||(_=Bn(y.session),u.set(y,_)),_},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=u.get(g);return y||(y=Bn(g.session),u.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=ao(g.session),a.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),_=c(y.entry);if(_===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return It(p,_)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:_}=await t.dedicatedSessionFor(f);return It(y,Ko(_))},releaseSessionHandle:f=>{let g=Ot(f);if(!g)return;if(g.app.startsWith(tr)){(async()=>{let _=null;try{_=(await t.sessionForHandle(f)).entry}catch{return}await ir(_.session).catch(()=>{}),await t.evict(g.app,_)})();return}if(!s||g.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let _=await h(f);await un(_.session);let S=y!==void 0&&m(f)?new vt({..._.session,consumerId:y},{sessionTag:y}):_.responses;return or(await S.responses.create(g),_.gone)},onSessionEnd:async(f,g)=>{let y=m(f);if(y)return y.entry.gone.onGone(I=>g({timeLeftMs:null,reason:I.message}));let{entry:_}=await t.sessionForHandle(f),S=_.session;if(typeof S.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let R=!1;return S.onPhase(I=>{if(R||!bu.has(I.name))return;R=!0;let E=S.endsAt??null;g({timeLeftMs:E?Math.max(0,E.getTime()-Date.now()):null,reason:I.reason??`session ${I.name}`})})}}}var aa=require("http");var hs=require("crypto"),ys=require("ws");var Zo="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ku=1007,es=1008,Te=1011,pn=1008,A=class extends Error{constructor(n,r=ku){super(n);this.closeCode=r}closeCode},te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,ln=["setup","clientContent","realtimeInput","toolResponse"];function ts(t){let e;try{e=JSON.parse(t)}catch{throw new A("client message is not valid JSON")}let n=te(e);if(!n)throw new A("client message must be a JSON object");let r=ln.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!ln.includes(u));if(o.length>0)throw new A(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${ln.join(", ")}`);if(r.length!==1)throw new A(`client message must contain exactly one of ${ln.join(", ")} (got ${r.length})`);let s=r[0],i=te(n[s]);if(!i)throw new A(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ns(t,e){if(typeof t=="string")return t;let n=te(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new A(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=te(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new A(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new A(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new A(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
9
- `)}var xu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ve="urun.videoOut";function rs(t){return{framing:io,codec:t}}function os(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ve]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ru={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Eu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ve],Qo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Au(t){let e=te(t);if(!e)throw new A("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new A(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=te(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new A("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new A(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new A("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Qo.includes(e.activityHandling))throw new A(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Qo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Iu=["temperature","maxOutputTokens","responseModalities"];function ss(t){for(let[c,p]of Object.entries(Ru))if(t[c]!==void 0)throw new A(p);for(let c of Object.keys(t))if(!Eu.includes(c))throw new A(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new A('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=te(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new A("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Iu.includes(c))throw new A(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new A("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new A("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new A(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:ns(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new A("setup.tools must be an array");u=[];for(let c of t.tools){let p=te(c);if(!p)throw new A("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new A(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new A("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let h=te(m);if(!h||typeof h.name!="string")throw new A("functionDeclarations entries require a string name");u.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=te(t.sessionResumption);if(!c)throw new A("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new A(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new A("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?xu:Au(t.realtimeInputConfig),d=!1;if(t[Ve]!==void 0){if(!te(t[Ve]))throw new A(`setup["${Ve}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function is(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function as(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function us(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new A(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new A("clientContent.turns must be an array");let n=[];for(let r of e){let o=te(r);if(!o)throw new A("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new A(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:ns(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var dn=16e3,ls=24e3,Ou=`audio/pcm;rate=${ls}`,ds=Buffer.alloc(960).toString("base64");function Tu(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Pu(t){let e=te(t);if(!e)throw new A("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new A("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Cu(t){let e=te(t);if(!e)throw new A("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==dn)throw new A(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${dn} Hz (audio/pcm;rate=${dn})`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new A(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Tu(o,dn,ls);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function cs(t){if(t.mediaChunks!==void 0)throw new A('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new A("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=te(t[o]);if(!s||Object.keys(s).length!==0)throw new A(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new A(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new A(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Cu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Pu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new A("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new A("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ps(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new A(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new A("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=te(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new A("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function fs(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ms(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ou,data:t}}]}}}}function gs(t){let e=te(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=te(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=te(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=te(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new A(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Te);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new A(`upstream function_call arguments are not valid JSON: ${c}`,Te)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=te(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var $u=256,lr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>$u;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Mu="local",Pt=t=>t.slice(0,120),dr=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof F){this.ws.close(es,Pt(e.message));return}if(e instanceof j){this.ws.close(pn,Pt(e.message));return}if(e instanceof A){this.ws.close(e.closeCode,Pt(e.message));return}this.ws.close(Te,Pt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=ts(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new A(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=us(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=cs(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:ds);return}this.transcript.push(...ps(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new A("setup may only be sent once, as the first client message");let n=ss(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new A("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",pn);if(s.model!==n.model)throw new A(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new A("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new A(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,pn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),u=i.onOutputFrame(l=>this.send(os(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[Ve]=rs(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new A("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new A("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Te);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ms(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new A("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new A("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Te);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new A(`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 A("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new A("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,hs.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(is(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(as(e.timeLeftMs)),this.ws.close(Te,Pt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new A(`upstream error: ${JSON.stringify(l)}`,Te);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=fs(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new A("upstream produced no response.completed event",Te);let{messages:i,assistantItems:u}=gs(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Je=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Lu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Je(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new Je(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 u;for(let a of r)u=a;if(u===void 0&&n)throw new Je(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function ws(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ys.WebSocketServer({noServer:!0}),o=new lr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Zo&&(u.on("error",()=>{}),(async()=>{let d=Lu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Je(401,"invalid local proxy api key");c={clients:e.clients,scope:Mu}}r.handleUpgrade(i,u,a,p=>{new dr(p,c,o)})})().catch(d=>{let c=502;(d instanceof Je||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",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
4
+ `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function yu(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||ce(`${r.model_id}-${r.variant}`)===e.appSlug||ce(r.model_id)===e.appSlug)),n?hu(n.engine_args?.pool):null}function nr(t,e,n,r,o){if(!o)throw new X(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new X(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new X(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Do(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new X(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Ho="shared:",Fo="speech:",sr="realtime:";function Ne(t){return t.sharedApp?Ho+t.appSlug:t.appSlug}function It(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function or(t,e){let n=e.filter(s=>ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>ce(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function wu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function _u(t){let e=t.map(wu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var vu={stt:"stt",tts:"tts"};function Le(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:vu[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Go(t,e){let n=or(t,e);return n.length>0?n:er(t,e)}function At(t,e){return Go(t.appSlug,e)}function bu(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new X(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var rn=6e4,on=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??rn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??rn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??rn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??rn;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ge)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
+ `),xt}let r=Ro(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
6
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Xn(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Ho)||o.startsWith(Fo)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new G(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Qn(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,u=ce(s),a=n.endpoints.filter(c=>ce(c.model_id)===u&&(i===void 0||c.variant===i)),l=new Set(a.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:Qn(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=ce(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),u=this.servable(i);if(u.includes(o))return{appSlug:o};let a=u.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new G(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new G(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let u=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===ce(a.model_id)||o===ce(`${a.model_id}-${a.variant}`));if(u)throw new G(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${u.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=It(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return yu(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ne(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ne(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return It(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Fo+Ne(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,sr+(0,qo.randomUUID)())}async evictHandle(e){let n=Tt(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:It(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Ot(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Ot(n,this.keyOf(r))}}async sessionForHandle(e){let n=Tt(e);if(!n)throw new V(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(u=>u,()=>null):null;if(i===null)throw new V(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o&&this.mintedIds.get(i)!==o)throw new V(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:xt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
7
+ `);let a=(n?ot(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=tn(d),p=st(d),m=Zn(d),g=kt(l.model_id,l.variant,i),v=tr(d);return He({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>nn(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return No(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=nr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Do(`${r.modelId}:${r.variant}`,s).includes(n)}return Uo(or(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Le(At(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Le(At(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Le(At(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):At(n,r);return bu(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):At(n,r);return tr(o)}async imageModelList(){let e=await this.catalogRows(),n=xt,r=[];for(let s of await this.availableIds()){let i=Uo(or(s,e));i.length!==0&&r.push(He({...nn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=nr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Do(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=He({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=xt,r=[];for(let s of await this.availableIds())Le(Go(s,e))==="stt"&&r.push(nn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=nr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Le(i)!=="stt")continue;let u=He({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Ue=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Pt=class extends Ue{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},ir=class extends Ue{constructor(e,n=!1){super("acquire_timeout",429,30,n?"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")}},ve=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},sn=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 n={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(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.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(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.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 n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Pt;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new Pt;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand();continue}let a=r+n-Date.now();if(a<=0)throw new ir(n,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,a)})])}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 Pt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&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 n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!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 n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){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,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.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,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var ar=require("@urun-sh/core"),be=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},un=33e4;function Vo(t,e=un){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new an),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof V||l instanceof ar.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof an?(await r.return?.(void 0),new be("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 be("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new be("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var an=class extends Error{constructor(){super("stream idle timeout")}};function Jo(t){return t instanceof be?!1:t instanceof V?!0:t instanceof ar.SessionFailedError?t.kind==="transport-failed":!1}var ur=require("@urun-sh/core"),Su="audio";function Wo(t){let e=t.streamEndpoint(Su);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,ur.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,ur.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var Ko=require("@urun-sh/core"),ku="rt-video-in";function zo(t){let e=t.streamEndpoint(ku);return{sendInputFrame:async n=>{e.send((0,Ko.encodeStreamEnvelope)(n))}}}var xu=3,Ru="llm",Eu=new Set(["paused","error"]);function Yo(t,e,n){let r=t.doc(Ru),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<xu||d(new V(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Eu.has(c.name)&&d(new V(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*lr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Iu=0,Ou=4,Tu=4;function Xo(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Iu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Ou));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Tu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Qo(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return un;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function dr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Zo(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new vt(v),gone:Yo(v,n)});if(i.lane==="jwt"){let v=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(dr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:x}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,pr.randomUUID)(),w=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,re.createClientToken)(v,{baseUrl:x,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(dr(w,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,pr.randomUUID)(),g=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,re.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(dr(g,e.appSlug,u,l))}function es(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function fr(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Pu=new Set(["error","paused"]);function ts(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=Zo(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new on({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>jo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>fo(n):null),listPrices:n?()=>Eo(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return Ao(i)}:e.lane==="api-key"?()=>Io({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:es});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ne({appSlug:t.defaultApp}))),s}function ns(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
8
+ `)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new sn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let v=Zo(t,d,c,{concurrencyKey:g.concurrencyKey});return v.gone.onGone(()=>m.markSessionDead(v)),await dn(v.session),u(`slot attached pool=${c} slot=${g.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async g=>{g.gone.dispose(),g.audioDispose?.(),await g.session.end()},onDetach:(g,v)=>u(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${v}`),terminalOpenFailure:g=>g instanceof re.SessionFailedError&&fr(g)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ne(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ne(c),m=a(c,p);await l(c,p);let g=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(g.entry)??[];return v.push(g),i.set(g.entry,v),{app:p,entry:g.entry,identity:It(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ne(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Cu(t){return(0,re.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?re.DEFAULT_WHEN_LIVE_TIMEOUT_MS:re.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:re.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function dn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Cu(t.phase),signal:e})}async function cr(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function ln(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function rs(t,e=Zt,n,r,o=un,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let h=f.session.id;return typeof h=="string"&&h.length>0?h:null},p="lane",m=f=>{let h=Tt(f);if(!s||!h||h.app!==p)return null;let y=s.entryFor(h.key);if(!y)throw new V(`the lane behind this handle (${h.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:h.key,entry:y}},g=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let h=i.get(f);if(!h){let y={waiting:0,gone:new AbortController};d.set(f,y),h=(async()=>{if(await dn(f.session,y.gone.signal),y.gone.signal.aborted)throw ln(y.gone.signal);d.get(f)===y&&d.delete(f);let b=await po(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,h),h.then(b=>{i.get(f)===h&&(f.audioDispose=()=>b.dispose())},()=>{}),h.catch(()=>{i.get(f)===h&&i.delete(f)}),h.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return h},x=f=>{let h=l.get(f);return h||(h=(async()=>{let y=await v(f);return{appendInputAudio:(b,R)=>y.appendInputAudio(b,R),onOutputAudio:b=>y.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,h),h.catch(()=>{l.get(f)===h&&l.delete(f)})),h},S=async(f,h,y)=>{if(y?.aborted){let A=d.get(f);throw(i.get(f)===void 0||A!==void 0&&A.waiting===0)&&await cr(f.session),ln(y)}let b=h(f),R=d.get(f);return R!==void 0&&R.waiting++,y===void 0?b:new Promise((A,O)=>{let _=()=>{R!==void 0&&--R.waiting===0&&d.get(f)===R&&(R.gone.abort(),d.delete(f),i.delete(f),l.delete(f),cr(f.session).catch(()=>{})),O(ln(y))};y.addEventListener("abort",_,{once:!0});let E=()=>y.removeEventListener("abort",_);b.then(k=>{E(),A(k)},k=>{E(),O(k)})})},w=async(f,h,y)=>{try{return await y}catch(b){throw(b instanceof V||b instanceof re.SessionFailedError&&fr(b))&&(t.evict(f,h),b instanceof re.SessionFailedError&&n?.(f,b.kind==="never-live"?"never-live":"create-failed")),b}};return{createResponse:bo({sessionFor:s?async f=>{let h=await t.resolveTargetFor(f);if(h.sharedApp){let y=await s.sessionFor(f,h);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,h)=>{s&&s.owns(h)?s.evict(h):r?r.evict(h):t.evict(f,h)},onAdmissionVerdict:(f,h,y)=>{fr(y)&&(s&&s.owns(h)?s.evict(h):r?r.markSessionDead(h):t.evict(f,h),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,h)=>{try{await dn(f.session);let y=Vo(lr(await f.responses.responses.create(h),f.gone),o);if(!r&&!s)return y;let b=f;return(async function*(){try{yield*y}catch(A){throw Jo(A)&&(s&&s.owns(b)?s.evict(b):r&&(A instanceof V?r.markSessionDead(b):r.evict(b))),A}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,h)=>t.supportsImages(f,h),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,h)=>{let{app:y,entry:b}=await t.sessionFor(f);return await w(y,b,S(b,v,h))},openAudioOn:async(f,h,y,b)=>{let R=m(f);if(R){let _=R.entry.session;return Wo(_)}let{app:A,entry:O}=await t.sessionForHandle(f);if(b&&O.session.phase?.name!=="live"){let _=O.session.phase?.name;b({status:_==="queued"||_==="waiting_for_capacity"?_:"pending",reason:`the dial's session is ${_??"not yet admitted"} \u2014 the connection waits for admission`})}return await w(A,O,S(O,x,h))},openTurnsOn:async function*(f,h){if(h?.aborted)throw ln(h);let y=await g(f);yield*_o(y.session,h)},openVideoOn:async f=>{let h=m(f);if(h)return zo(h.entry.session);let{entry:y}=await t.sessionForHandle(f),b=u.get(y);return b||(b=Jn(y.session),u.set(y,b)),b},openVideo:async f=>{let{entry:h}=await t.sessionFor(f),y=u.get(h);return y||(y=Jn(h.session),u.set(h,y)),y},openVideoOut:async f=>{let{entry:h}=await t.sessionFor(f),y=a.get(h);return y||(y=go(h.session),a.set(h,y)),y},sessionHandle:async f=>{if(s){let h=await t.resolveTargetFor(f);if(h.sharedApp){let y=await s.sessionFor(f,h),b=c(y.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Ot(p,b)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:b}=await t.dedicatedSessionFor(f);return Ot(y,es(b))},releaseSessionHandle:f=>{let h=Tt(f);if(!h)return;if(h.app.startsWith(sr)){(async()=>{let b=null;try{b=(await t.sessionForHandle(f)).entry}catch{return}await cr(b.session).catch(()=>{}),await t.evict(h.app,b)})();return}if(!s||h.app!==p)return;let y=s.entryFor(h.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:h,entry:y}=await t.sessionForHandle(f);await t.evict(h,y)},createResponseOn:async(f,h,y)=>{let b=await g(f);await dn(b.session);let R=y!==void 0&&m(f)?new vt({...b.session,consumerId:y},{sessionTag:y}):b.responses;return lr(await R.responses.create(h),b.gone)},onSessionEnd:async(f,h)=>{let y=m(f);if(y)return y.entry.gone.onGone(O=>h({timeLeftMs:null,reason:O.message}));let{entry:b}=await t.sessionForHandle(f),R=b.session;if(typeof R.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let A=!1;return R.onPhase(O=>{if(A||!Pu.has(O.name))return;A=!0;let _=R.endsAt??null;h({timeLeftMs:_?Math.max(0,_.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}var ma=require("http");var Ss=require("crypto"),ks=require("ws");var ss="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Mu=1007,is=1008,Pe=1011,mn=1008,I=class extends Error{constructor(n,r=Mu){super(n);this.closeCode=r}closeCode},te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,cn=["setup","clientContent","realtimeInput","toolResponse"];function as(t){let e;try{e=JSON.parse(t)}catch{throw new I("client message is not valid JSON")}let n=te(e);if(!n)throw new I("client message must be a JSON object");let r=cn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!cn.includes(u));if(o.length>0)throw new I(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${cn.join(", ")}`);if(r.length!==1)throw new I(`client message must contain exactly one of ${cn.join(", ")} (got ${r.length})`);let s=r[0],i=te(n[s]);if(!i)throw new I(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function us(t,e){if(typeof t=="string")return t;let n=te(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new I(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=te(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new I(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new I(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new I(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
9
+ `)}var $u={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ve="urun.videoOut";function ls(t){return{framing:mo,codec:t}}function ds(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ve]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Lu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Nu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ve],os=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Uu(t){let e=te(t);if(!e)throw new I("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new I(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=te(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new I("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new I(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new I("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!os.includes(e.activityHandling))throw new I(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${os.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Du=["temperature","maxOutputTokens","responseModalities"];function cs(t){for(let[c,p]of Object.entries(Lu))if(t[c]!==void 0)throw new I(p);for(let c of Object.keys(t))if(!Nu.includes(c))throw new I(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new I('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=te(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new I("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Du.includes(c))throw new I(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new I("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new I("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new I(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:us(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new I("setup.tools must be an array");u=[];for(let c of t.tools){let p=te(c);if(!p)throw new I("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new I(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new I("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=te(m);if(!g||typeof g.name!="string")throw new I("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=te(t.sessionResumption);if(!c)throw new I("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new I(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new I("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?$u:Uu(t.realtimeInputConfig),d=!1;if(t[Ve]!==void 0){if(!te(t[Ve]))throw new I(`setup["${Ve}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function ps(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function fs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ms(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new I(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new I("clientContent.turns must be an array");let n=[];for(let r of e){let o=te(r);if(!o)throw new I("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new I(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:us(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var pn=16e3,gs=24e3,Fu=`audio/pcm;rate=${gs}`,hs=Buffer.alloc(960).toString("base64");function qu(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Bu(t){let e=te(t);if(!e)throw new I("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new I("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ju(t){let e=te(t);if(!e)throw new I("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==pn)throw new I(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${pn} Hz (audio/pcm;rate=${pn})`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new I(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=qu(o,pn,gs);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function ys(t){if(t.mediaChunks!==void 0)throw new I('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new I("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=te(t[o]);if(!s||Object.keys(s).length!==0)throw new I(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new I(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new I(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ju(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Bu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new I("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new I("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ws(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new I(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new I("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=te(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new I("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function _s(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function vs(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Fu,data:t}}]}}}}function bs(t){let e=te(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=te(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=te(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=te(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new I(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Pe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new I(`upstream function_call arguments are not valid JSON: ${c}`,Pe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=te(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var Hu=256,mr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Hu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Gu="local",Ct=t=>t.slice(0,120),gr=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof G){this.ws.close(is,Ct(e.message));return}if(e instanceof V){this.ws.close(mn,Ct(e.message));return}if(e instanceof I){this.ws.close(e.closeCode,Ct(e.message));return}this.ws.close(Pe,Ct(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=as(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new I(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=ms(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=ys(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:hs);return}this.transcript.push(...ws(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new I("setup may only be sent once, as the first client message");let n=cs(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new I("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",mn);if(s.model!==n.model)throw new I(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new I("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new I(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,mn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),u=i.onOutputFrame(l=>this.send(ds(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[Ve]=ls(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new I("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new I("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Pe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(vs(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new I("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new I("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Pe);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new I(`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 I("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new I("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Ss.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ps(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(fs(e.timeLeftMs)),this.ws.close(Pe,Ct(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new I(`upstream error: ${JSON.stringify(l)}`,Pe);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=_s(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new I("upstream produced no response.completed event",Pe);let{messages:i,assistantItems:u}=bs(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Je=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Vu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Je(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new Je(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 u;for(let a of r)u=a;if(u===void 0&&n)throw new Je(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function xs(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ks.WebSocketServer({noServer:!0}),o=new mr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===ss&&(u.on("error",()=>{}),(async()=>{let d=Vu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Je(401,"invalid local proxy api key");c={clients:e.clients,scope:Gu}}r.handleUpgrade(i,u,a,p=>{new gr(p,c,o)})})().catch(d=>{let c=502;(d instanceof Je||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",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
10
10
  Connection: close\r
11
11
  \r
12
12
  ${m}\r
13
- `),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Fe=require("ws");var _s=require("crypto"),vs="Inference-Id";function Ct(){return(0,_s.randomUUID)()}function cr(t){return t==="/v1"||t.startsWith("/v1/")}function bs(t,e){if(!cr(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function $t(t){return`resp_${t}`}function Ss(t){return`chatcmpl-${t}`}function ks(t){return`msg_${t}`}function ge(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function xs(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Rs(t){return`${JSON.stringify(t)}
14
- `}var Nu=256,Uu=128;function ae(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Uu)}var We=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Nu?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=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(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Du=256;function Fu(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Ke=class extends Error{},it=class{conversations=new Map;thread(e,n){let r=Fu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ke(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Du)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Es=new WeakMap;function Mt(t){let e=Es.get(t);return e||(e=new it,Es.set(t,e)),e}function at(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function ut(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var De=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},qu=["<tool_call>","<function="];function ju(t){return qu.find(e=>t.includes(e))}function ze(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Ye(t,e,n){if(!(!t||e>0))return ju(n)}function lt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Pe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Bu(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function pr(t,e){let n=Bu(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var he=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function dt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ke?new he(n.message,"previous_response_not_found",400,"previous_response_id"):new he(String(n instanceof Error?n.message:n),"invalid_input")}}function As(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function fr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new he("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...As(e)!==void 0?{response_format:As(e)}:{}},o)}async function Lt(t){let{body:e,clients:n,store:r,stats:o}=t,s=dt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ae(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await fr(n,e,s,!0,c?ge(c):void 0);return{responseId:i,events:Ju({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function Hu(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?Vu(o[i++],a):a),...Gu(r,n)]}function Gu(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function Vu(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*Ju(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=L=>L.response&&typeof L.response=="object"?{...L,response:{...L.response,id:r}}:L,p=`item_${r.slice(5)}`,m=!1,h=!1,v=0;function*k(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],w=(L,H)=>{b.push({output_index:L,item:H})},f=!1,g=0,y="",_=0,S="";function*R(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:S};let L={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:S}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:L},w(g,L),S=""}let I=!1,E=0,O="",x=0,$="",B="";function*q(L){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:O,output_index:E,content_index:0,text:$},yield{type:"response.content_part.done",item_id:O,output_index:E,content_index:0,part:{type:"output_text",text:$}};let H={id:O,type:"message",role:"assistant",status:L,content:[{type:"output_text",text:$}]};yield{type:"response.output_item.done",output_index:E,item:H},w(E,H),$=""}let Q=new De,V=null,$e=-1;function*Z(L){if(!V)return;let H=V;V=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let W={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:L};yield{type:"response.output_item.done",output_index:H.outputIndex,item:W},w(H.outputIndex,W)}let ie=!1;for await(let L of l.track(e,o,t.turn)){d.push(L);let H=String(L.type??"");if(H==="response.created"||H==="response.in_progress"){m=!0,yield c(L);continue}if(H==="response.output_item.added"){h=!0,yield c(L);continue}if(H==="response.reasoning_text.delta"&&!h){yield*k(),f||(f=!0,g=v++,_+=1,y=_===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${_}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),S+=String(L.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:L.delta};continue}if(H==="response.output_text.delta"&&!h){yield*k(),yield*R(),I||(I=!0,E=v++,x+=1,O=x===1?p:`${p}_${x}`,yield{type:"response.output_item.added",output_index:E,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:O,output_index:E,content_index:0,part:{type:"output_text",text:""}}),$+=String(L.delta??""),B+=String(L.delta??""),yield{type:H,item_id:O,output_index:E,content_index:0,delta:L.delta};continue}let W=h?null:ut(L);if(W){if(yield*k(),yield*R(),yield*q("completed"),Q.add(W),W.tool_index!==$e){yield*Z("completed"),$e=W.tool_index;let je=v++;V={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:je,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:je,item:{id:V.fcId,type:"function_call",call_id:V.callId??V.fcId,name:V.name??"",arguments:"",status:"in_progress"}}}V&&(W.call_id&&(V.callId=W.call_id),W.name&&(V.name=W.name),V.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:V.fcId,output_index:V.outputIndex,delta:W.delta});continue}if(H==="response.completed"&&!h){let je=at(L.response),tt=Ye(s,Q.size+je.length,B);if(tt){ie=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(o,tt)}};break}if(yield*R(),yield*q("completed"),yield*Z("completed"),Q.size===0)for(let ee of je){let we=v++,Be=ee.id??ee.call_id??`fc_${we}`,Fn=ee.arguments??"",Kr={id:Be,type:"function_call",call_id:ee.call_id??Be,name:ee.name??""};yield{type:"response.output_item.added",output_index:we,item:{...Kr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Be,output_index:we,delta:Fn},yield{type:"response.function_call_arguments.done",item_id:Be,output_index:we,arguments:Fn};let zr={...Kr,arguments:Fn,status:"completed"};yield{type:"response.output_item.done",output_index:we,item:zr},w(we,zr)}let K=Hu(b,L.response);yield K.length>0?c({...L,response:{...L.response,output:K}}):c(L);continue}yield c(L)}if(yield*R(),yield*q("incomplete"),yield*Z("incomplete"),i&&!ie){let L=Ae(d);a.remember(r,n,pr(L,lt(d,L)),u)}}var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Wu=[/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 Se(t){return!Wu.some(e=>e.test(t))}function ke(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function pe(t,e){if(t instanceof j)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=Is(t);return n||{message:ke(e?.inferenceId??null),redacted:!0}}function Is(t){return t instanceof Me?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof z?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof F?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof ve?Se(t.message)?{message:t.message,redacted:!1}:null:t instanceof _e?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function ct(t,e,n){let r=n??(i=>console.error(i)),o=Is(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${be(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Se(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${be(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Se(e)?e:null}function be(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Ku="/v1/responses",zu=64*1024*1024,Yu=8*1024*1024,Xu=16,Os=32,Ts=3600*1e3,Qu=/^[A-Za-z0-9._-]{1,256}$/;function ue(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Zu=ue(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 hr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function el(t){for(;t.bufferedAmount>Yu&&t.readyState===Fe.WebSocket.OPEN;){let{promise:e,resolve:n}=hr();setTimeout(n,5),await e}}var mr=class extends it{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Ke))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},gr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new mr(Mt(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ue(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ts/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ts).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ue(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(ue(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(ue(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ue(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ue(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ue(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Qu.test(o.stream_id)){this.sendFrame(Zu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Os){this.sendFrame(ue(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Os}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Ct();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Lt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:$t(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await el(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Ct(),o=$t(r);try{let s=dt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:be(e);if(e instanceof he)return ue(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof F)return ue(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof j){let u=pe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ue(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),ue(s.status,{type:s.openaiType,message:o},n);let i=pe(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: ${o}`),ue(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),u=i??ke(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)}`),ue(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=Xu;){let{promise:e,resolve:n}=hr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function fn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
13
+ `),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Fe=require("ws");var Rs=require("crypto"),Es="Inference-Id";function Mt(){return(0,Rs.randomUUID)()}function hr(t){return t==="/v1"||t.startsWith("/v1/")}function As(t,e){if(!hr(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function $t(t){return`resp_${t}`}function Is(t){return`chatcmpl-${t}`}function Os(t){return`msg_${t}`}function he(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ts(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_seconds:null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Ps(t){return`${JSON.stringify(t)}
14
+ `}var Ju=256,Wu=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Wu)}var We=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Ju?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=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(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ku=256;function zu(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Ke=class extends Error{},it=class{conversations=new Map;thread(e,n){let r=zu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ke(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Ku)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Cs=new WeakMap;function Lt(t){let e=Cs.get(t);return e||(e=new it,Cs.set(t,e)),e}function at(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ie(t){return t.find(e=>e.type==="response.completed")?.response??null}function ut(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var De=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Yu=["<tool_call>","<function="];function Xu(t){return Yu.find(e=>t.includes(e))}function ze(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Ye(t,e,n){if(!(!t||e>0))return Xu(n)}function lt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ce(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Qu(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function yr(t,e){let n=Qu(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ye=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function dt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ke?new ye(n.message,"previous_response_not_found",400,"previous_response_id"):new ye(String(n instanceof Error?n.message:n),"invalid_input")}}function Ms(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function wr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ye("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Ms(e)!==void 0?{response_format:Ms(e)}:{}},o)}async function Nt(t){let{body:e,clients:n,store:r,stats:o}=t,s=dt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ue(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await wr(n,e,s,!0,c?he(c):void 0);return{responseId:i,events:nl({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function Zu(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?tl(o[i++],a):a),...el(r,n)]}function el(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function tl(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*nl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=$=>$.response&&typeof $.response=="object"?{...$,response:{...$.response,id:r}}:$,p=`item_${r.slice(5)}`,m=!1,g=!1,v=0;function*x(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],w=($,H)=>{S.push({output_index:$,item:H})},f=!1,h=0,y="",b=0,R="";function*A(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:h,content_index:0,text:R};let $={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:$},w(h,$),R=""}let O=!1,_=0,E="",k=0,M="",q="";function*B($){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:E,output_index:_,content_index:0,text:M},yield{type:"response.content_part.done",item_id:E,output_index:_,content_index:0,part:{type:"output_text",text:M}};let H={id:E,type:"message",role:"assistant",status:$,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:_,item:H},w(_,H),M=""}let N=new De,U=null,oe=-1;function*J($){if(!U)return;let H=U;U=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let z={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:$};yield{type:"response.output_item.done",output_index:H.outputIndex,item:z},w(H.outputIndex,z)}let ne=!1;for await(let $ of l.track(e,o,t.turn)){d.push($);let H=String($.type??"");if(H==="response.created"||H==="response.in_progress"){m=!0,yield c($);continue}if(H==="response.output_item.added"){g=!0,yield c($);continue}if(H==="response.reasoning_text.delta"&&!g){yield*x(),f||(f=!0,h=v++,b+=1,y=b===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${b}`,yield{type:"response.output_item.added",output_index:h,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String($.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:h,content_index:0,delta:$.delta};continue}if(H==="response.output_text.delta"&&!g){yield*x(),yield*A(),O||(O=!0,_=v++,k+=1,E=k===1?p:`${p}_${k}`,yield{type:"response.output_item.added",output_index:_,item:{id:E,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:E,output_index:_,content_index:0,part:{type:"output_text",text:""}}),M+=String($.delta??""),q+=String($.delta??""),yield{type:H,item_id:E,output_index:_,content_index:0,delta:$.delta};continue}let z=g?null:ut($);if(z){if(yield*x(),yield*A(),yield*B("completed"),N.add(z),z.tool_index!==oe){yield*J("completed"),oe=z.tool_index;let Be=v++;U={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:Be,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:Be,item:{id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:"",status:"in_progress"}}}U&&(z.call_id&&(U.callId=z.call_id),z.name&&(U.name=z.name),U.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:U.fcId,output_index:U.outputIndex,delta:z.delta});continue}if(H==="response.completed"&&!g){let Be=at($.response),tt=Ye(s,N.size+Be.length,q);if(tt){ne=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(o,tt)}};break}if(yield*A(),yield*B("completed"),yield*J("completed"),N.size===0)for(let ee of Be){let _e=v++,je=ee.id??ee.call_id??`fc_${_e}`,jn=ee.arguments??"",Zr={id:je,type:"function_call",call_id:ee.call_id??je,name:ee.name??""};yield{type:"response.output_item.added",output_index:_e,item:{...Zr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:je,output_index:_e,delta:jn},yield{type:"response.function_call_arguments.done",item_id:je,output_index:_e,arguments:jn};let eo={...Zr,arguments:jn,status:"completed"};yield{type:"response.output_item.done",output_index:_e,item:eo},w(_e,eo)}let Y=Zu(S,$.response);yield Y.length>0?c({...$,response:{...$.response,output:Y}}):c($);continue}yield c($)}if(yield*A(),yield*B("incomplete"),yield*J("incomplete"),i&&!ne){let $=Ie(d);a.remember(r,n,yr($,lt(d,$)),u)}}var Oe=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},pe=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var rl=[/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 ke(t){return!rl.some(e=>e.test(t))}function xe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function fe(t,e){if(t instanceof V)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=$s(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function $s(t){return t instanceof $e?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof X?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof G?{message:t.message,redacted:!1}:t instanceof Oe?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof be?ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof ve?{message:t.message,redacted:!1}:t instanceof pe?{message:t.message,redacted:!1}:null}function ct(t,e,n){let r=n??(i=>console.error(i)),o=$s(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Se(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Se(e)}`),`the ${t} upstream failed while serving this request`)}function Te(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function Se(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var ol="/v1/responses",sl=64*1024*1024,il=8*1024*1024,al=16,Ls=32,Ns=3600*1e3,ul=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var ll=le(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 br(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function dl(t){for(;t.bufferedAmount>il&&t.readyState===Fe.WebSocket.OPEN;){let{promise:e,resolve:n}=br();setTimeout(n,5),await e}}var _r=class extends it{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Ke))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},vr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new _r(Lt(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ns/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ns).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(le(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(le(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(le(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(le(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!ul.test(o.stream_id)){this.sendFrame(ll);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Ls){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Ls}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Mt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Nt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:$t(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await dl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Mt(),o=$t(r);try{let s=dt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Se(e);if(e instanceof ye)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof G)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof V){let u=fe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),le(s.status,{type:s.openaiType,message:o},n);let i=fe(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: ${o}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Te(o),u=i??xe(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)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=al;){let{promise:e,resolve:n}=br();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function gn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
15
15
  `;t.end(`HTTP/1.1 ${e} ${r}\r
16
16
  Connection: close\r
17
17
  Content-Type: text/plain; charset=utf-8\r
18
18
  Content-Length: ${Buffer.byteLength(o)}\r
19
19
  \r
20
- ${o}`)}function Ps(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:zu}),r=new We,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{fn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==Ku){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){fn(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(k){let b=e.statusOf?.(k)??null;fn(c,b?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new gr(k,v,r,e.statusOf,e.operatorLog??(b=>console.error(b)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&fn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=hr();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Fe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Tr=require("@urun-sh/core");var Cs=require("@urun-sh/core"),tl={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},nl={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 Nt(t,e){let n=nl[t.code];return e?`${n} (${e})`:n}function mn(t){if(t==null)return null;let e=tl[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function gn(t){if(t.kind==="create-failed")return mn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Cs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return mn(e?"cold_start_exceeded":"queue_timeout")}var Ms=nt(require("os"),1),Ls=nt(require("path"),1),Ns=require("url"),Us=require("util");var $s="0.6.41";var Ds=4141,ol=$s,yn={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function _r(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function Fs(t,e,n){let r={...t,..._r(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function qs(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function js(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Bs(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Hs(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=(0,Ns.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function Gs(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function Vs(t){if(t[0]!=="--port")return null;let e=Gs(t[1]);return t.splice(0,2),e}function vr(t){let e=t.indexOf("--port");if(e===-1)return Ds;let n=Gs(t[e+1]);return t.splice(e,2),n}function Js(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function yr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function pt(t){let e=sl(yr(t,"URUN_BASE_URL")),n=yr(t,"URUN_ORG_ID"),r=yr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?hn(s,"URUN_API_URL"):Mo,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?hn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function sl(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function hn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function br(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:ol}}function il(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var al=250;async function Sr(t,e=al){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Ws=2e3;async function ul(t,e=Ws){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function Ks(t,e,n=Ds,r=Ws){if(t!=null)return{mode:"spawn",port:t};let o=await Sr(n);if(o!==null&&il(o,e)){let s=await ul(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function kr(t,e=Ms.default.homedir()){return Ls.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var wr=["log","info","warn","error","debug","trace"];function zs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(wr.map(u=>[u,n[u]]));for(let u of wr)n[u]=(...a)=>{t.write(`${(0,Us.format)(...a)}
21
- `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of wr)n[u]=i[u]}}var ll=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ys(t){let e=t?.code;return typeof e=="string"&&ll.has(e)}function xe(t,e){try{return t.write(e),!0}catch(n){if(Ys(n))return!1;throw n}}function Xs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Ys(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
22
- `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function Qs(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
20
+ ${o}`)}function Us(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:sl}),r=new We,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{gn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==ol){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){gn(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(x){let S=e.statusOf?.(x)??null;gn(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,x=>{s.delete(c),o.add(x),x.on("close",()=>o.delete(x));try{new vr(x,v,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(x),x.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&gn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=br();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Fe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Lr=require("@urun-sh/core");var Ds=require("@urun-sh/core"),cl={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},pl={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 Ut(t,e){let n=pl[t.code];return e?`${n} (${e})`:n}function hn(t){if(t==null)return null;let e=cl[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function yn(t){if(t.kind==="create-failed")return hn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ds.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return hn(e?"cold_start_exceeded":"queue_timeout")}var qs=nt(require("os"),1),Bs=nt(require("path"),1),js=require("url"),Hs=require("util");var Fs="0.6.43";var Gs=4141,ml=Fs,_n={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function xr(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function Vs(t,e,n){let r={...t,...xr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Js(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function Ws(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Ks(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function zs(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=(0,js.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function Ys(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function Xs(t){if(t[0]!=="--port")return null;let e=Ys(t[1]);return t.splice(0,2),e}function Rr(t){let e=t.indexOf("--port");if(e===-1)return Gs;let n=Ys(t[e+1]);return t.splice(e,2),n}function Qs(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function Sr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function pt(t){let e=gl(Sr(t,"URUN_BASE_URL")),n=Sr(t,"URUN_ORG_ID"),r=Sr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?wn(s,"URUN_API_URL"):Bo,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?wn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function gl(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function wn(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function Er(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:ml}}function hl(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var yl=250;async function Ar(t,e=yl){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Zs=2e3;async function wl(t,e=Zs){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ei(t,e,n=Gs,r=Zs){if(t!=null)return{mode:"spawn",port:t};let o=await Ar(n);if(o!==null&&hl(o,e)){let s=await wl(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function Ir(t,e=qs.default.homedir()){return Bs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var kr=["log","info","warn","error","debug","trace"];function ti(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(kr.map(u=>[u,n[u]]));for(let u of kr)n[u]=(...a)=>{t.write(`${(0,Hs.format)(...a)}
21
+ `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of kr)n[u]=i[u]}}var _l=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ni(t){let e=t?.code;return typeof e=="string"&&_l.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(ni(n))return!1;throw n}}function ri(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{ni(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
22
+ `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function oi(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
23
23
  `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
24
24
  `)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
25
- `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function Zs(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}var si=require("ws");var oi=require("@urun-sh/core");var ti=require("crypto");function T(t){return`${t}_${(0,ti.randomUUID)().replace(/-/g,"").slice(0,24)}`}var wn=4*1024*1024,xr=8*1024*1024,_n=512,vn=20*1024*1024;function Y(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Xe(t,e){return{type:"server_error",code:t,message:e}}function G(t){return{type:"error",event_id:T("event"),error:t}}function Rr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},dl={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},cl={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},pl={format:!0,voice:!0,speed:!0};function fl(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function ft(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ei(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var ml=10;function Er(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:ml})}function Ut(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in dl));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=ft(o.modalities,"modalities"),a=ft(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("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[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: 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(a==="transcription"&&!n.turns)throw new P('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=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=ft(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!fl(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=Er(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("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=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`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,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new P(`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(m!=null&&m!==c[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, 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(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`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=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("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 P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in cl))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ei(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Ut({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Ut({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("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 P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in pl))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ei(d.format,"audio.output.format"),d.speed!==void 0)throw new P("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 P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("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 bn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Ar(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:T("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new P("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 P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("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 P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Sn(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var gl=1001,hl=1011,ni=t=>t.slice(0,120),yl=/^[A-Za-z0-9+/=]*$/,wl=2;function _l(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>wl)return!1;return!0}var Dt=class{id=T("conn");ws;binding;onClosed;operatorLog;config=Rr();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;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??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:T("event"),session:bn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof j&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(G(Xe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:T("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:T("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:T("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:T("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("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=T("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:i,content_index:0,transcript:s}),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 n;try{n=e.toString()}catch{this.fail(Y("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>wn){this.fail(Y("frame_too_large",`frame exceeds the ${wn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Y("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Y("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Xe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Ut(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(G(Y("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:T("event"),session:bn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Ar(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(G(Y("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:T("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(G(Y("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(G(Y("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:T("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(Y("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!yl.test(e.audio)){this.send(G(Y("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>vn){this.send(G(Y("buffer_full",`uncommitted input audio exceeds the ${vn}-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+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(G(Y("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=T("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(Y("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(Y("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(Y("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(Y("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(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,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,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(Y("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?ft(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?ft(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("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((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(G(Y("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=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:Sn(this.items),c=Er(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,h=m==="inf"||m===void 0?void 0:m,v=n.tools!==void 0?n.tools:this.config.tools,k=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,b={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},...v!==void 0?{tools:v}:{},...k!==void 0?{tool_choice:k}:{}};if(!(a&&!this.ensureVoice())){for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],f=S=>{this.responseFlushed?this.send(S):w.push(S)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let S of w)this.send(S);w.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},_=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))return;l=this.items.length,d=Sn(this.items)}let{input:S,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},I={...b,input:S,...a?this.compositeTurnAsk(n):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(I,i)}catch(O){this.upstreamTurnFault(O,u);return}try{for await(let O of E){if(this.cancelled)break;let x=O;if(x.type==="error"){let $=this.upstreamErrorBody(x);this.responseFlushed?this.send(G($)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,$)});return}if(x.type==="response.output_text.delta"&&typeof x.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(u,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&f({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:x.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,f({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:x.delta})),y.messageText+=x.delta;continue}if(x.type==="response.function_call_arguments.delta"){g();let $=typeof x.delta=="string"?x.delta:"",B=typeof x.call_id=="string"&&x.call_id.length>0?x.call_id:`${u}_fc_${y.nextOutputIndex}`,q=y.tools.get(B);if(!q){let Q=typeof x.name=="string"&&x.name.length>0?x.name:void 0;q={outputIndex:y.nextOutputIndex++,name:Q,args:""},y.tools.set(B,q);let V={id:B,object:"realtime.item",type:"function_call",call_id:B,name:Q??"",arguments:"",status:"in_progress"};f({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:q.outputIndex,item:V}),this.emitAssistantItemAdded(V)}typeof x.name=="string"&&x.name.length>0&&(q.name=x.name),q.args+=$,f({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:B,response_id:u,output_index:q.outputIndex,call_id:B,name:q.name??"",delta:$});continue}if(x.type==="response.completed"){_=x.response??null;continue}}}catch(O){this.upstreamTurnFault(O,u);return}if(this.cancelled)return;this.closeOpenItems(u,y,l),g(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,_)})}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,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(_l(n))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:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("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:T("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:T("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Oe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ke(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Se(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${be(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Xe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof j){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof oi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Xe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(Y("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>_n&&(this.items.shift(),this.send(G({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${_n} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(G(Y("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>St){this.send(G(Y("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${St}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(Y("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(G(Xe(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>xr){this.ws.close(gl,ni("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=pe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${be(e)}`),r.message}fail(e,n){this.send(G(e)),this.ws.close(hl,ni(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>ri(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ri(this.id,e)}},Ir=[];function ri(t,e){Ir.push({id:t,reason:e}),Ir.length>256&&Ir.shift()}var Pr="/v1/realtime",vl=t=>t.slice(0,120);function bl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
+ `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function si(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}var qt=require("ws");var di=require("@urun-sh/core");var ai=require("crypto");function T(t){return`${t}_${(0,ai.randomUUID)().replace(/-/g,"").slice(0,24)}`}var vn=4*1024*1024,Or=8*1024*1024,bn=512,Sn=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Xe(t,e){return{type:"server_error",code:t,message:e}}function W(t){return{type:"error",event_id:T("event"),error:t}}function Tr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},vl={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},bl={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Sl={format:!0,voice:!0,speed:!0};function kl(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function ft(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ii(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var xl=10;function Pr(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:xl})}function Dt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in vl));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=ft(o.modalities,"modalities"),a=ft(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("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[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: 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(a==="transcription"&&!n.turns)throw new P('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=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=ft(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!kl(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=Pr(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("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=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`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,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new P(`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(m!=null&&m!==c[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, 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(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`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=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("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 P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in bl))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ii(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Dt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Dt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("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 P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Sl))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ii(d.format,"audio.output.format"),d.speed!==void 0)throw new P("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 P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("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 kn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Cr(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:T("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new P("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 P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("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 P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function xn(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Rl=1001,El=1011,Al=15e3;var Rn=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},ui=t=>t.slice(0,120),Il=/^[A-Za-z0-9+/=]*$/,Ol=2;function Tl(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ol)return!1;return!0}var Ft=class{id=T("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=Tr();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;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??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Al,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:T("event"),session:kn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof V&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(W(Xe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:T("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:T("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:T("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:T("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("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=T("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:i,content_index:0,transcript:s}),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 n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>vn){this.fail(Q("frame_too_large",`frame exceeds the ${vn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(W({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Xe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Dt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(W(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:T("event"),session:kn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Cr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(W(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:T("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(W(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(W(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:T("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(W(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Il.test(e.audio)){this.send(W(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Sn){this.send(W(Q("buffer_full",`uncommitted input audio exceeds the ${Sn}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;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:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(W(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=T("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(W(Q("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(W(Q("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(W(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(W(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(W({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=!0;try{for(;;){let o;if(r||this.turnStallMs<=0)r=!1,o=await n.next();else{let s,i=new Promise((u,a)=>{s=setTimeout(()=>a(new Rn),this.turnStallMs)});o=await Promise.race([n.next(),i]).finally(()=>clearTimeout(s))}if(o.done===!0)return;yield o.value}}finally{await n.return?.()}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,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(W(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?ft(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?ft(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("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((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(W(Q("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=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:xn(this.items),c=Pr(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,g=m==="inf"||m===void 0?void 0:m,v=n.tools!==void 0?n.tools:this.config.tools,x=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...g!==void 0?{max_output_tokens:g}:{},...v!==void 0?{tools:v}:{},...x!==void 0?{tool_choice:x}:{}};if(!(a&&!this.ensureVoice())){for(let{audio:w,captureWallMs:f}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w,f);this.inFlight=(async()=>{let w=[],f=R=>{this.responseFlushed?this.send(R):w.push(R)},h=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let R of w)this.send(R);w.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},b=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(E=>{this.pendingTranscriptSettled=E}),this.cancelled||this.closed))return;l=this.items.length,d=xn(this.items)}let{input:R,sawAudioOnlyItem:A}=d??{input:[],sawAudioOnlyItem:!1},O={...S,input:R,...a?this.compositeTurnAsk(n):{}};A&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let _;try{_=await this.upstreamStream(O,i)}catch(E){this.upstreamTurnFault(E,u);return}try{for await(let E of this.stallBoundedTurn(_)){if(this.cancelled)break;let k=E;if(k.type==="error"){let M=this.upstreamErrorBody(k);this.responseFlushed?this.send(W(M)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,M)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){h(),y.messageOpen||(this.beginMessageItem(u,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&f({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,f({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta})),y.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){h();let M=typeof k.delta=="string"?k.delta:"",q=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${u}_fc_${y.nextOutputIndex}`,B=y.tools.get(q);if(!B){let N=typeof k.name=="string"&&k.name.length>0?k.name:void 0;B={outputIndex:y.nextOutputIndex++,name:N,args:""},y.tools.set(q,B);let U={id:q,object:"realtime.item",type:"function_call",call_id:q,name:N??"",arguments:"",status:"in_progress"};f({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:B.outputIndex,item:U}),this.emitAssistantItemAdded(U)}typeof k.name=="string"&&k.name.length>0&&(B.name=k.name),B.args+=M,f({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:q,response_id:u,output_index:B.outputIndex,call_id:q,name:B.name??"",delta:M});continue}if(k.type==="response.completed"){b=k.response??null;continue}}}catch(E){if(E instanceof Rn)this.operatorLog(`[realtime] turn ${u} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(E,u);return}}if(this.cancelled)return;this.closeOpenItems(u,y,l),h(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,b)})}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,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Tl(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(W({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:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("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:T("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:T("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Te(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??xe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Se(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Xe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof V){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof di.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Xe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(W(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(W(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>bn&&(this.items.shift(),this.send(W({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${bn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(W(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>St){this.send(W(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${St}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(W(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(W(Xe(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Or){this.ws.close(Rl,ui("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=fe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Se(e)}`),r.message}fail(e,n){this.send(W(e)),this.ws.close(El,ui(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>li(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),li(this.id,e)}},Mr=[];function li(t,e){Mr.push({id:t,reason:e}),Mr.length>256&&Mr.shift()}var Nr="/v1/realtime",ci="urun.admission",pi=t=>t.slice(0,120);function Pl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
29
- ${vl(n)}\r
30
- `),t.destroy()}function Sl(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
31
- `}function kl(t){xe(process.stdout,t)}function xl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Or(t){return t.audioSession?.audio.sessionId??void 0}function Cr(t,e){let n=new si.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Pr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=T("rtup"),l=xl(o),d=y=>{(e.log??kl)(Sl(y))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,m=y=>{p??=y,c.abort(new Error(p))},h=()=>m("client socket closed"),v=()=>m("client socket closed (half-close)"),k=y=>m(`client socket error: ${y.message}`);s.once("close",h),s.once("end",v),s.once("error",k);let b=()=>{s.removeListener("close",h),s.removeListener("end",v),s.removeListener("error",k)},w=y=>{d({stage:"close",conn:a,model:l,...y})},f=y=>{let _=y,S=_.session!=null&&typeof _.session.sendResponseCreate=="function",R=_.clients!=null&&typeof _.clients.createResponse=="function";if(!S&&!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((I,E)=>{n.handleUpgrade(o,s,i,O=>{try{new Dt({ws:O,binding:y,operatorLog:e.operatorLog,onClosed:(x,$)=>{w({while:"live",reason:$.reason})}}),d({stage:"admit",conn:a,model:l,...Or(y)===void 0?{}:{session:Or(y)}}),I()}catch(x){E(x)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async y=>{if(c.signal.aborted){b();let _=Or(y);try{await y.release?.()}catch(S){w({while:"queued",..._===void 0?{}:{session:_},reason:p??"client socket closed",release_failed:S instanceof Error?S.message:String(S)});return}w({while:"queued",..._===void 0?{}:{session:_},reason:p??"client socket closed",released:!0}),s.destroy();return}b(),await f(y)}).catch(y=>{let _=y instanceof Tr.SessionFailedError?gn(y):null,S=null;if(y!==null&&typeof y=="object"&&"status"in y){let O=y.status;typeof O=="number"&&(S=O)}let R=S??_?.status??502,I=y instanceof Error?y.message:String(y),E=S!==null?I:_!==null?Nt(_,y instanceof Tr.SessionFailedError&&y.status.sessionId?`session ${y.status.sessionId}`:void 0):pe(y).message;w({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:I,status:R}}),s.destroyed||bl(s,R,E)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var di=require("crypto");var Mr="x-urun-profile",Ft="voice";var le=class extends Error{status=400},Rl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,El=/\s/;function Al(t){return Rl.test(t)}function $r(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new le(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ii(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new le(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new le(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new le(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function ai(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new le(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new le(`the ${Mr} header is empty \u2014 the only profile this lane accepts is "${Ft}" (omit the header for the ordinary lane)`);if(l!==Ft)throw new le(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Ft}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Ft)throw new le(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Ft}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new le("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new le("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:ii(a,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:ii(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:$r(a,"sentence_flush",!0),includeReasoning:$r(a,"include_reasoning",!1),metadata:$r(a,"metadata",!1)}}var mt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Al(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(El.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ce=(t,e)=>Object.assign(new Error(e),{status:t}),Tl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Nr=(t,e,n)=>new j(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Lr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof F?Ce(404,n.message):n}};async function ui(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ce(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Tl}`);if(o==="transcription")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); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ce(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ce(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof F?Ce(404,m.message):m}if(!p)throw Ce(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof F?Ce(404,m.message):m}if(p!=="stt")throw Ce(501,`the configured stt companion ${JSON.stringify(n.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 s=await Lr(t,n.stt),i=await Lr(t,e),u=await Lr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Pl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof j?Nr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function li(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var kn=class extends Error{};async function*Pl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,h=null,v=null,k=[],b=null,w=new Promise((O,x)=>{n&&n.addEventListener("abort",()=>x(new kn),{once:!0})}),f=()=>m||n?.aborted===!0,g=async O=>{if(f())return;let x;try{x=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(B){throw B instanceof j?Nr("tts",a.tts,B):B}let $=x[Symbol.asyncIterator]();v=$;try{for(;;){let B=$.next(),q;try{q=await Promise.race([B,w])}catch(V){if(B.catch(()=>{}),V instanceof kn)return;throw V}if(q.done)return;let Q=q.value;if(Q.type==="error"){let V=Q.error&&typeof Q.error.message=="string"?Q.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${V}`)}if(Q.type==="response.completed")return}}finally{v===$&&(v=null)}},y=async()=>{for(;k.length>0&&!f();){let O=k.shift();await g(O)}},_=O=>{if(O===""||f()||(k.push(O),b!==null))return;let x=y();b=x,x.then(()=>{b===x&&(b=null)},$=>{b===x&&(b=null),h??=$})},S=()=>{m=!0,k.length=0;let O=v;if(v=null,O){let x=O.return?.();x&&x.catch(()=>{})}},R=async()=>{for(;k.length>0||b!==null;){let O=b;if(O===null){await g(k.shift());continue}await O}},I=p?new mt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>_(O)):null,E=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(x){throw x instanceof j?Nr("chat",u,x):x}for await(let x of O){if(f())return;let $=x;if($.type==="error"){yield x;return}if($.type==="response.output_text.delta"&&typeof $.delta=="string"){yield x,I?.push($.delta);continue}if($.type==="response.function_call_arguments.delta"){I?.flush(),yield x;continue}if($.type==="response.completed"){E=x.response;continue}}I?.flush(),I?.dispose(),p&&await R(),E!==null&&(yield{type:"response.completed",response:E})}finally{I?.dispose(),S();try{if(h instanceof j)throw h}finally{r?.()}}}var fe=(t,e)=>Object.assign(new Error(e),{status:t});function Cl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function $l(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ml='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Ll(t,e,n,r){if(!t.supportsAudio)throw fe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(c){throw c instanceof F?fe(404,c.message):c}if(!o){let c=null;if(t.realtimeCompanionsFor)try{c=await t.realtimeCompanionsFor(e)}catch(p){throw p instanceof F?fe(404,p.message):p}if(c!==null)return await ui(t,e,c,n,r);throw fe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw fe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(c){throw c instanceof F?fe(404,c.message):c}if(s&&!t.openTurnsOn)throw fe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let c;try{c=await t.transcriptStreamFor(e)}catch(p){throw p instanceof F?fe(404,p.message):p}if(c!=="stt")throw fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \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 fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ml}`);if(r==="transcription"&&!s)throw fe(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=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(c){throw c instanceof ce?fe(503,c.message):c}let u=`conn_${(0,di.randomUUID)()}`,l={audio:await t.openAudioOn(i,n,u).catch(c=>{throw t.releaseSessionHandle?.(i),c})},d={clients:{createResponse:async c=>await t.createResponseOn(i,c,u)},voice:o,audioSession:l};return t.openVideoOn&&(d.video=()=>t.openVideoOn(i,n)),s&&(d.turns=c=>t.openTurnsOn(i,c)),r==="transcription"&&(d.intent="transcription"),t.releaseSessionHandle&&(d.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(d.model=e),d}function ci(t,e,n){let r=li(t,n);return{resolve:async(o,s)=>{if(e!==void 0){let i=o.headers.authorization,u=typeof i=="string"?i.trim():"",a=u.startsWith("Bearer ")?u.slice(7).trim():"";if(a===""||a!==e)throw fe(401,"invalid local proxy api key")}return Ll(r,Cl(o),s,$l(o))}}}var M=class extends Error{},ye=class extends Error{};function re(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function gt(t,e){if(t!=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 Ur(t){let e=xn(t);return e!==null&&e<=1?e:null}function pi(t,e){if(!re(t))throw new M("decisions requires a JSON object body");gt(t.prompt_cache_key,"prompt_cache_key"),gt(t.prompt_cache_options,"prompt_cache_options"),gt(t.safety_identifier,"safety_identifier");let n=[],r=Nl(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new M("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=ql(o[l],l,o.length,n);if(u.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`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function Nl(t,e){if(typeof t=="string")return t;if(!re(t)&&!Array.isArray(t))throw new M("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)Dl(o,r,e);return Ul(r)}function Ul(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
29
+ ${pi(n)}\r
30
+ `),t.destroy()}function Cl(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
31
+ `}function Ml(t){Re(process.stdout,t)}function $l(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function $r(t){return t.audioSession?.audio.sessionId??void 0}function Ur(t,e){let n=new qt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Nr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=T("rtup"),l=$l(o),d=_=>{(e.log??Ml)(Cl(_))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,m=_=>{p??=_,c.abort(new Error(p))},g=()=>m("client socket closed"),v=()=>m("client socket closed (half-close)"),x=_=>m(`client socket error: ${_.message}`);s.once("close",g),s.once("end",v),s.once("error",x);let S=()=>{s.removeListener("close",g),s.removeListener("end",v),s.removeListener("error",x)},w=_=>{d({stage:"close",conn:a,model:l,..._})},f=null,h=!1,y=null,b=_=>JSON.stringify({type:ci,event_id:T("event"),..._}),R=_=>{if(f!==null){f.readyState===qt.WebSocket.OPEN&&f.send(b(_));return}h||(h=!0,n.handleUpgrade(o,s,i,E=>{f=E,y=[],E.on("message",k=>{y?.push(String(k))}),d({stage:"waiting",conn:a,model:l,status:_.status}),E.send(b(_))}))},A=_=>{let E=_,k=E.session!=null&&typeof E.session.sendResponseCreate=="function",M=E.clients!=null&&typeof E.clients.createResponse=="function";if(!k&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((q,B)=>{let N=(U,oe)=>{try{let J=Date.now();new Ft({ws:U,binding:_,operatorLog:e.operatorLog,...oe.length>0?{replayFrames:oe}:{},onClosed:(ne,$)=>{w({while:"live",reason:$.reason});try{e.onSessionEnded?.({req:o,binding:_,connected_ms:Math.max(0,Date.now()-J),reason:$.reason})}catch(H){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${H instanceof Error?H.message:String(H)}
32
+ `)}}}),d({stage:"admit",conn:a,model:l,...$r(_)===void 0?{}:{session:$r(_)}}),q()}catch(J){B(J)}};if(f!==null){let U=y??[];y=null,N(f,U);return}n.handleUpgrade(o,s,i,U=>N(U,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,R).then(async _=>{if(c.signal.aborted){S();let E=$r(_);try{await _.release?.()}catch(k){w({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}w({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),s.destroy();return}S(),await A(_)}).catch(_=>{let E=_ instanceof Lr.SessionFailedError?yn(_):null,k=null;if(_!==null&&typeof _=="object"&&"status"in _){let N=_.status;typeof N=="number"&&(k=N)}let M=k??E?.status??502,q=_ instanceof Error?_.message:String(_),B=k!==null?q:E!==null?Ut(E,_ instanceof Lr.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):fe(_).message;if(w({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:q,status:M}}),f!==null&&!c.signal.aborted){let N=JSON.stringify({type:ci,event_id:T("event"),status:M<500?"rejected":"failed",reason:B});f.readyState===qt.WebSocket.OPEN&&f.send(N),f.close(1011,pi(B));return}s.destroyed||Pl(s,M,B)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var yi=require("crypto");var Fr="x-urun-profile",Bt="voice";var de=class extends Error{status=400},Ll=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Nl=/\s/;function Ul(t){return Ll.test(t)}function Dr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function fi(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new de(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new de(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new de(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function mi(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new de(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new de(`the ${Fr} header is empty \u2014 the only profile this lane accepts is "${Bt}" (omit the header for the ordinary lane)`);if(l!==Bt)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Bt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Bt)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Bt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:fi(a,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:fi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Dr(a,"sentence_flush",!0),includeReasoning:Dr(a,"include_reasoning",!1),metadata:Dr(a,"metadata",!1)}}var mt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Ul(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Nl.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Me=(t,e)=>Object.assign(new Error(e),{status:t}),ql='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Br=(t,e,n)=>new V(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),qr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof G?Me(404,n.message):n}};async function gi(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Me(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${ql}`);if(o==="transcription")throw Me(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Me(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Me(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof G?Me(404,m.message):m}if(!p)throw Me(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof G?Me(404,m.message):m}if(p!=="stt")throw Me(501,`the configured stt companion ${JSON.stringify(n.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 s=await qr(t,n.stt),i=await qr(t,e),u=await qr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Bl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof V?Br("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function hi(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var En=class extends Error{};async function*Bl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,g=null,v=null,x=[],S=null,w=new Promise((E,k)=>{n&&n.addEventListener("abort",()=>k(new En),{once:!0})}),f=()=>m||n?.aborted===!0,h=async E=>{if(f())return;let k;try{k=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:E}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(q){throw q instanceof V?Br("tts",a.tts,q):q}let M=k[Symbol.asyncIterator]();v=M;try{for(;;){let q=M.next(),B;try{B=await Promise.race([q,w])}catch(U){if(q.catch(()=>{}),U instanceof En)return;throw U}if(B.done)return;let N=B.value;if(N.type==="error"){let U=N.error&&typeof N.error.message=="string"?N.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${U}`)}if(N.type==="response.completed")return}}finally{v===M&&(v=null)}},y=async()=>{for(;x.length>0&&!f();){let E=x.shift();await h(E)}},b=E=>{if(E===""||f()||(x.push(E),S!==null))return;let k=y();S=k,k.then(()=>{S===k&&(S=null)},M=>{S===k&&(S=null),g??=M})},R=()=>{m=!0,x.length=0;let E=v;if(v=null,E){let k=E.return?.();k&&k.catch(()=>{})}},A=async()=>{for(;x.length>0||S!==null;){let E=S;if(E===null){await h(x.shift());continue}await E}},O=p?new mt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},E=>b(E)):null,_=null;try{let E;try{E=await o.createResponseOn(s,d)}catch(k){throw k instanceof V?Br("chat",u,k):k}for await(let k of E){if(f())return;let M=k;if(M.type==="error"){yield k;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield k,O?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){O?.flush(),yield k;continue}if(M.type==="response.completed"){_=k.response;continue}}O?.flush(),O?.dispose(),p&&await A(),_!==null&&(yield{type:"response.completed",response:_})}finally{O?.dispose(),R();try{if(g instanceof V)throw g}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function jl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Hl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Gl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Vl(t,e,n,r,o){if(!t.supportsAudio)throw me(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(g){throw g instanceof G?me(404,g.message):g}if(m!==null)return await gi(t,e,m,n,r);throw me(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw me(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(i&&!t.openTurnsOn)throw me(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let m;try{m=await t.transcriptStreamFor(e)}catch(g){throw g instanceof G?me(404,g.message):g}if(m!=="stt")throw me(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \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 me(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Gl}`);if(r==="transcription"&&!i)throw me(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 u;try{u=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(m){throw m instanceof pe?me(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,yi.randomUUID)()}`,c={audio:await t.openAudioOn(u,n,l,o).catch(m=>{throw t.releaseSessionHandle?.(u),m})},p={clients:{createResponse:async m=>await t.createResponseOn(u,m,l)},voice:s,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(u,n)),i&&(p.turns=m=>t.openTurnsOn(u,m)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(u)),e!==void 0&&(p.model=e),a!==null&&(p.catalog=a),p}function wi(t,e,n){let r=hi(t,n);return{resolve:async(o,s,i)=>{if(e!==void 0){let u=o.headers.authorization,a=typeof u=="string"?u.trim():"",l=a.startsWith("Bearer ")?a.slice(7).trim():"";if(l===""||l!==e)throw me(401,"invalid local proxy api key")}return Vl(r,jl(o),s,Hl(o),i)}}}var L=class extends Error{},we=class extends Error{};function se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function An(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function gt(t,e){if(t!=null)throw new L(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function jr(t){let e=An(t);return e!==null&&e<=1?e:null}function _i(t,e){if(!se(t))throw new L("decisions requires a JSON object body");gt(t.prompt_cache_key,"prompt_cache_key"),gt(t.prompt_cache_options,"prompt_cache_options"),gt(t.safety_identifier,"safety_identifier");let n=[],r=Jl(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new L("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=Yl(o[l],l,o.length,n);if(u.has(c.key))throw new L(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function Jl(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new L("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)Kl(o,r,e);return Wl(r)}function Wl(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
32
33
 
33
- `)}function Dl(t,e,n){if(!re(t))throw new M("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Fl(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){fi(s,e,n,void 0,!1);return}throw new M(`${o} 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(o??null)})`)}}function Fl(t,e,n,r){e==="assistant"&&gt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new M(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!re(s))throw new M("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new M(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}fi(o,n,r,e)}function fi(t,e,n,r,o=!0){for(let s of t){if(!re(s))throw new M("decisions content parts must be JSON objects");switch(gt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new M("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)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=s.data;if(!re(i)&&!(Array.isArray(i)&&i.every(re)))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":{n.push(mi(s));break}default:throw new M(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function mi(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new M("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===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,o]=n;if(o==="")throw new M("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new M("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.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 u={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(u.detail=i),u}function ql(t,e,n,r){if(!re(t))throw new M(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new M(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new M(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=jl(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:u,name:i}};case"choice":{let l=t.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 v of l){if(!re(v))throw new M(`questions[${e}] choices must be JSON objects`);let k=v.value;if(typeof k!="string"&&typeof k!="boolean")throw new M(`questions[${e}] choice value must be a string or boolean`);let b=String(k);if(c.has(b))throw new M(`questions[${e}] has duplicate choice value ${JSON.stringify(b)} (choices must be unique)`);c.add(b);let w=v.description;if(w!==void 0&&typeof w!="string")throw new M(`questions[${e}] choice description must be a string`);d.push(k),p.push(w)}let m=l.map((v,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:a,options:m},spec:{type:o,key:u,name:i,choiceValues:d}}}case"score":{let l=t.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 m of l){if(!re(m)||typeof m.label!="string")throw new M(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new M(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let h=m.description;if(h!==void 0&&typeof h!="string")throw new M(`questions[${e}] score level description must be a string`);let v=h!==void 0?`${m.label}: ${h}`:m.label;if(c.includes(v))throw new M(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d}}}}}function jl(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new M(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!re(s))throw new M(`questions[${e}] instruction parts must be JSON objects`);switch(gt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new M(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>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(mi(s));break}case"input_json":{let i=s.data;if(!re(i)&&!(Array.isArray(i)&&i.every(re)))throw new M(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new M(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
34
+ `)}function Kl(t,e,n){if(!se(t))throw new L("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){zl(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){vi(s,e,n,void 0,!1);return}throw new L(`${o} output must be a string or an array of parts`)}default:throw new L(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function zl(t,e,n,r){e==="assistant"&&gt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new L(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!se(s))throw new L("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new L(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}vi(o,n,r,e)}function vi(t,e,n,r,o=!0){for(let s of t){if(!se(s))throw new L("decisions content parts must be JSON objects");switch(gt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new L("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new L("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=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new L("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(bi(s));break}default:throw new L(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function bi(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new L("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new L("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new L("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new L("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new L("input_image detail must be low, high, auto, or original");let u={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(u.detail=i),u}function Yl(t,e,n,r){if(!se(t))throw new L(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new L(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new L(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=Xl(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:u,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new L(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let v of l){if(!se(v))throw new L(`questions[${e}] choices must be JSON objects`);let x=v.value;if(typeof x!="string"&&typeof x!="boolean")throw new L(`questions[${e}] choice value must be a string or boolean`);let S=String(x);if(c.has(S))throw new L(`questions[${e}] has duplicate choice value ${JSON.stringify(S)} (choices must be unique)`);c.add(S);let w=v.description;if(w!==void 0&&typeof w!="string")throw new L(`questions[${e}] choice description must be a string`);d.push(x),p.push(w)}let m=l.map((v,x)=>({name:String(d[x]),description:p[x]??String(d[x])}));return{entry:{kind:"choice",prompt:a,options:m},spec:{type:o,key:u,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new L(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!se(m)||typeof m.label!="string")throw new L(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new L(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let g=m.description;if(g!==void 0&&typeof g!="string")throw new L(`questions[${e}] score level description must be a string`);let v=g!==void 0?`${m.label}: ${g}`:m.label;if(c.includes(v))throw new L(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d}}}}}function Xl(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new L(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!se(s))throw new L(`questions[${e}] instruction parts must be JSON objects`);switch(gt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new L(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new L(`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(bi(s));break}case"input_json":{let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new L(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new L(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
34
35
 
35
- `)}function gi(t,e){if(!re(e))throw new ye("decision answer was not a JSON object");let n=e.answers;if(!re(n))throw new ye("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!re(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=re(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=Ur(s.noul);if(u===null)throw new ye(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new ye(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new ye(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=xn(s.confidence);if(d===null)throw new ye(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=Ur(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=xn(s.score);if(a===null)throw new ye(`the score answer for "${o.key}" carries no numeric score to translate`);let l=xn(s.confidence);if(l===null)throw new ye(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=Ur(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var oe=class extends Error{};async function Rn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new oe(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new oe(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function En(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new oe(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof oe?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var hi="/v1/images/generations",An="/v1/images/edits";function yi(t){return t===hi||t===An}var wi="/v1/images/models";async function _i(t,e,n){if(t){if(t.model=ae({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var D=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Bl=16*1024*1024,vi=64*1024*1024;function bi(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function qt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Si(t,e,n,r,o,s){let i=s??(h=>console.error(h)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let h of u){if(h.type==="error"){let v=h.error??{},k=typeof v.message=="string"&&v.message.length>0&&Se(v.message)?v.message:null;throw k===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new D(502,"the image upstream failed while serving this request")):new D(502,`image upstream error: ${k}`)}if(h.type==="response.completed"){a=h.response??null;break}}if(a===null)throw new D(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Pe(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new D(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(bi(p)===null)throw new D(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 ki(t,e){if(t instanceof D)return t;if(t instanceof Ie)throw t;return t instanceof F?new D(404,t.message):new D(502,ct("image",t,e))}async function xi(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return qt(r,new D(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ri(t,e){t&&(t.outputUnits=e.images.length)}function Ei(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Hl={model:!0,prompt:!0,response_format:!0,n:!0};async function Ai(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??vi;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${hi}`);let s;try{s=JSON.parse((await Rn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof oe?new D(413,p.message):new D(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new D(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Hl[p])throw new D(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 u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new D(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new D(400,"model must be a string","model");await _i(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new D(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 D(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",u.length,u.length),!await xi(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Si(n.clients,a,c,n.turn?ge(n.turn):void 0,n.turn,r);Ri(n.turn,p),Ei(e,p)}catch(p){throw ki(p,r)}}catch(s){if(s instanceof oe){qt(e,new D(413,s.message));return}if(s instanceof D){qt(e,s);return}throw s}}var Gl={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ii(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??vi,s=n.maxImagePartBytes??Bl;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${An}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new D(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await En(t,o)}catch(h){throw h instanceof oe?new D(413,h.message):new D(400,String(h instanceof Error?h.message:h))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new D(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new D(400,"model must be a string field","model");let d=l===null?void 0:l;await _i(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new D(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 h of u.keys())if(!Gl[h])throw new D(400,`form field "${h}" 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[]).`,h);let p=[];for(let h of["image","image[]"])for(let v of u.getAll(h)){if(!(v instanceof File))throw new D(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(v.size>s)throw new D(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let k=new Uint8Array(await v.arrayBuffer()),b=bi(k);if(b===null)throw new D(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:k,mime:b})}if(p.length===0)throw new D(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await xi(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:h,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(h).toString("base64")}`});try{let h=await Si(n.clients,d,m,n.turn?ge(n.turn):void 0,n.turn,r);Ri(n.turn,h),Ei(e,h)}catch(h){throw ki(h,r)}}catch(i){if(i instanceof oe){qt(e,new D(413,i.message));return}if(i instanceof D){qt(e,i);return}throw i}}var jt="/v1/audio/speech";function Ui(t){return t===jt}var Oi=4096,Ti=18e4,Pi=5e3,Vl=64*1024*1024,Ci=8,$i=5,Mi=1024*1024,ht="voice_applied",On="X-Urun-Voice-Applied",N=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Dr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Tn=class extends N{constructor(e){super(502,e)}};function Di(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Fi(t){return new N(502,`the runtime's ${ht} receipt ${JSON.stringify(t)} cannot be relayed as the ${On} 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 Jl(t,e,n){if(t){if(t.model=ae({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function qi(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Wl=2;function Kl(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Wl)return!1;return!0}function zl(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Li=new WeakMap,In=new WeakMap;function Yl(t,e){let n=In.get(t)??0;if(n>=Ci)throw new N(503,`this model's speech queue is full \u2014 ${Ci} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${$i}s`,void 0,$i);In.set(t,n+1);let r=Li.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Li.set(t,s),(async()=>{await r;try{return await e()}finally{In.set(t,(In.get(t)??1)-1),o()}})()}async function Xl(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new N(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof j))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Qe(t,e){if(t instanceof N)return t;if(t instanceof Ie)throw t;return t instanceof F?new N(404,t.message):new N(502,ct("speech",t,e))}async function Ni(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return Yl(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,h=!1,v,k=new Promise(R=>{v=R}),b=[],w=()=>{m&&!h&&b.length>=o.quietRunFrames&&(h=!0,v())},f=e.onOutputAudio(R=>{let I=Buffer.from(R,"base64");if(I.byteLength===0)return;let E=Kl(I);if(!p){if(E)return;p=!0}if(E){b.push(I),w();return}for(let O of b)c(O);b.length=0,c(I),w()}),g=null,y,_,S;try{S=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let I=new Promise(x=>{_=setTimeout(x,s.capMs)}),E=!1;for(;;){let x=S.next(),$=await Promise.race([x,I]);if($===void 0){E=!0,x.catch(()=>{});break}if($.done)break;let B=$.value;if(B.type==="error"){let q=B.error??{};await S.return?.();let Q=typeof q.message=="string"&&q.message.length>0&&Se(q.message)?q.message:null;throw Q===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(B)}`),new N(502,"the speech upstream failed while serving this request")):new N(502,`speech upstream error: ${Q}`)}if(B.type==="response.completed"){g=B.response??null,m=!0,a?.(g),w(),await S.return?.();break}}if(clearTimeout(_),E)throw new N(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(g===null)throw new N(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let O=!1;if(await Promise.race([k,new Promise(x=>{y=setTimeout(()=>{O=!0,x()},o.capMs)})]),y!==void 0&&clearTimeout(y),r.voice!==void 0){let x=g[ht];if(typeof x!="string"||x!==r.voice){let $=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${ht} ${JSON.stringify(x)}`:`no ${ht} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Tn($):new N(502,$)}}if(!p)throw new N(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(O&&!h&&b.length<1)throw new N(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return g}catch(R){throw R instanceof Tn||await Xl(t,n,S,s.returnBoundMs),R}finally{y!==void 0&&clearTimeout(y),_!==void 0&&clearTimeout(_),f()}})}function Ql(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",On)),t.write(u,a=>{a||(s+=u.byteLength,qi(e,s))}),t.writableLength>Mi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Mi} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[ht];if(typeof a=="string"){if(!Di(a))throw Fi(a);t.addTrailers({[On]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function Zl(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Qe(s,r)}return o?!0:(Dr(n,new N(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 ed={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},td="wav, pcm";async function ji(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??Vl,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${jt}`);let u;try{u=JSON.parse((await Rn(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof oe?new N(413,g.message):new N(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new N(400,"request body must be a JSON object");let a=u;for(let g of Object.keys(a))if(!ed[g])throw new N(400,`request field "${g}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,g);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new N(400,"input is required and must be a non-empty string","input");if(l.length>Oi)throw new N(400,`input is ${l.length} chars \u2014 over the ${Oi}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new N(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new N(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new N(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 ${jt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(g){throw Qe(g,r)}if(p.defect!==null)throw new N(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 m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new N(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=a.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new N(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${td} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new N(400,"stream_format, when present, must be a string","stream_format");let v=a.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new N(400,"speed, when present, must be a number","speed");if(v!==1)throw new N(400,`speed=${JSON.stringify(v)} 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 k=a.instructions;if(k!==void 0){if(typeof k!="string")throw new N(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new N(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 Jl(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",b,b),!await Zl(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new N(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new N(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new N(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 w;try{w=await n.clients.speechSessionHandle(d)}catch(g){throw Qe(g,r)}let f;try{f=await n.clients.openAudioOn(w)}catch(g){throw Qe(g,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(h==="wav"){let g=[],y=await Ni(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ti,returnBoundMs:n.turnReturnBoundMs??Pi},i,S=>g.push(S),S=>{n.turn&&(n.turn.outputSeconds=Pe(S))},r);if(y===null||i())return;let _=Buffer.concat(g);if(m===void 0){let S=y[ht];if(typeof S=="string"){if(!Di(S))throw Fi(S);e.setHeader(On,S)}}qi(n.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([zl(_.byteLength),_]))}else{let g=Ql(e,n.turn,i,m===void 0),y;try{y=await Ni(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ti,returnBoundMs:n.turnReturnBoundMs??Pi},i,g.sink,_=>{n.turn&&(n.turn.outputSeconds=Pe(_))},r)}catch(_){let S=Qe(_,r);if(!g.started())throw S;n.turn&&(n.turn.streamError=!0),g.fail(S);return}if(y===null)return;try{await g.finish(y)}catch(_){let S=Qe(_,r);n.turn&&(n.turn.streamError=!0),g.fail(S);return}}}catch(g){throw Qe(g,r)}}catch(u){if(u instanceof oe){Dr(e,new N(413,u.message));return}if(u instanceof N){Dr(e,u);return}throw u}}var Pn="/v1/audio/transcriptions";function Bi(t){return t===Pn}var Hi="/v1/audio/models",nd=16*1024*1024,rd=64*1024*1024,X=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Fr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Gi(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function od(t){if(!Gi(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function sd(t,e,n){if(t){if(t.model=ae({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function id(t,e){t&&(t.outputUnits=e.seconds)}async function ad(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Se(p.message)?p.message:null;throw h===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new X(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new X(m==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new X(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Pe(d)),lt(l,d)}function Vi(t,e){if(t instanceof X)return t;if(t instanceof Ie)throw t;return t instanceof F?new X(404,t.message):new X(502,ct("transcription",t,e))}async function ud(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Vi(s,r)}return o?!0:(Fr(n,new X(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 ld=new Set(["file","model","language","response_format"]);async function Ji(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??rd,s=n.maxAudioPartBytes??nd;try{if(t.method!=="POST")throw new X(405,`${String(t.method)} is not supported on ${Pn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new X(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await En(t,o)}catch(w){throw w instanceof oe?new X(413,w.message):new X(400,String(w instanceof Error?w.message:w))}let a=new Map;for(let w of u.keys()){if(!ld.has(w))throw new X(400,`form field "${w}" 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.`,w);a.set(w,(a.get(w)??0)+1)}for(let[w,f]of a)if(f>1)throw new X(400,`form field "${w}" appears ${f} 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`,w);let l=u.get("model");if(l!==null&&typeof l!="string")throw new X(400,"model must be a string field","model");let d=l===null?void 0:l,c=u.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new X(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=u.get("response_format")??"json";if(m!=="json")throw new X(400,`response_format ${JSON.stringify(m)} 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 h=u.get("file");if(!(h instanceof File))throw new X(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new X(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await h.arrayBuffer());if(!Gi(v))throw new X(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 k=od(v);if(k===null)throw new X(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 sd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await ud(n.transcriptionModels,d,e,r))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let w=await ad(n.clients,d,b,p,n.turn?ge(n.turn):void 0,n.turn,r);id(n.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:w}))}catch(w){throw Vi(w,r)}}catch(i){if(i instanceof oe){Fr(e,new X(413,i.message));return}if(i instanceof X){Fr(e,i);return}throw i}}var Ki="/v1/usage/requests",Wi=1e4,dd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},yt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var zi=1024*1024;function qr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>Wi)throw new qe(`"${e}" carries ${n.length} ids; at most ${Wi} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!dd.test(s))throw new qe(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function Yi(t){return qr(t,"inference_ids")}function Cn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new yt(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new yt(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var Nn=require("@urun-sh/core");var jr="/partners/huggingface/v1/billing/requests";function cd(t){return qr(t,"requestIds")}function pd(t){return t>=200&&t<=399}function fd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&pd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Xi(t,e){let n=cd(t),r=await e(n);return Cn(r,n),fd(r)}var md={"/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 gd(t){return md[t]??null}var ta=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function hd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function yd(t){return t==="surface"}function wd(t){let e=t?.ledgerFailureReason;return ta.includes(e)?e:"unknown"}var _d=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Qi=["priced","unpriced"],vd={written:Qi,already_written:Qi,skipped:_d,failed:ta},$m=Object.entries(vd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function bd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Sd(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var kd=256,Zi=4096,Ht=12e4,xd=250,Rd=8e3,Gt=[],ea=new Set,Vt=0,Bt=!1;var Ed=new Set;function Ad(){return Vt===0&&Gt.length===0}function Id(){if(Ad()){Bt=!1;for(let t of[...Ed])t()}}function na(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
36
- `}function Od(t){xe(process.stdout,t)}function ra(t,e){try{t(e)}catch{}}function oa(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Od,o=gd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ra(r,na("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 u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:Sd(e),completed_at:e.ts,billable_outcome:bd(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(Gt.length>=Zi){i("queue_full",`${Gt.length} ledger writes are already waiting (capacity ${Zi}, ${Vt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Gt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Vt<kd&&(Vt+=1,Td())}async function Td(){try{for(;;){let t=Pd();if(t===void 0)return;ea.add(t);try{await Cd(t)}finally{ea.delete(t)}}}finally{Vt-=1,Id()}}function Pd(){let t=Date.now();for(;;){let e=Gt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Ht)return e;wt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Ht}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Cd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);wt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=hd(o);if(s!==null){wt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=wd(o),u=Date.now()-t.queuedAt;if(Bt){wt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(yd(i)&&u<Ht){if(await Md($d(t.attempts)),Bt||Date.now()-t.queuedAt>=Ht){let a=Date.now()-t.queuedAt;wt(t,{outcome:"failed",reason:Bt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Bt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Ht}ms dwell bound (waited ${a}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}wt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function $d(t){return Math.min(Rd,xd*2**Math.max(0,t-1))}function Md(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function wt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ra(t.report,na(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Gr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ld(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function se(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){se(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Vr(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),u=i??ke(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),se(t,l,{error:{message:u,type:o,code:a}})}function Re(t,e,n,r){se(t,e,{type:"error",error:{type:n,message:r}})}function _t(t,e,n){if(e==="anthropic"){se(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}se(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Nd=64*1024*1024,Jt=class extends Error{};async function sa(t,e=Nd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Jt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ze(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function ua(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function $n(t){let e=ua(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ia(t){let e=$n(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Ud(t)},completion_tokens_details:{reasoning_tokens:0}}}function Ud(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Dd(t,e){let n=ua(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Fd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function qd(t,e){let n=Fd(e);n&&(t.timing=n),t.outputSeconds=Pe(e)}function et(t,e){Dd(t,e),qd(t,e)}async function Un(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function la(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function jd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Mn=class extends Error{};function Bd(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Mn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Hd(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Bd(n.role,n.content)})}return e}function Br(t){return at(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Gd(t,e,n,r,o,s,i){let u=$t(s.id),a=t.stream===!0;if(s.model=ae(t),s.stream=a,await Un(s,e,typeof t.model=="string"?t.model:void 0),a){let w;try{w=await Lt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(f){if(f instanceof F){_t(r,"openai",f);return}if(f instanceof he){J(r,f.status,f.message);return}if(f instanceof _e||f instanceof ce){r.setHeader("retry-after","2"),J(r,503,f.message,"capacity_error");return}throw f}Gr(r);for await(let f of w.events){if(f.type==="error"){s.streamError=!0;let g=f.error,y=Oe(g),_=y??ke(s.id);y===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(f)}`),r.write(`event: error
37
- data: ${JSON.stringify({error:{message:_,type:g?.type??"upstream_error",code:g?.code??null}})}
36
+ `)}function Si(t,e){if(!se(e))throw new we("decision answer was not a JSON object");let n=e.answers;if(!se(n))throw new we("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!se(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=se(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=jr(s.noul);if(u===null)throw new we(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new we(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new we(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=An(s.confidence);if(d===null)throw new we(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=jr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=An(s.score);if(a===null)throw new we(`the score answer for "${o.key}" carries no numeric score to translate`);let l=An(s.confidence);if(l===null)throw new we(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=jr(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var ie=class extends Error{};async function In(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function On(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ki="/v1/images/generations",Tn="/v1/images/edits";function xi(t){return t===ki||t===Tn}var Ri="/v1/images/models";async function Ei(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var j=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ql=16*1024*1024,Ai=64*1024*1024;function Ii(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function jt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Oi(t,e,n,r,o,s){let i=s??(g=>console.error(g)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let g of u){if(g.type==="error"){let v=g.error??{},x=typeof v.message=="string"&&v.message.length>0&&ke(v.message)?v.message:null;throw x===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new j(502,"the image upstream failed while serving this request")):new j(502,`image upstream error: ${x}`)}if(g.type==="response.completed"){a=g.response??null;break}}if(a===null)throw new j(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ce(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new j(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(Ii(p)===null)throw new j(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 Ti(t,e){if(t instanceof j)return t;if(t instanceof Oe)throw t;return t instanceof G?new j(404,t.message):new j(502,ct("image",t,e))}async function Pi(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return jt(r,new j(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ci(t,e){t&&(t.outputUnits=e.images.length)}function Mi(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Zl={model:!0,prompt:!0,response_format:!0,n:!0};async function $i(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ai;try{if(t.method!=="POST")throw new j(405,`${String(t.method)} is not supported on ${ki}`);let s;try{s=JSON.parse((await In(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new j(413,p.message):new j(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new j(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Zl[p])throw new j(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 u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new j(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new j(400,"model must be a string","model");await Ei(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new j(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 j(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",u.length,u.length),!await Pi(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Oi(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Ci(n.turn,p),Mi(e,p)}catch(p){throw Ti(p,r)}}catch(s){if(s instanceof ie){jt(e,new j(413,s.message));return}if(s instanceof j){jt(e,s);return}throw s}}var ed={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Li(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ai,s=n.maxImagePartBytes??Ql;try{if(t.method!=="POST")throw new j(405,`${String(t.method)} is not supported on ${Tn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new j(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await On(t,o)}catch(g){throw g instanceof ie?new j(413,g.message):new j(400,String(g instanceof Error?g.message:g))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new j(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new j(400,"model must be a string field","model");let d=l===null?void 0:l;await Ei(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new j(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 g of u.keys())if(!ed[g])throw new j(400,`form field "${g}" 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[]).`,g);let p=[];for(let g of["image","image[]"])for(let v of u.getAll(g)){if(!(v instanceof File))throw new j(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(v.size>s)throw new j(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let x=new Uint8Array(await v.arrayBuffer()),S=Ii(x);if(S===null)throw new j(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:x,mime:S})}if(p.length===0)throw new j(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Pi(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:g,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(g).toString("base64")}`});try{let g=await Oi(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Ci(n.turn,g),Mi(e,g)}catch(g){throw Ti(g,r)}}catch(i){if(i instanceof ie){jt(e,new j(413,i.message));return}if(i instanceof j){jt(e,i);return}throw i}}var Ht="/v1/audio/speech";function Gi(t){return t===Ht}var Ni=4096,Ui=18e4,Di=5e3,td=64*1024*1024,Fi=8,qi=5,Bi=1024*1024,ht="voice_applied",Cn="X-Urun-Voice-Applied",D=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Hr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Mn=class extends D{constructor(e){super(502,e)}};function Vi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ji(t){return new D(502,`the runtime's ${ht} receipt ${JSON.stringify(t)} cannot be relayed as the ${Cn} 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 nd(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Wi(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var rd=2;function od(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>rd)return!1;return!0}function sd(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var ji=new WeakMap,Pn=new WeakMap;function id(t,e){let n=Pn.get(t)??0;if(n>=Fi)throw new D(503,`this model's speech queue is full \u2014 ${Fi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${qi}s`,void 0,qi);Pn.set(t,n+1);let r=ji.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return ji.set(t,s),(async()=>{await r;try{return await e()}finally{Pn.set(t,(Pn.get(t)??1)-1),o()}})()}async function ad(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new D(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof V))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{clearTimeout(s)})}function Qe(t,e){if(t instanceof D)return t;if(t instanceof Oe)throw t;return t instanceof G?new D(404,t.message):new D(502,ct("speech",t,e))}async function Hi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return id(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,v,x=new Promise(E=>{v=E}),S=[],w,f=!1,h=null,y=()=>{h!==null&&(clearTimeout(w),w=setTimeout(()=>{f=!0,h?.()},o.capMs))},b=()=>{m&&!g&&S.length>=o.quietRunFrames&&(g=!0,v())},R=e.onOutputAudio(E=>{let k=Buffer.from(E,"base64");if(k.byteLength===0)return;y();let M=od(k);if(!p){if(M)return;p=!0}if(M){S.push(k),b();return}for(let q of S)c(q);S.length=0,c(k),b()}),A=null,O,_;try{_=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let k=()=>(clearTimeout(O),new Promise(N=>{O=setTimeout(N,s.capMs)})),M=k(),q=!1;for(;;){let N=_.next(),U=await Promise.race([N,M]);if(U===void 0){q=!0,N.catch(()=>{});break}if(U.done)break;let oe=U.value;if(M=k(),oe.type==="error"){let J=oe.error??{};await _.return?.();let ne=typeof J.message=="string"&&J.message.length>0&&ke(J.message)?J.message:null;throw ne===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(oe)}`),new D(502,"the speech upstream failed while serving this request")):new D(502,`speech upstream error: ${ne}`)}if(oe.type==="response.completed"){A=oe.response??null,m=!0,a?.(A),b(),await _.return?.();break}}if(clearTimeout(O),q)throw new D(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(A===null)throw new D(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let B=new Promise(N=>{h=N});if(y(),await Promise.race([x,B]),clearTimeout(w),w=void 0,h=null,r.voice!==void 0){let N=A[ht];if(typeof N!="string"||N!==r.voice){let U=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof N=="string"?`${ht} ${JSON.stringify(N)}`:`no ${ht} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Mn(U):new D(502,U)}}if(!p)throw new D(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(f&&!g&&S.length<1)throw new D(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return A}catch(E){throw E instanceof Mn||await ad(t,n,_,s.returnBoundMs),E}finally{clearTimeout(w),clearTimeout(O),R()}})}function ud(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Cn)),t.write(u,a=>{a||(s+=u.byteLength,Wi(e,s))}),t.writableLength>Bi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Bi} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[ht];if(typeof a=="string"){if(!Vi(a))throw Ji(a);t.addTrailers({[Cn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function ld(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Qe(s,r)}return o?!0:(Hr(n,new D(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 dd={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},cd="wav, pcm";async function Ki(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??td,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${Ht}`);let u;try{u=JSON.parse((await In(t,o)).toString("utf8")||"{}")}catch(h){throw h instanceof ie?new D(413,h.message):new D(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new D(400,"request body must be a JSON object");let a=u;for(let h of Object.keys(a))if(!dd[h])throw new D(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new D(400,"input is required and must be a non-empty string","input");if(l.length>Ni)throw new D(400,`input is ${l.length} chars \u2014 over the ${Ni}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new D(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new D(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new D(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 ${Ht} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(h){throw Qe(h,r)}if(p.defect!==null)throw new D(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 m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new D(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=a.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new D(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${cd} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new D(400,"stream_format, when present, must be a string","stream_format");let v=a.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new D(400,"speed, when present, must be a number","speed");if(v!==1)throw new D(400,`speed=${JSON.stringify(v)} 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 x=a.instructions;if(x!==void 0){if(typeof x!="string")throw new D(400,"instructions, when present, must be a string","instructions");if(x.trim().length>0)throw new D(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 nd(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await ld(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new D(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new D(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new D(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 w;try{w=await n.clients.speechSessionHandle(d)}catch(h){throw Qe(h,r)}let f;try{f=await n.clients.openAudioOn(w)}catch(h){throw Qe(h,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(g==="wav"){let h=[],y=await Hi(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ui,returnBoundMs:n.turnReturnBoundMs??Di},i,R=>h.push(R),R=>{n.turn&&(n.turn.outputSeconds=Ce(R))},r);if(y===null||i())return;let b=Buffer.concat(h);if(m===void 0){let R=y[ht];if(typeof R=="string"){if(!Vi(R))throw Ji(R);e.setHeader(Cn,R)}}Wi(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([sd(b.byteLength),b]))}else{let h=ud(e,n.turn,i,m===void 0),y;try{y=await Hi(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ui,returnBoundMs:n.turnReturnBoundMs??Di},i,h.sink,b=>{n.turn&&(n.turn.outputSeconds=Ce(b))},r)}catch(b){let R=Qe(b,r);if(!h.started())throw R;n.turn&&(n.turn.streamError=!0),h.fail(R);return}if(y===null)return;try{await h.finish(y)}catch(b){let R=Qe(b,r);n.turn&&(n.turn.streamError=!0),h.fail(R);return}}}catch(h){throw Qe(h,r)}}catch(u){if(u instanceof ie){Hr(e,new D(413,u.message));return}if(u instanceof D){Hr(e,u);return}throw u}}var $n="/v1/audio/transcriptions";function zi(t){return t===$n}var Yi="/v1/audio/models",pd=16*1024*1024,fd=64*1024*1024,Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Gr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Xi(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function md(t){if(!Xi(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function gd(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function hd(t,e){t&&(t.outputUnits=e.seconds)}async function yd(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&ke(p.message)?p.message:null;throw g===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Z(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Z(m==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}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 s&&(s.outputSeconds=Ce(d)),lt(l,d)}function Qi(t,e){if(t instanceof Z)return t;if(t instanceof Oe)throw t;return t instanceof G?new Z(404,t.message):new Z(502,ct("transcription",t,e))}async function wd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Qi(s,r)}return o?!0:(Gr(n,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 _d=new Set(["file","model","language","response_format"]);async function Zi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??fd,s=n.maxAudioPartBytes??pd;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.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 u;try{u=await On(t,o)}catch(w){throw w instanceof ie?new Z(413,w.message):new Z(400,String(w instanceof Error?w.message:w))}let a=new Map;for(let w of u.keys()){if(!_d.has(w))throw new Z(400,`form field "${w}" 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.`,w);a.set(w,(a.get(w)??0)+1)}for(let[w,f]of a)if(f>1)throw new Z(400,`form field "${w}" appears ${f} 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`,w);let l=u.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=u.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,m=u.get("response_format")??"json";if(m!=="json")throw new Z(400,`response_format ${JSON.stringify(m)} 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 g=u.get("file");if(!(g 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(g.size>s)throw new Z(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await g.arrayBuffer());if(!Xi(v))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 x=md(v);if(x===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 gd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await wd(n.transcriptionModels,d,e,r))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let w=await yd(n.clients,d,S,p,n.turn?he(n.turn):void 0,n.turn,r);hd(n.turn,x),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:w}))}catch(w){throw Qi(w,r)}}catch(i){if(i instanceof ie){Gr(e,new Z(413,i.message));return}if(i instanceof Z){Gr(e,i);return}throw i}}var ta="/v1/usage/requests",ea=1e4,vd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},yt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var na=1024*1024;function Vr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>ea)throw new qe(`"${e}" carries ${n.length} ids; at most ${ea} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!vd.test(s))throw new qe(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ra(t){return Vr(t,"inference_ids")}function Ln(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new yt(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new yt(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var Fn=require("@urun-sh/core");var Jr="/partners/huggingface/v1/billing/requests";function bd(t){return Vr(t,"requestIds")}function Sd(t){return t>=200&&t<=399}function kd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Sd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function oa(t,e){let n=bd(t),r=await e(n);return Ln(r,n),kd(r)}var xd={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Rd(t){return xd[t]??null}var ua=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ed(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ad(t){return t==="surface"}function Id(t){let e=t?.ledgerFailureReason;return ua.includes(e)?e:"unknown"}var Od=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],sa=["priced","unpriced"],Td={written:sa,already_written:sa,skipped:Od,failed:ua},Jm=Object.entries(Td).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Pd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Cd(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Md=256,ia=4096,Vt=12e4,$d=250,Ld=8e3,Jt=[],aa=new Set,Wt=0,Gt=!1;var Nd=new Set;function Ud(){return Wt===0&&Jt.length===0}function Dd(){if(Ud()){Gt=!1;for(let t of[...Nd])t()}}function la(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
37
+ `}function Fd(t){Re(process.stdout,t)}function da(t,e){try{t(e)}catch{}}function ca(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Fd,o=Rd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),da(r,la("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 u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:Cd(e),completed_at:e.ts,billable_outcome:Pd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Jt.length>=ia){i("queue_full",`${Jt.length} ledger writes are already waiting (capacity ${ia}, ${Wt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Jt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Wt<Md&&(Wt+=1,qd())}async function qd(){try{for(;;){let t=Bd();if(t===void 0)return;aa.add(t);try{await jd(t)}finally{aa.delete(t)}}}finally{Wt-=1,Dd()}}function Bd(){let t=Date.now();for(;;){let e=Jt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Vt)return e;wt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Vt}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 jd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);wt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Ed(o);if(s!==null){wt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Id(o),u=Date.now()-t.queuedAt;if(Gt){wt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Ad(i)&&u<Vt){if(await Gd(Hd(t.attempts)),Gt||Date.now()-t.queuedAt>=Vt){let a=Date.now()-t.queuedAt;wt(t,{outcome:"failed",reason:Gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Vt}ms dwell bound (waited ${a}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}wt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Hd(t){return Math.min(Ld,$d*2**Math.max(0,t-1))}function Gd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function wt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;da(t.report,la(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function zr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Vd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Yr(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Te(r),u=i??xe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ae(t,l,{error:{message:u,type:o,code:a}})}function Ee(t,e,n,r){ae(t,e,{type:"error",error:{type:n,message:r}})}function _t(t,e,n){if(e==="anthropic"){ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Jd=64*1024*1024,Kt=class extends Error{};async function pa(t,e=Jd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Kt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ze(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function ga(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function Nn(t){let e=ga(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function fa(t){let e=Nn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Wd(t)},completion_tokens_details:{reasoning_tokens:0}}}function Wd(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Kd(t,e){let n=ga(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function zd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function Yd(t,e){let n=zd(e);n&&(t.timing=n),t.outputSeconds=Ce(e)}function et(t,e){Kd(t,e),Yd(t,e)}async function qn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ha(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Xd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Un=class extends Error{};function Qd(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Un(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Zd(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Qd(n.role,n.content)})}return e}function Wr(t){return at(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function ec(t,e,n,r,o,s,i){let u=$t(s.id),a=t.stream===!0;if(s.model=ue(t),s.stream=a,await qn(s,e,typeof t.model=="string"?t.model:void 0),a){let w;try{w=await Nt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(f){if(f instanceof G){_t(r,"openai",f);return}if(f instanceof ye){K(r,f.status,f.message);return}if(f instanceof ve||f instanceof pe){r.setHeader("retry-after","2"),K(r,503,f.message,"capacity_error");return}throw f}zr(r);for await(let f of w.events){if(f.type==="error"){s.streamError=!0;let h=f.error,y=Te(h),b=y??xe(s.id);y===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(f)}`),r.write(`event: error
38
+ data: ${JSON.stringify({error:{message:b,type:h?.type??"upstream_error",code:h?.code??null}})}
38
39
 
39
40
  `),r.end();return}f.type==="response.completed"&&et(s,f.response),r.write(`event: ${String(f.type??"message")}
40
41
  data: ${JSON.stringify(f)}
41
42
 
42
43
  `)}r.write(`data: [DONE]
43
44
 
44
- `),r.end();return}let l;try{l=dt(n,t)}catch(w){if(w instanceof he){J(r,w.status,w.message);return}throw w}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ae(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await fr(e,t,l,!1,ge(s))}catch(w){if(w instanceof F){_t(r,"openai",w);return}if(w instanceof he){J(r,w.status,w.message);return}if(w instanceof _e||w instanceof ce){r.setHeader("retry-after","2"),J(r,503,w.message,"capacity_error");return}throw w}let h=[],v=null;for await(let w of o.track(m,c,s)){if(h.push(w),w.type==="error"){Vr(r,w,{inferenceId:s.id,operatorError:i});return}w.type==="response.completed"&&(v=w.response)}if(v==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}et(s,v);let k=lt(h,v),b=Ye(p,at(v).length,k);if(b){J(r,502,ze(c,b),"upstream_error");return}d&&n.remember(u,l,pr(v,k),d),se(r,200,{...v,id:u})}async function Vd(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){J(n,400,"chat/completions requires a messages array");return}let a;try{a=ai(s,t)}catch(E){if(E instanceof le){J(n,E.status,E.message);return}throw E}let l=String(t.model??"urun"),d=Ss(o.id),c;try{c=Hd(u)}catch(E){if(E instanceof Mn){J(n,400,E.message);return}throw E}let p=ae(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:jd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},ge(o))}catch(E){if(E instanceof F){_t(n,"openai",E);return}if(E instanceof _e||E instanceof ce){n.setHeader("retry-after","2"),J(n,503,E.message,"capacity_error");return}throw E}if(t.stream===!0){a?Ld(n):Gr(n);let E=[],O=new De,x="",$=a?new mt(a,q=>{n.write(`data: ${JSON.stringify(Ze(d,l,{content:q},null))}
45
+ `),r.end();return}let l;try{l=dt(n,t)}catch(w){if(w instanceof ye){K(r,w.status,w.message);return}throw w}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ue(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await wr(e,t,l,!1,he(s))}catch(w){if(w instanceof G){_t(r,"openai",w);return}if(w instanceof ye){K(r,w.status,w.message);return}if(w instanceof ve||w instanceof pe){r.setHeader("retry-after","2"),K(r,503,w.message,"capacity_error");return}throw w}let g=[],v=null;for await(let w of o.track(m,c,s)){if(g.push(w),w.type==="error"){Yr(r,w,{inferenceId:s.id,operatorError:i});return}w.type==="response.completed"&&(v=w.response)}if(v==null){K(r,502,"upstream produced no response.completed event","upstream_error");return}et(s,v);let x=lt(g,v),S=Ye(p,at(v).length,x);if(S){K(r,502,ze(c,S),"upstream_error");return}d&&n.remember(u,l,yr(v,x),d),ae(r,200,{...v,id:u})}async function tc(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){K(n,400,"chat/completions requires a messages array");return}let a;try{a=mi(s,t)}catch(_){if(_ instanceof de){K(n,_.status,_.message);return}throw _}let l=String(t.model??"urun"),d=Is(o.id),c;try{c=Zd(u)}catch(_){if(_ instanceof Un){K(n,400,_.message);return}throw _}let p=ue(t);r.model(p),o.model=p,o.stream=t.stream===!0,await qn(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:c,stream:!0,tools:Xd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},he(o))}catch(_){if(_ instanceof G){_t(n,"openai",_);return}if(_ instanceof ve||_ instanceof pe){n.setHeader("retry-after","2"),K(n,503,_.message,"capacity_error");return}throw _}if(t.stream===!0){a?Vd(n):zr(n);let _=[],E=new De,k="",M=a?new mt(a,B=>{n.write(`data: ${JSON.stringify(Ze(d,l,{content:B},null))}
45
46
 
46
- `)}):null,B=q=>{$?.flush(),n.write(q),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
47
+ `)}):null,q=B=>{M?.flush(),n.write(B),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
47
48
 
48
49
  `),n.write(`data: ${JSON.stringify(Ze(d,l,{role:"assistant"},null))}
49
50
 
50
- `);for await(let Z of r.track(h,p,o)){E.push(Z);let ie=ut(Z);if(Z.type==="response.output_text.delta"&&typeof Z.delta=="string")x+=Z.delta,$?$.push(Z.delta):n.write(`data: ${JSON.stringify(Ze(d,l,{content:Z.delta},null))}
51
+ `);for await(let J of r.track(g,p,o)){_.push(J);let ne=ut(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")k+=J.delta,M?M.push(J.delta):n.write(`data: ${JSON.stringify(Ze(d,l,{content:J.delta},null))}
51
52
 
52
- `);else if(Z.type==="response.reasoning_text.delta"&&typeof Z.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Ze(d,l,{reasoning_content:Z.delta},null))}
53
+ `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Ze(d,l,{reasoning_content:J.delta},null))}
53
54
 
54
- `);else if(ie){$?.flush();let{call:L,isNew:H}=O.add(ie),W=H?{index:ie.tool_index,id:L.id??`call_${ie.tool_index}`,type:"function",function:{name:L.name??"",arguments:ie.delta}}:{index:ie.tool_index,function:{arguments:ie.delta}};n.write(`data: ${JSON.stringify(Ze(d,l,{tool_calls:[W]},null))}
55
+ `);else if(ne){M?.flush();let{call:$,isNew:H}=E.add(ne),z=H?{index:ne.tool_index,id:$.id??`call_${ne.tool_index}`,type:"function",function:{name:$.name??"",arguments:ne.delta}}:{index:ne.tool_index,function:{arguments:ne.delta}};n.write(`data: ${JSON.stringify(Ze(d,l,{tool_calls:[z]},null))}
55
56
 
56
- `)}else if(Z.type==="error"){o.streamError=!0;let L=Z.error??{},H=Oe(L),W=H??ke(o.id);H===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Z)}`),B(`data: ${JSON.stringify({error:{message:W,type:L.type??"upstream_error",code:L.code??null}})}
57
+ `)}else if(J.type==="error"){o.streamError=!0;let $=J.error??{},H=Te($),z=H??xe(o.id);H===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(J)}`),q(`data: ${JSON.stringify({error:{message:z,type:$.type??"upstream_error",code:$.code??null}})}
57
58
 
58
- `);return}}let q=Br(Ae(E)),Q=Ye(m,O.size+q.length,x);if(Q){o.streamError=!0,B(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(p,Q)}})}
59
+ `);return}}let B=Wr(Ie(_)),N=Ye(m,E.size+B.length,k);if(N){o.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(p,N)}})}
59
60
 
60
- `);return}$?.flush(),O.size===0&&q.length>0&&n.write(`data: ${JSON.stringify(Ze(d,l,{tool_calls:q},null))}
61
+ `);return}M?.flush(),E.size===0&&B.length>0&&n.write(`data: ${JSON.stringify(Ze(d,l,{tool_calls:B},null))}
61
62
 
62
- `);let V=O.size>0||q.length>0;n.write(`data: ${JSON.stringify(Ze(d,l,{},V?"tool_calls":"stop"))}
63
+ `);let U=E.size>0||B.length>0;n.write(`data: ${JSON.stringify(Ze(d,l,{},U?"tool_calls":"stop"))}
63
64
 
64
- `);let $e=$n(Ae(E));et(o,Ae(E)),$e&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:ia(Ae(E))})}
65
+ `);let oe=Nn(Ie(_));et(o,Ie(_)),oe&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:fa(Ie(_))})}
65
66
 
66
67
  `),n.write(`data: [DONE]
67
68
 
68
- `),n.end();return}finally{$?.flush(),$?.dispose()}}let v="",k="",b=[],w=new De;for await(let E of r.track(h,p,o)){b.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(v+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(k+=E.delta);let O=ut(E);if(O&&w.add(O),E.type==="error"){Vr(n,E,{inferenceId:o.id,operatorError:i});return}}let f=Ae(b);et(o,f);let g=Br(f),y=g.length>0?g:Br({output:w.items()}),_=Ye(m,y.length,v);if(_){J(n,502,ze(p,_),"upstream_error");return}let S=y.map(({index:E,...O})=>O),R={role:"assistant",content:v||null},I=k||la(f);I&&(R.reasoning_content=I),S.length>0&&(R.tool_calls=S),se(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:R,finish_reason:S.length>0?"tool_calls":"stop"}],usage:ia(f)})}var da="sense-latest";async function Jd(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:da,u=ae({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){J(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}let l=await ca(t,i,u,e,n,r,o,s);l!==null&&se(n,200,l.answer)}async function ca(t,e,n,r,o,s,i,u){let a={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=a;let l=performance.now();s.model(n),await Un(i,r,e),a.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(t)}],stream:!0},ge(i))}catch(b){if(b instanceof F)return _t(o,"openai",b),null;if(b instanceof _e||b instanceof ce)return o.setHeader("retry-after","2"),J(o,503,b.message,"capacity_error"),null;throw b}a.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let b of s.track(d,n,i))if(m===null&&(m=performance.now(),a.first_event_ms=Math.round(m-c)),p.push(b),b.type==="error")return Vr(o,b,{inferenceId:i.id,operatorError:u}),null}catch(b){if(b instanceof F)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),_t(o,"openai",b),null;if(b instanceof _e||b instanceof ce)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),J(o,503,b.message,"capacity_error"),null;throw m!==null&&(a.stream_ms=Math.round(performance.now()-m)),b}m!==null&&(a.stream_ms=Math.round(performance.now()-m));let h=Ae(p);if(h==null)return J(o,502,"upstream produced no response.completed event","upstream_error"),null;et(i,h);let v=lt(p,h),k;try{k=JSON.parse(v)}catch{return J(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return J(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let b=k.timing;if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"question_fwd_ms"in b&&"head_ms"in b){let w=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;a.question_fwd_ms=w(b.question_fwd_ms),a.head_ms=w(b.head_ms)}}return{answer:k,completed:h}}async function Wd(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:da,u=ae({model:i});o.model=u,o.stream=!1;let a;try{a=pi(t,i)}catch(p){if(p instanceof M){J(n,400,p.message);return}throw p}let l=await ca(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=gi(a.specs,l.answer)}catch(p){if(p instanceof ye){J(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;se(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function Kd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Wt=class extends Error{};function Ln(t){return new Wt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function zd(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function Yd(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Wt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Xd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ln(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ln(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Qd(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Ln(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Xd(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw Ln(u)}}return s(),r}function Hr(t){return at(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function Zd(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Re(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){Re(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Re(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(R=>typeof R!="string"))){Re(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=ks(o.id),l=[],d;try{t.system&&l.push({role:"system",content:Kd(t.system)});for(let R of i)l.push(...Qd(R));d=Yd(t.tool_choice)}catch(R){if(R instanceof Wt){Re(n,400,"invalid_request_error",R.message);return}throw R}let c=ae(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:zd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ge(o))}catch(R){if(R instanceof F){_t(n,"anthropic",R);return}if(R instanceof _e||R instanceof ce){n.setHeader("retry-after","2"),Re(n,503,"capacity_error",R.message);return}throw R}let h=(R,I)=>{n.destroyed||n.write(`event: ${R}
69
- data: ${JSON.stringify({type:R,...I})}
70
-
71
- `)};if(t.stream===!0){let R=r.track(m,c,o);Gr(n),h("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let I=0,E="",O=0,x="none",$=()=>x,B=-1,q=-1,Q=new De,V=[],$e=()=>{x!=="none"&&(x="none",h("content_block_stop",{index:B}))},Z=(K,ee)=>{$e(),x=K,B=O++,h("content_block_start",{index:B,content_block:ee})};for await(let K of R){if(n.destroyed)break;V.push(K);let ee=ut(K);if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")$()!=="thinking"&&Z("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:B,delta:{type:"thinking_delta",thinking:K.delta}});else if(K.type==="response.output_text.delta"&&typeof K.delta=="string")$()!=="text"&&Z("text",{type:"text",text:""}),I+=1,E+=K.delta,h("content_block_delta",{index:B,delta:{type:"text_delta",text:K.delta}});else if(ee){let{call:we}=Q.add(ee);($()!=="tool"||ee.tool_index!==q)&&(q=ee.tool_index,Z("tool",{type:"tool_use",id:we.id??`call_${ee.tool_index}`,name:we.name??"",input:{}})),ee.delta&&h("content_block_delta",{index:B,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(K.type==="error"){o.streamError=!0;let we=K.error,Be=Oe(we);Be===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(K)}`),h("error",{error:{type:"api_error",message:Be??ke(o.id)}}),n.end();return}}if(n.destroyed)return;let ie=Ae(V),L=at(ie),H=Ye(p,Q.size+L.length,E);if(H){o.streamError=!0,h("error",{error:{type:"api_error",message:ze(c,H)}}),n.end();return}$e();let W=[];if(Q.size===0)try{W=Hr(ie)}catch(K){o.streamError=!0;let ee=pe(K,{inferenceId:o.id});ee.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(K instanceof Error?K.message:K)}`),h("error",{error:{type:"api_error",message:ee.message}}),n.end();return}O===0&&W.length===0&&(Z("text",{type:"text",text:""}),$e()),W.forEach(K=>{let ee=O++;h("content_block_start",{index:ee,content_block:{...K,input:{}}}),h("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(K.input??{})}}),h("content_block_stop",{index:ee})});let je=Q.size>0||W.length>0,tt=$n(ie);et(o,ie),h("message_delta",{delta:{stop_reason:je?"tool_use":"end_turn"},usage:tt?{input_tokens:tt.input_tokens,output_tokens:tt.output_tokens}:{output_tokens:I}}),h("message_stop",{}),n.end();return}let v="",k="",b=[],w=new De;for await(let R of r.track(m,c,o)){b.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(v+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(k+=R.delta);let I=ut(R);if(I&&w.add(I),R.type==="error"){let E=R.error,O=E?.type==="invalid_request_error",x=Oe(E);x===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),Re(n,O?400:502,O?"invalid_request_error":"api_error",x??ke(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Ae(b);et(o,f);let g;try{g=Hr(f),g.length===0&&w.size>0&&(g=Hr({output:w.items()}))}catch(R){let I=pe(R,{inferenceId:o.id});I.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),Re(n,502,"api_error",I.message);return}let y=Ye(p,g.length,v);if(y){Re(n,502,"api_error",ze(c,y));return}let _=[],S=k||la(f);S&&_.push({type:"thinking",thinking:S}),(v||g.length===0)&&_.push({type:"text",text:v}),_.push(...g),se(n,200,{id:a,type:"message",role:"assistant",content:_,model:u,stop_reason:g.length>0?"tool_use":"end_turn",usage:$n(f)??{input_tokens:0,output_tokens:0}})}function ec(t){xe(process.stdout,t)}function tc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??ec,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new We;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(f,g,y,_,S)=>m?Re(c,f,_,g):J(c,f,g,y,S),v=cr(p.pathname),k=p.pathname.startsWith("/partners/"),b=v||k?{id:Ct(),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;b&&(c.setHeader(vs,b.id),c.once("close",()=>{let f=xs({turn:b,method:d.method??"",path:p.pathname,res:c});i(Rs(f)),a?.(f),oa({record:f,ledger:t.ledger??null,req:d})}));let w=()=>bs(p.pathname,b);(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(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===Ki?"canonical":p.pathname===jr?"huggingface":null;if(f){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let S=t.usage;if(!S){h(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=S.authorize(d),I;try{I=await sa(d,zi)}catch(x){if(x instanceof Jt){h(413,x.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let E=x=>S.lookup(R,x),O;try{if(f==="canonical"){let x=Yi(I),$=await E(x);Cn($,x),O={requests:$}}else O=await Xi(I,E)}catch(x){if(x instanceof qe){h(x.status,x.message,"invalid_request_error","invalid_request_error");return}throw x}se(c,200,O);return}if(d.method==="GET"&&p.pathname===Et){let S=await s(d);if(b&&(b.org=S.tenant??null),!S.openRouterModels){h(501,`GET ${Et} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}se(c,200,await S.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${jr} and GET ${Et}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(b&&(b.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Et}),c.end();return}se(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===wi){if(!g.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}se(c,200,await g.listImageModels());return}if(yi(p.pathname)){if(!g.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let S={clients:g,imageModels:g.supportsImages,stats:l,turn:w(),operatorLog:u};p.pathname===An?await Ii(d,c,S):await Ai(d,c,S);return}if(d.method==="GET"&&p.pathname===Hi){if(!g.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}se(c,200,await g.listSpeechToTextModels());return}if(Bi(p.pathname)){if(!g.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Pn}`,"not_implemented","not_implemented_error");return}let S={clients:g,transcriptionModels:g.supportsTranscription,stats:l,turn:w(),operatorLog:u};await Ji(d,c,S);return}if(Ui(p.pathname)){if(!g.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${jt}`,"not_implemented","not_implemented_error");return}let S={clients:g,speechModels:g.supportsSpeech,stats:l,turn:w(),operatorLog:u};await ji(d,c,S);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await sa(d)}catch(S){if(S instanceof Jt){h(413,S.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",_,_),await Gd(y,g,Mt(g),c,l,w(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",_,_),await Vd(y,g,c,l,w(),d.headers[Mr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",_,_),await Jd(y,g,c,l,w(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",_,_),await Wd(y,g,c,l,w(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",_,_),await Zd(y,g,c,l,w(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",_,_),Re(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let g=String(f instanceof Error?f.message:f);if(!c.headersSent){let S=o?.(f)??null;if(S){S.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${S.operatorDetail}`),h(S.status,g,S.openaiType,S.anthropicType,S.code);return}if(f instanceof Nn.SessionAllocationError){let I=mn(f.code);if(I){let E=f.retryAfterSeconds??(I.status===429?30:void 0);E!==void 0&&c.setHeader("Retry-After",String(E)),h(I.status,Nt(I,f.code??void 0),I.openaiType,I.anthropicType,I.code);return}}if(f instanceof Nn.SessionFailedError){let I=gn(f);if(I){let E=I.status===429?30:void 0;E!==void 0&&c.setHeader("Retry-After",String(E)),h(I.status,Nt(I,f.status.sessionId?`session ${f.status.sessionId}`:void 0),I.openaiType,I.anthropicType,I.code);return}}if(f instanceof yt){h(502,g,"upstream_error","api_error");return}if(f instanceof ve){f.retryable&&c.setHeader("Retry-After","1");let I=pe(f,{inferenceId:b?.id??null});I.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:be(f)}`),h(502,I.message,"upstream_error","api_error",f.code);return}if(f instanceof Ue){c.setHeader("Retry-After",String(f.retryAfterSeconds)),h(f.status,g,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let R=pe(f,{inferenceId:b?.id??null});R.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:be(f)}`),h(500,R.message,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let y=f instanceof ve?f.code:null,_=pe(f,{inferenceId:b?.id??null});_.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:be(f)}`),c.destroyed||(m?c.write(`event: error
72
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:_.message}})}
73
-
74
- `):c.write(`data: ${JSON.stringify({error:{message:_.message,type:"upstream_error",code:y}})}
75
-
76
- `)),c.end()})}}function pa(t){let{clients:e,apiKey:n}=t,r=(0,aa.createServer)(tc(t)),o=Ps(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Cr(r,{resolver:ci(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),ws(r,{clients:e,apiKey:n}),r}var Dn=require("@urun-sh/core/internal");var nc={ensureWebRTC:Dn.ensureNodeWebRTC,webrtcUnavailableReason:Dn.nodeWebRTCUnavailableReason,audioBackend:Yt};async function fa(t=nc){try{await t.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}let e=t.webrtcUnavailableReason();if(e)return{ok:!1,reason:`${e} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await t.audioBackend()).createSource()}catch(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function oc(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?hn(n,"URUN_CATALOG_URL"):"",o=(t.URUN_CATALOG_ANON_KEY??"").trim();return!r||!o?(e(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
77
- `),null):{catalogUrl:r,anonKey:o}}function sc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:oc(U.default.env,r=>U.default.stderr.write(r)),decisionPool:Vo(U.default.env,U.default.env.HOSTNAME)??void 0},n=zo(e);return{router:n,decision:e.decisionPool?Yo(e,n):null}}async function ma(t,e,n){let r=(0,Jr.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{U.default.stderr.write(`failed to launch ${t}: ${String(s)}
78
- `),o(127)})})}function ga(){return Hs(U.default.env,C,Ee.existsSync)}function ya(t){for(let[e,n]of Object.entries(_r(t)))U.default.stdout.write(`export ${e}=${n}
79
- `)}async function ha(t,e){let n=pt(U.default.env),r=e?br(n):void 0,{router:o,decision:s}=sc(n);s&&(s.boot().then(()=>s.reap()).catch(c=>U.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
80
- `)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=kr(c.port),(0,Ee.mkdirSync)(Wr.default.dirname(i),{recursive:!0})}(0,Ee.appendFileSync)(i,d)},a=pa({clients:Xo(o,void 0,void 0,s??void 0,Jo(U.default.env)),identity:r,...e?{requestLog:u}:{}});try{await new Promise((d,c)=>{a.once("error",c),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),d.code==="EADDRINUSE"?new Error(Zs(t,await Sr(t))):d}let l=a.address().port;return e&&(U.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
81
- `),ya(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function ic(){let t=U.default.argv.slice(2),e=Vs(t),n=t.shift()??"proxy";if(n==="env")return ya(Js(e??vr(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await fa();return o?(U.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
82
- `),0):(U.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
83
- `),1)}if(n==="proxy"){let o=e??vr(t),s=await ha(o,!0);return await new Promise(i=>{U.default.once("SIGINT",i),U.default.once("SIGTERM",i)}),await s.close(),0}let r=n==="run"?t.shift():n;{if(!r)throw new Error(`launch needs an agent (${Object.keys(yn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let w=pt(U.default.env);return ma("pi",["-e",ga(),...js(w.appId,t)],U.default.env)}if(r==="omp"){let w=pt(U.default.env);return ma("omp",["-e",ga(),...Bs(w.appId,t)],U.default.env)}let o,s,i="openai";if(r==="--"){if(o=t.shift()??"",s=t,!o)throw new Error("`-- <cmd>` needs a command to launch")}else{let w=yn[r];if(!w)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(yn).join(" | ")} \u2014 or \`-- <cmd>\``);o=w.bin,s=[...w.args??[],...t],i=w.env}let u=await Ks(e,br(pt(U.default.env))),a=null,l=u.port;u.mode==="reuse"?U.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${l} (app ${u.identity.app}, fn ${u.identity.fn}, v${u.identity.proxy_version})
84
- `):u.reason&&U.default.stderr.write(`urun compat: ${u.reason}
85
- `);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await ha(u.port,!1),l=a.port,m=kr(l),(0,Ee.mkdirSync)(Wr.default.dirname(m),{recursive:!0}),p=(0,Ee.createWriteStream)(m,{flags:"a"}),c=Xs({streams:U.default,note:w=>(0,Ee.appendFileSync)(m,w)}).uninstall,p.on("error",w=>{d?.(),d=null,xe(U.default.stderr,`urun compat: proxy log ${m} failed: ${String(w)} \u2014 proxy output continues on the terminal
86
- `)}),U.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
87
- `),d=zs(p)),r==="codex"&&(s=qs(l,pt(U.default.env).appId,s));let h=(0,Jr.spawn)(o,s,{stdio:"inherit",env:Fs(U.default.env,l,i)}),v=m!==null?Qs({logPath:m,appendSync:Ee.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:w=>U.default.stderr.write(w),killChild:()=>h.kill("SIGTERM"),exit:w=>U.default.exit(w),proc:U.default}):null,k=await new Promise(w=>{h.once("exit",f=>w(f??1)),h.once("error",f=>{d?.(),d=null,xe(U.default.stderr,`failed to launch ${o}: ${String(f)}
88
- `),w(127)})});v?.();let b=null;try{a&&await a.close()}catch(w){b=w}finally{d?.(),d=null,c?.(),c=null,p?.end()}return b!==null&&xe(U.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${k} preserved): ${String(b instanceof Error?b.message:b)}
89
- `),k}}ic().then(t=>U.default.exit(t),t=>{U.default.stderr.write(`${String(t instanceof Error?t.message:t)}
90
- `),U.default.exit(1)});
69
+ `),n.end();return}finally{M?.flush(),M?.dispose()}}let v="",x="",S=[],w=new De;for await(let _ of r.track(g,p,o)){S.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(v+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(x+=_.delta);let E=ut(_);if(E&&w.add(E),_.type==="error"){Yr(n,_,{inferenceId:o.id,operatorError:i});return}}let f=Ie(S);et(o,f);let h=Wr(f),y=h.length>0?h:Wr({output:w.items()}),b=Ye(m,y.length,v);if(b){K(n,502,ze(p,b),"upstream_error");return}let R=y.map(({index:_,...E})=>E),A={role:"assistant",content:v||null},O=x||ha(f);O&&(A.reasoning_content=O),R.length>0&&(A.tool_calls=R),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:A,finish_reason:R.length>0?"tool_calls":"stop"}],usage:fa(f)})}var ya="sense-latest";async function nc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:ya,u=ue({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){K(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){K(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){K(n,400,"systemone media, when present, must be an array");return}let l=await wa(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function wa(t,e,n,r,o,s,i,u){let a={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=a;let l=performance.now();s.model(n),await qn(i,r,e),a.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(t)}],stream:!0},he(i))}catch(S){if(S instanceof G)return _t(o,"openai",S),null;if(S instanceof ve||S instanceof pe)return o.setHeader("retry-after","2"),K(o,503,S.message,"capacity_error"),null;throw S}a.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let S of s.track(d,n,i))if(m===null&&(m=performance.now(),a.first_event_ms=Math.round(m-c)),p.push(S),S.type==="error")return Yr(o,S,{inferenceId:i.id,operatorError:u}),null}catch(S){if(S instanceof G)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),_t(o,"openai",S),null;if(S instanceof ve||S instanceof pe)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),K(o,503,S.message,"capacity_error"),null;throw m!==null&&(a.stream_ms=Math.round(performance.now()-m)),S}m!==null&&(a.stream_ms=Math.round(performance.now()-m));let g=Ie(p);if(g==null)return K(o,502,"upstream produced no response.completed event","upstream_error"),null;et(i,g);let v=lt(p,g),x;try{x=JSON.parse(v)}catch{return K(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(x===null||typeof x!="object"||Array.isArray(x))return K(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"timing"in x){let S=x.timing;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"question_fwd_ms"in S&&"head_ms"in S){let w=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;a.question_fwd_ms=w(S.question_fwd_ms),a.head_ms=w(S.head_ms)}}return{answer:x,completed:g}}async function rc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:ya,u=ue({model:i});o.model=u,o.stream=!1;let a;try{a=_i(t,i)}catch(p){if(p instanceof L){K(n,400,p.message);return}throw p}let l=await wa(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Si(a.specs,l.answer)}catch(p){if(p instanceof we){K(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function oc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var zt=class extends Error{};function Dn(t){return new zt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function sc(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function ic(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new zt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function ac(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Dn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Dn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function uc(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Dn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:ac(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw Dn(u)}}return s(),r}function Kr(t){return at(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function lc(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ee(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){Ee(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ee(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(A=>typeof A!="string"))){Ee(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=Os(o.id),l=[],d;try{t.system&&l.push({role:"system",content:oc(t.system)});for(let A of i)l.push(...uc(A));d=ic(t.tool_choice)}catch(A){if(A instanceof zt){Ee(n,400,"invalid_request_error",A.message);return}throw A}let c=ue(t);r.model(c),o.model=c,o.stream=t.stream===!0,await qn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:sc(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},he(o))}catch(A){if(A instanceof G){_t(n,"anthropic",A);return}if(A instanceof ve||A instanceof pe){n.setHeader("retry-after","2"),Ee(n,503,"capacity_error",A.message);return}throw A}let g=(A,O)=>{n.destroyed||n.write(`event: ${A}
70
+ data: ${JSON.stringify({type:A,...O})}
71
+
72
+ `)};if(t.stream===!0){let A=r.track(m,c,o);zr(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,_="",E=0,k="none",M=()=>k,q=-1,B=-1,N=new De,U=[],oe=()=>{k!=="none"&&(k="none",g("content_block_stop",{index:q}))},J=(Y,ee)=>{oe(),k=Y,q=E++,g("content_block_start",{index:q,content_block:ee})};for await(let Y of A){if(n.destroyed)break;U.push(Y);let ee=ut(Y);if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")M()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:Y.delta}});else if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")M()!=="text"&&J("text",{type:"text",text:""}),O+=1,_+=Y.delta,g("content_block_delta",{index:q,delta:{type:"text_delta",text:Y.delta}});else if(ee){let{call:_e}=N.add(ee);(M()!=="tool"||ee.tool_index!==B)&&(B=ee.tool_index,J("tool",{type:"tool_use",id:_e.id??`call_${ee.tool_index}`,name:_e.name??"",input:{}})),ee.delta&&g("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(Y.type==="error"){o.streamError=!0;let _e=Y.error,je=Te(_e);je===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),g("error",{error:{type:"api_error",message:je??xe(o.id)}}),n.end();return}}if(n.destroyed)return;let ne=Ie(U),$=at(ne),H=Ye(p,N.size+$.length,_);if(H){o.streamError=!0,g("error",{error:{type:"api_error",message:ze(c,H)}}),n.end();return}oe();let z=[];if(N.size===0)try{z=Kr(ne)}catch(Y){o.streamError=!0;let ee=fe(Y,{inferenceId:o.id});ee.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Y instanceof Error?Y.message:Y)}`),g("error",{error:{type:"api_error",message:ee.message}}),n.end();return}E===0&&z.length===0&&(J("text",{type:"text",text:""}),oe()),z.forEach(Y=>{let ee=E++;g("content_block_start",{index:ee,content_block:{...Y,input:{}}}),g("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(Y.input??{})}}),g("content_block_stop",{index:ee})});let Be=N.size>0||z.length>0,tt=Nn(ne);et(o,ne),g("message_delta",{delta:{stop_reason:Be?"tool_use":"end_turn"},usage:tt?{input_tokens:tt.input_tokens,output_tokens:tt.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let v="",x="",S=[],w=new De;for await(let A of r.track(m,c,o)){S.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(v+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(x+=A.delta);let O=ut(A);if(O&&w.add(O),A.type==="error"){let _=A.error,E=_?.type==="invalid_request_error",k=Te(_);k===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),Ee(n,E?400:502,E?"invalid_request_error":"api_error",k??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Ie(S);et(o,f);let h;try{h=Kr(f),h.length===0&&w.size>0&&(h=Kr({output:w.items()}))}catch(A){let O=fe(A,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),Ee(n,502,"api_error",O.message);return}let y=Ye(p,h.length,v);if(y){Ee(n,502,"api_error",ze(c,y));return}let b=[],R=x||ha(f);R&&b.push({type:"thinking",thinking:R}),(v||h.length===0)&&b.push({type:"text",text:v}),b.push(...h),ae(n,200,{id:a,type:"message",role:"assistant",content:b,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:Nn(f)??{input_tokens:0,output_tokens:0}})}function dc(t){Re(process.stdout,t)}function cc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??dc,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new We;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(f,h,y,b,R)=>m?Ee(c,f,b,h):K(c,f,h,y,R),v=hr(p.pathname),x=p.pathname.startsWith("/partners/"),S=v||x?{id:Mt(),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;S&&(c.setHeader(Es,S.id),c.once("close",()=>{let f=Ts({turn:S,method:d.method??"",path:p.pathname,res:c});i(Ps(f)),a?.(f),ca({record:f,ledger:t.ledger??null,req:d})}));let w=()=>As(p.pathname,S);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===ta?"canonical":p.pathname===Jr?"huggingface":null;if(f){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let R=t.usage;if(!R){g(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 A=R.authorize(d),O;try{O=await pa(d,na)}catch(k){if(k instanceof Kt){g(413,k.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=k=>R.lookup(A,k),E;try{if(f==="canonical"){let k=ra(O),M=await _(k);Ln(M,k),E={requests:M}}else E=await oa(O,_)}catch(k){if(k instanceof qe){g(k.status,k.message,"invalid_request_error","invalid_request_error");return}throw k}ae(c,200,E);return}if(d.method==="GET"&&p.pathname===Et){let R=await s(d);if(S&&(S.org=R.tenant??null),!R.openRouterModels){g(501,`GET ${Et} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await R.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Jr} and GET ${Et}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Et}),c.end();return}ae(c,200,await h.listModels());return}if(d.method==="GET"&&p.pathname===Ri){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listImageModels());return}if(xi(p.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let R={clients:h,imageModels:h.supportsImages,stats:l,turn:w(),operatorLog:u};p.pathname===Tn?await Li(d,c,R):await $i(d,c,R);return}if(d.method==="GET"&&p.pathname===Yi){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listSpeechToTextModels());return}if(zi(p.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${$n}`,"not_implemented","not_implemented_error");return}let R={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:w(),operatorLog:u};await Zi(d,c,R);return}if(Gi(p.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ht}`,"not_implemented","not_implemented_error");return}let R={clients:h,speechModels:h.supportsSpeech,stats:l,turn:w(),operatorLog:u};await Ki(d,c,R);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await pa(d)}catch(R){if(R instanceof Kt){g(413,R.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",b,b),await ec(y,h,Lt(h),c,l,w(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",b,b),await tc(y,h,c,l,w(),d.headers[Fr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",b,b),await nc(y,h,c,l,w(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",b,b),await rc(y,h,c,l,w(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",b,b),await lc(y,h,c,l,w(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",b,b),Ee(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let h=String(f instanceof Error?f.message:f);if(!c.headersSent){let R=o?.(f)??null;if(R){R.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${R.operatorDetail}`),g(R.status,h,R.openaiType,R.anthropicType,R.code);return}if(f instanceof Fn.SessionAllocationError){let O=hn(f.code);if(O){let _=f.retryAfterSeconds??(O.status===429?30:void 0);_!==void 0&&c.setHeader("Retry-After",String(_)),g(O.status,Ut(O,f.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof Fn.SessionFailedError){let O=yn(f);if(O){let _=O.status===429?30:void 0;_!==void 0&&c.setHeader("Retry-After",String(_)),g(O.status,Ut(O,f.status.sessionId?`session ${f.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof yt){g(502,h,"upstream_error","api_error");return}if(f instanceof be){f.retryable&&c.setHeader("Retry-After","1");let O=fe(f,{inferenceId:S?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Se(f)}`),g(502,O.message,"upstream_error","api_error",f.code);return}if(f instanceof Ue){c.setHeader("Retry-After",String(f.retryAfterSeconds)),g(f.status,h,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let A=fe(f,{inferenceId:S?.id??null});A.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Se(f)}`),g(500,A.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let y=f instanceof be?f.code:null,b=fe(f,{inferenceId:S?.id??null});b.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Se(f)}`),c.destroyed||(m?c.write(`event: error
73
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:b.message}})}
74
+
75
+ `):c.write(`data: ${JSON.stringify({error:{message:b.message,type:"upstream_error",code:y}})}
76
+
77
+ `)),c.end()})}}function _a(t){let{clients:e,apiKey:n}=t,r=(0,ma.createServer)(cc(t)),o=Us(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Ur(r,{resolver:wi(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),xs(r,{clients:e,apiKey:n}),r}var Bn=require("@urun-sh/core/internal");var pc={ensureWebRTC:Bn.ensureNodeWebRTC,webrtcUnavailableReason:Bn.nodeWebRTCUnavailableReason,audioBackend:Zt};async function va(t=pc){try{await t.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}let e=t.webrtcUnavailableReason();if(e)return{ok:!1,reason:`${e} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await t.audioBackend()).createSource()}catch(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function mc(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?wn(n,"URUN_CATALOG_URL"):"",o=(t.URUN_CATALOG_ANON_KEY??"").trim();return!r||!o?(e(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
78
+ `),null):{catalogUrl:r,anonKey:o}}function gc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:mc(F.default.env,r=>F.default.stderr.write(r)),decisionPool:Xo(F.default.env,F.default.env.HOSTNAME)??void 0},n=ts(e);return{router:n,decision:e.decisionPool?ns(e,n):null}}async function ba(t,e,n){let r=(0,Xr.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{F.default.stderr.write(`failed to launch ${t}: ${String(s)}
79
+ `),o(127)})})}function Sa(){return zs(F.default.env,C,Ae.existsSync)}function xa(t){for(let[e,n]of Object.entries(xr(t)))F.default.stdout.write(`export ${e}=${n}
80
+ `)}async function ka(t,e){let n=pt(F.default.env),r=e?Er(n):void 0,{router:o,decision:s}=gc(n);s&&(s.boot().then(()=>s.reap()).catch(c=>F.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
81
+ `)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=Ir(c.port),(0,Ae.mkdirSync)(Qr.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=_a({clients:rs(o,void 0,void 0,s??void 0,Qo(F.default.env)),identity:r,...e?{requestLog:u}:{}});try{await new Promise((d,c)=>{a.once("error",c),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),d.code==="EADDRINUSE"?new Error(si(t,await Ar(t))):d}let l=a.address().port;return e&&(F.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
82
+ `),xa(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function hc(){let t=F.default.argv.slice(2),e=Xs(t),n=t.shift()??"proxy";if(n==="env")return xa(Qs(e??Rr(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await va();return o?(F.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
83
+ `),0):(F.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
84
+ `),1)}if(n==="proxy"){let o=e??Rr(t),s=await ka(o,!0);return await new Promise(i=>{F.default.once("SIGINT",i),F.default.once("SIGTERM",i)}),await s.close(),0}let r=n==="run"?t.shift():n;{if(!r)throw new Error(`launch needs an agent (${Object.keys(_n).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let w=pt(F.default.env);return ba("pi",["-e",Sa(),...Ws(w.appId,t)],F.default.env)}if(r==="omp"){let w=pt(F.default.env);return ba("omp",["-e",Sa(),...Ks(w.appId,t)],F.default.env)}let o,s,i="openai";if(r==="--"){if(o=t.shift()??"",s=t,!o)throw new Error("`-- <cmd>` needs a command to launch")}else{let w=_n[r];if(!w)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(_n).join(" | ")} \u2014 or \`-- <cmd>\``);o=w.bin,s=[...w.args??[],...t],i=w.env}let u=await ei(e,Er(pt(F.default.env))),a=null,l=u.port;u.mode==="reuse"?F.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${l} (app ${u.identity.app}, fn ${u.identity.fn}, v${u.identity.proxy_version})
85
+ `):u.reason&&F.default.stderr.write(`urun compat: ${u.reason}
86
+ `);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await ka(u.port,!1),l=a.port,m=Ir(l),(0,Ae.mkdirSync)(Qr.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=ri({streams:F.default,note:w=>(0,Ae.appendFileSync)(m,w)}).uninstall,p.on("error",w=>{d?.(),d=null,Re(F.default.stderr,`urun compat: proxy log ${m} failed: ${String(w)} \u2014 proxy output continues on the terminal
87
+ `)}),F.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
88
+ `),d=ti(p)),r==="codex"&&(s=Js(l,pt(F.default.env).appId,s));let g=(0,Xr.spawn)(o,s,{stdio:"inherit",env:Vs(F.default.env,l,i)}),v=m!==null?oi({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:w=>F.default.stderr.write(w),killChild:()=>g.kill("SIGTERM"),exit:w=>F.default.exit(w),proc:F.default}):null,x=await new Promise(w=>{g.once("exit",f=>w(f??1)),g.once("error",f=>{d?.(),d=null,Re(F.default.stderr,`failed to launch ${o}: ${String(f)}
89
+ `),w(127)})});v?.();let S=null;try{a&&await a.close()}catch(w){S=w}finally{d?.(),d=null,c?.(),c=null,p?.end()}return S!==null&&Re(F.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${x} preserved): ${String(S instanceof Error?S.message:S)}
90
+ `),x}}hc().then(t=>F.default.exit(t),t=>{F.default.stderr.write(`${String(t instanceof Error?t.message:t)}
91
+ `),F.default.exit(1)});