@urun-sh/openai 0.6.56 → 0.6.57

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ua=Object.create;var fo=Object.defineProperty;var Da=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var Ba=Object.getPrototypeOf,qa=Object.prototype.hasOwnProperty;var ja=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fa(e))!qa.call(t,o)&&o!==n&&fo(t,o,{get:()=>e[o],enumerable:!(r=Da(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ua(Ba(t)):{},ja(e||!t||!t.__esModule?fo(n,"default",{value:t,enumerable:!0}):n,t));var Ha=()=>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,L=Ha();var uo=require("child_process"),Ae=require("fs"),lo=ot(require("path"),1),H=ot(require("process"),1);var se=require("@urun-sh/core");var Te=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 rn=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function mo(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)})}var _o=require("@urun-sh/core/internal");function go(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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 zn(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 ho(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 yo=require("@urun-sh/core/internal");var Ga="llm-resp";async function*wo(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 ho(s);return}}}async function*Yn(t,e){let n=`${Ga}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*wo(e,t.stream(n).messages())}finally{try{(0,yo.gcRequest)(t.doc("llm"),e)}catch{}}}var on=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=zn(e,n,this.consumerId);return this.write(r),Yn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=go(e,n,r,this.consumerId);return this.write(o),Yn(this.session,r)})}cancelTurn(e){try{(0,_o.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await mo(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 vo=0;function Va(){return vo+=1,`req_${Date.now().toString(36)}_${vo.toString(36)}`}var Rt=class{transport;constructor(e,n){this.transport=new on(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Va(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};function an(t){let e=t.byteLength>>1,n=0;for(let r=0;r<e;r++){let o=t.readInt16LE(r*2);if(o>16||o<-16)return!1;n+=o*o}return n<=64*e}var So="audio",Xn=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 ko(t,e,n=1e4){try{return await Wa(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Wa(t,e,n){let r=new Xn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(So);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ka(t,n);return await r.startInbound(i),r}function Ka(t,e){let n=t.stream(So);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 bo="rt-video-in",At=256e3;function Zn(t){let e=t.stream(bo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${bo}') 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>At)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${At}-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 za=24e3,Et=480,Ya=111,Xa=50,sn=null;async function Qa(){if(sn)return;let t=await import("opusscript");sn=t.default??t}function Za(){if(!sn)throw new Error("[opus-guard] opusscript module not loaded");return new sn(za,1,2048)}var Qn=class{constructor(e=Za){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>=Xa}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 un(){let t=await import("werift");await Qa();let e=new Qn;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>=Et;){let d=a.subarray(l,l+Et);l+=Et;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Et);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+Et>>>0;let m=new t.RtpHeader({version:2,payloadType:Ya,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=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}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 xo(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 ln=require("@urun-sh/core"),er="rt-video-out";var eu="h264";function tu(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 nu(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;tu(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 Ro="urun.videoOut.v2-ws";function Eo(t){let e=t.stream(er);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${er}') 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: "${er}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=nu(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:eu,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 Ao={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},st=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Io(t){let e=t.t;if(typeof e!="string"||!(e in Ao))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ao).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 ru(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new st(`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 st(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Io(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new st(`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 Io(t)}function To(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function ou(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 Oo(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 To(e);let s=o.next();if(e!==void 0&&await ou(s,e)==="aborted")throw s.catch(()=>{}),To(e);let i=await s;if(i.done)return;yield ru(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Po=require("@urun-sh/core"),tr=2;function su(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function iu(t){let e=t?.type;return e==="response.completed"||e==="error"}function Co(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=tr;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(iu(m)&&(d=!0),su(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Po.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<tr&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<tr&&!c){await t.evict(u,a);continue}return}})()}}var _r=require("crypto");var he=class extends Error{name="ModelPriceError"},nr="per_million_input_tokens",rr="per_million_output_tokens",$o="model_id,variant,unit,price_usd,effective_at,expires_at",Mo={per_request:!0,per_minute:!0,per_output_unit:!0},au=5e3;function uu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new he(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Lo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new he(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function lu(t,e,n){return t===null?null:Lo(t,e,n)}function du(t,e){if(t===nr)return"input";if(t===rr)return"output";if(typeof t=="string"&&Object.hasOwn(Mo,t))return null;throw new he(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${nr} | ${rr}) nor a known GPU-time unit (${Object.keys(Mo).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 cu(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 or(t,e){return`${t}\0${e}`}function pu(t){if(!Array.isArray(t))throw new he(`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 he(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of $o.split(","))if(!Object.hasOwn(s,l))throw new he(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=du(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new he(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new he(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:uu(s.price_usd,o),effective_at:Lo(s.effective_at,o,"effective_at"),expires_at:lu(s.expires_at,o,"expires_at")})}return e}function No(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 S=p&&p.length>0?p:d?.[m];if(!S||S.length===0)return null;let R=cu(S,m);return"reason"in R?R:R.rate.usd===0?m==="output"&&g!==null&&n?.has(or(a,g))?R.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`}:R.rate};for(let[p,m]of o.get(a)){let g=l.get(p),S=c(g?.input,"input",m),R=c(g?.output,"output",m);if(S!==null&&"reason"in S){i.push({model_id:a,variant:m,reason:S.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:a,variant:m,reason:R.reason});continue}S===null||R===null||s.push({model_id:a,variant:m,pricing:{input:S.usd,output:R.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 It(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 Tt={prices:[],refusals:[]};async function Uo(t){let e=t.fetchImpl??fetch,n=`${nr},${rr}`,r=await e(`${t.catalogUrl}/model_prices?select=${$o}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(au)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return pu(await r.json())}var Xo=require("crypto");var ee=class extends Error{},fu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function mu(t){if(typeof t!="string")return!1;let e=fu.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 gu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`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 ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`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 ee(`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 ee(`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 ee(`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 ee(`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",mu(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ee(`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 ee(`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 ee(`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 ee(`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 it(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Do(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 ee(`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 sr(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 ee(`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 Fo(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 ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return gu(await r.json())}function fe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Pt="/partners/openrouter/models",hu={chat:!0,code:!0,agent:!0,vl:!0},Bo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function yu(t){let e=t.toLowerCase();return Object.hasOwn(Bo,e)?Bo[e]:null}var qo={"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 wu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(qo,o)?qo[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 jo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ho={2:"Llama2",3:"Llama3"};function _u(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(jo,s))return jo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ho,i))return Ho[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var vu=["context_length","max_model_len"];function bu(t){let e=vu.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 dn(t){let e=t.map(bu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Su(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function ir(t){if(t.length===0)return null;let e=t.map(Su),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ar(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 ku(t,e){let n=e.filter(s=>fe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Ot(n);let r=e.filter(s=>fe(s.model_id)===t);if(r.length>0)return Ot(r);let o=ar(t,e);return o.length>0?Ot(o):null}function Ot(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:xu(t),matches:t}:null}function xu(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 Ne=class extends Error{name="ModelCreatedError"};function at(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 Ne(`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 Ne(`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 Ne(`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 Ne(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(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 cn(t,e,n){let r=ku(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=dn(s),u=at(s),a=It(o.model_id,o.variant,n),l=Vo(o,s),d=ir(s);return Ge({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 Ru=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vo(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:[...Ru],defect:o}:{published:[],defect:o}}function ur(t){let e=t.length>0?Ot(t):null;return e===null?{published:[],defect:null}:Vo(e.row,e.matches)}function Go(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 Jo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Go(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Go(t.output)}]}}function Eu(t,e,n,r){if(e.length===0)return null;let o=Ot(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||hu[s.task]!==!0)return null;let u=dn(i),a=It(s.model_id,s.variant,n),l=_u(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:at(i),quantization:yu(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:Jo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:Jo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Wo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?it(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:wu(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=Eu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Qo="https://api.urun.sh/v1",J=class extends Error{},V=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},pr="credits_exhausted",fr="insufficient_credits",dr="urs1.";function $t(t,e){return dr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Je(t){if(!t.startsWith(dr))return null;try{let e=JSON.parse(Buffer.from(t.slice(dr.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 Zo(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 Ko(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ou(t);return e===null?[]:[e]}function Au(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 Ua=Object.create;var fo=Object.defineProperty;var Da=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var Ba=Object.getPrototypeOf,qa=Object.prototype.hasOwnProperty;var ja=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fa(e))!qa.call(t,o)&&o!==n&&fo(t,o,{get:()=>e[o],enumerable:!(r=Da(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ua(Ba(t)):{},ja(e||!t||!t.__esModule?fo(n,"default",{value:t,enumerable:!0}):n,t));var Ha=()=>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,L=Ha();var uo=require("child_process"),Ae=require("fs"),lo=ot(require("path"),1),H=ot(require("process"),1);var se=require("@urun-sh/core");var Te=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 rn=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function mo(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)})}var _o=require("@urun-sh/core/internal");function go(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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 zn(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 ho(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 yo=require("@urun-sh/core/internal");var Ga="llm-resp";async function*wo(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 ho(s);return}}}async function*Yn(t,e){let n=`${Ga}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*wo(e,t.stream(n).messages())}finally{try{(0,yo.gcRequest)(t.doc("llm"),e)}catch{}}}var on=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=zn(e,n,this.consumerId);return this.write(r),Yn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=go(e,n,r,this.consumerId);return this.write(o),Yn(this.session,r)})}cancelTurn(e){try{(0,_o.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await mo(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 vo=0;function Va(){return vo+=1,`req_${Date.now().toString(36)}_${vo.toString(36)}`}var Rt=class{transport;constructor(e,n){this.transport=new on(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Va(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};function an(t){let e=t.byteLength>>1,n=0;for(let r=0;r<e;r++){let o=t.readInt16LE(r*2);if(o>16||o<-16)return!1;n+=o*o}return n<=64*e}var So="audio",Xn=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 ko(t,e,n=1e4){try{return await Wa(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Wa(t,e,n){let r=new Xn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(So);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ka(t,n);return await r.startInbound(i),r}function Ka(t,e){let n=t.stream(So);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 bo="rt-video-in",At=256e3;function Zn(t){let e=t.stream(bo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${bo}') 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>At)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${At}-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 za=24e3,Et=480,Ya=111,Xa=50,sn=null;async function Qa(){if(sn)return;let t=await import("opusscript");sn=t.default??t}function Za(){if(!sn)throw new Error("[opus-guard] opusscript module not loaded");return new sn(za,1,2048)}var Qn=class{constructor(e=Za){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>=Xa}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 un(){let t=await import("werift");await Qa();let e=new Qn;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>=Et;){let d=a.subarray(l,l+Et);l+=Et;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Et);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+Et>>>0;let m=new t.RtpHeader({version:2,payloadType:Ya,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=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}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 xo(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 ln=require("@urun-sh/core"),er="rt-video-out";var eu="h264";function tu(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 nu(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;tu(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 Ro="urun.videoOut.v2-ws";function Eo(t){let e=t.stream(er);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${er}') 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: "${er}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=nu(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:eu,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 Ao={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},st=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Io(t){let e=t.t;if(typeof e!="string"||!(e in Ao))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ao).join(", ")}`);let n={kind:e};return e!=="turn_dropped"&&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 ru(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new st(`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 st(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Io(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new st(`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 Io(t)}function To(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function ou(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 Oo(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 To(e);let s=o.next();if(e!==void 0&&await ou(s,e)==="aborted")throw s.catch(()=>{}),To(e);let i=await s;if(i.done)return;yield ru(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Po=require("@urun-sh/core"),tr=2;function su(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function iu(t){let e=t?.type;return e==="response.completed"||e==="error"}function Co(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=tr;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(iu(m)&&(d=!0),su(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Po.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<tr&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<tr&&!c){await t.evict(u,a);continue}return}})()}}var _r=require("crypto");var he=class extends Error{name="ModelPriceError"},nr="per_million_input_tokens",rr="per_million_output_tokens",$o="model_id,variant,unit,price_usd,effective_at,expires_at",Mo={per_request:!0,per_minute:!0,per_output_unit:!0},au=5e3;function uu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new he(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Lo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new he(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function lu(t,e,n){return t===null?null:Lo(t,e,n)}function du(t,e){if(t===nr)return"input";if(t===rr)return"output";if(typeof t=="string"&&Object.hasOwn(Mo,t))return null;throw new he(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${nr} | ${rr}) nor a known GPU-time unit (${Object.keys(Mo).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 cu(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 or(t,e){return`${t}\0${e}`}function pu(t){if(!Array.isArray(t))throw new he(`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 he(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of $o.split(","))if(!Object.hasOwn(s,l))throw new he(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=du(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new he(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new he(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:uu(s.price_usd,o),effective_at:Lo(s.effective_at,o,"effective_at"),expires_at:lu(s.expires_at,o,"expires_at")})}return e}function No(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 S=p&&p.length>0?p:d?.[m];if(!S||S.length===0)return null;let R=cu(S,m);return"reason"in R?R:R.rate.usd===0?m==="output"&&g!==null&&n?.has(or(a,g))?R.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`}:R.rate};for(let[p,m]of o.get(a)){let g=l.get(p),S=c(g?.input,"input",m),R=c(g?.output,"output",m);if(S!==null&&"reason"in S){i.push({model_id:a,variant:m,reason:S.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:a,variant:m,reason:R.reason});continue}S===null||R===null||s.push({model_id:a,variant:m,pricing:{input:S.usd,output:R.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 It(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 Tt={prices:[],refusals:[]};async function Uo(t){let e=t.fetchImpl??fetch,n=`${nr},${rr}`,r=await e(`${t.catalogUrl}/model_prices?select=${$o}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(au)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return pu(await r.json())}var Xo=require("crypto");var ee=class extends Error{},fu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function mu(t){if(typeof t!="string")return!1;let e=fu.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 gu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`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 ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`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 ee(`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 ee(`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 ee(`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 ee(`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",mu(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ee(`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 ee(`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 ee(`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 ee(`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 it(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Do(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 ee(`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 sr(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 ee(`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 Fo(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 ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return gu(await r.json())}function fe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Pt="/partners/openrouter/models",hu={chat:!0,code:!0,agent:!0,vl:!0},Bo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function yu(t){let e=t.toLowerCase();return Object.hasOwn(Bo,e)?Bo[e]:null}var qo={"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 wu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(qo,o)?qo[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 jo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ho={2:"Llama2",3:"Llama3"};function _u(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(jo,s))return jo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ho,i))return Ho[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var vu=["context_length","max_model_len"];function bu(t){let e=vu.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 dn(t){let e=t.map(bu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Su(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function ir(t){if(t.length===0)return null;let e=t.map(Su),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ar(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 ku(t,e){let n=e.filter(s=>fe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Ot(n);let r=e.filter(s=>fe(s.model_id)===t);if(r.length>0)return Ot(r);let o=ar(t,e);return o.length>0?Ot(o):null}function Ot(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:xu(t),matches:t}:null}function xu(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 Ne=class extends Error{name="ModelCreatedError"};function at(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 Ne(`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 Ne(`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 Ne(`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 Ne(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(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 cn(t,e,n){let r=ku(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=dn(s),u=at(s),a=It(o.model_id,o.variant,n),l=Vo(o,s),d=ir(s);return Ge({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 Ru=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vo(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:[...Ru],defect:o}:{published:[],defect:o}}function ur(t){let e=t.length>0?Ot(t):null;return e===null?{published:[],defect:null}:Vo(e.row,e.matches)}function Go(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 Jo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Go(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Go(t.output)}]}}function Eu(t,e,n,r){if(e.length===0)return null;let o=Ot(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||hu[s.task]!==!0)return null;let u=dn(i),a=It(s.model_id,s.variant,n),l=_u(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:at(i),quantization:yu(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:Jo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:Jo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Wo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?it(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:wu(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=Eu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Qo="https://api.urun.sh/v1",J=class extends Error{},V=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},pr="credits_exhausted",fr="insufficient_credits",dr="urs1.";function $t(t,e){return dr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Je(t){if(!t.startsWith(dr))return null;try{let e=JSON.parse(Buffer.from(t.slice(dr.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 Zo(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 Ko(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ou(t);return e===null?[]:[e]}function Au(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
4
  `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function Iu(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||fe(`${r.model_id}-${r.variant}`)===e.appSlug||fe(r.model_id)===e.appSlug)),n?Au(n.engine_args?.pool):null}function lr(t,e,n,r,o){if(!o)throw new ee(`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 ee(`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 ee(`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 zo(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 ee(`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 es="shared:",Yo="speech:",Lt="realtime:";function De(t){return t.sharedApp?es+t.appSlug:t.appSlug}function Mt(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 cr(t,e){let n=e.filter(s=>fe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>fe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Tu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ou(t){let e=t.map(Tu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Pu={stt:"stt",tts:"tts"};function Ue(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:Pu[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function ts(t,e){let n=cr(t,e);return n.length>0?n:ar(t,e)}function Ct(t,e){return ts(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 ee(`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 pn=6e4,fn=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??pn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??pn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??pn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??pn;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 he)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
5
  `),Tt}let r=No(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}
@@ -17,7 +17,7 @@ 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 zs(t,e){let n=new qe.WebSocketServer({noServer:!0,maxPayload:wl}),r=new ze,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{xn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==yl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){xn(c,401,"invalid local proxy api key");return}let S;try{S=await u(d)}catch(R){let k=e.statusOf?.(R)??null;xn(c,k?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Ar(R,S,r,e.statusOf,e.operatorLog??(k=>console.error(k)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&xn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Ir();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!==qe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Vr=require("@urun-sh/core");var Ys=require("@urun-sh/core"),xl={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},Rl={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 jt(t,e){let n=Rl[t.code];return e?`${n} (${e})`:n}function Rn(t){if(t==null)return null;let e=xl[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 En(t){if(t.kind==="create-failed")return Rn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ys.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Rn(e?"cold_start_exceeded":"queue_timeout")}var Qs=ot(require("os"),1),Zs=ot(require("path"),1),ei=require("url"),ti=require("util");var Xs="0.6.56";var ni=4141,Al=Xs,In={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 Pr(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 ri(t,e,n){let r={...t,...Pr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function oi(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 si(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ii(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ai(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,ei.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 ui(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 li(t){if(t[0]!=="--port")return null;let e=ui(t[1]);return t.splice(0,2),e}function Cr(t){let e=t.indexOf("--port");if(e===-1)return ni;let n=ui(t[e+1]);return t.splice(e,2),n}function di(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 Tr(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 mt(t){let e=Il(Tr(t,"URUN_BASE_URL")),n=Tr(t,"URUN_ORG_ID"),r=Tr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?An(s,"URUN_API_URL"):Qo,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?An(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 Il(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 An(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 Mr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Al}}function Tl(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 Ol=250;async function $r(t,e=Ol){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 ci=2e3;async function Pl(t,e=ci){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 pi(t,e,n=ni,r=ci){if(t!=null)return{mode:"spawn",port:t};let o=await $r(n);if(o!==null&&Tl(o,e)){let s=await Pl(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 Lr(t,e=Qs.default.homedir()){return Zs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Or=["log","info","warn","error","debug","trace"];function fi(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(Or.map(u=>[u,n[u]]));for(let u of Or)n[u]=(...a)=>{t.write(`${(0,ti.format)(...a)}
20
+ ${o}`)}function zs(t,e){let n=new qe.WebSocketServer({noServer:!0,maxPayload:wl}),r=new ze,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{xn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==yl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){xn(c,401,"invalid local proxy api key");return}let S;try{S=await u(d)}catch(R){let k=e.statusOf?.(R)??null;xn(c,k?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Ar(R,S,r,e.statusOf,e.operatorLog??(k=>console.error(k)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&xn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Ir();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!==qe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Vr=require("@urun-sh/core");var Ys=require("@urun-sh/core"),xl={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},Rl={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 jt(t,e){let n=Rl[t.code];return e?`${n} (${e})`:n}function Rn(t){if(t==null)return null;let e=xl[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 En(t){if(t.kind==="create-failed")return Rn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ys.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Rn(e?"cold_start_exceeded":"queue_timeout")}var Qs=ot(require("os"),1),Zs=ot(require("path"),1),ei=require("url"),ti=require("util");var Xs="0.6.57";var ni=4141,Al=Xs,In={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 Pr(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 ri(t,e,n){let r={...t,...Pr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function oi(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 si(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ii(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ai(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,ei.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 ui(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 li(t){if(t[0]!=="--port")return null;let e=ui(t[1]);return t.splice(0,2),e}function Cr(t){let e=t.indexOf("--port");if(e===-1)return ni;let n=ui(t[e+1]);return t.splice(e,2),n}function di(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 Tr(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 mt(t){let e=Il(Tr(t,"URUN_BASE_URL")),n=Tr(t,"URUN_ORG_ID"),r=Tr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?An(s,"URUN_API_URL"):Qo,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?An(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 Il(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 An(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 Mr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Al}}function Tl(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 Ol=250;async function $r(t,e=Ol){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 ci=2e3;async function Pl(t,e=ci){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 pi(t,e,n=ni,r=ci){if(t!=null)return{mode:"spawn",port:t};let o=await $r(n);if(o!==null&&Tl(o,e)){let s=await Pl(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 Lr(t,e=Qs.default.homedir()){return Zs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Or=["log","info","warn","error","debug","trace"];function fi(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(Or.map(u=>[u,n[u]]));for(let u of Or)n[u]=(...a)=>{t.write(`${(0,ti.format)(...a)}
21
21
  `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Or)n[u]=i[u]}}var Cl=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function mi(t){let e=t?.code;return typeof e=="string"&&Cl.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(mi(n))return!1;throw n}}function gi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{mi(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
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 hi(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}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-NMNR3SQ5.js";import"../chunk-CAR4AEQJ.js";import{F as K}from"../chunk-MBIJRS4O.js";import"../chunk-KV3UXLNF.js";import{h as R}from"../chunk-MYNG74AX.js";import"../chunk-KNWFUWXY.js";import{d as v,e as $,f as C,g as U,h as I,i as L,j as N,k as O,l as x,m as _,n as g,p as G,q as P,r as D,s as M,t as A,u as W,v as b,w as B,x as j,y as F}from"../chunk-6R3TCKOH.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
2
+ import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-HIM6EB3J.js";import"../chunk-CAR4AEQJ.js";import{F as K}from"../chunk-RONITPWW.js";import"../chunk-KV3UXLNF.js";import{h as R}from"../chunk-MYNG74AX.js";import"../chunk-EA3GQ2MM.js";import{d as v,e as $,f as C,g as U,h as I,i as L,j as N,k as O,l as x,m as _,n as g,p as G,q as P,r as D,s as M,t as A,u as W,v as b,w as B,x as j,y as F}from"../chunk-O3Z5AY5E.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-4GW343S5.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
3
3
  `),null):{catalogUrl:l,anonKey:s}}function me(e){let i={baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:fe(n.env,l=>n.stderr.write(l)),decisionPool:J(n.env,n.env.HOSTNAME)??void 0},t=H(i);return{router:t,decision:i.decisionPool?Y(i,t):null}}async function Q(e,i,t){let l=ee(e,i,{stdio:"inherit",env:t});return new Promise(s=>{l.once("exit",r=>s(r??1)),l.once("error",r=>{n.stderr.write(`failed to launch ${e}: ${String(r)}
4
4
  `),s(127)})})}function X(){return N(n.env,import.meta.url,pe)}function te(e){for(let[i,t]of Object.entries($(e)))n.stdout.write(`export ${i}=${t}
5
5
  `)}async function Z(e,i){let t=g(n.env),l=i?P(t):void 0,{router:s,decision:r}=me(t);r&&(r.boot().then(()=>r.reap()).catch(u=>n.stderr.write(`[decision-pool] boot FAILED: ${String(u instanceof Error?u.message:u)}
@@ -1,6 +1,6 @@
1
1
  import { Server, IncomingMessage } from 'node:http';
2
- import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-CIOofxp2.cjs';
3
- export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-CIOofxp2.cjs';
2
+ import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-4JhDPmCP.cjs';
3
+ export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-4JhDPmCP.cjs';
4
4
  export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-C6MpaZS-.cjs';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.cjs';
@@ -1,6 +1,6 @@
1
1
  import { Server, IncomingMessage } from 'node:http';
2
- import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-lokLYIya.js';
3
- export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-lokLYIya.js';
2
+ import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-BjRgfMOX.js';
3
+ export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-BjRgfMOX.js';
4
4
  export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CaOqL-V8.js';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.js';
@@ -1 +1 @@
1
- import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-MBIJRS4O.js";import{a as o,h as t}from"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-6R3TCKOH.js";import{i as r,j as i}from"../chunk-N3Y2GDQK.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
1
+ import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-RONITPWW.js";import{a as o,h as t}from"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-O3Z5AY5E.js";import{i as r,j as i}from"../chunk-4GW343S5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.56",
3
+ "version": "0.6.57",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -70,7 +70,7 @@
70
70
  "build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
71
71
  },
72
72
  "peerDependencies": {
73
- "@urun-sh/core": "^0.6.56"
73
+ "@urun-sh/core": "^0.6.57"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",