@urun-sh/openai 0.6.32 → 0.6.33

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.
@@ -11,18 +11,18 @@ Connection: close\r
11
11
  \r
12
12
  ${y}\r
13
13
  `),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Ne=require("ws");var is=require("crypto"),as="Inference-Id";function Rt(){return(0,is.randomUUID)()}function Zn(t){return t==="/v1"||t.startsWith("/v1/")}function us(t,e){if(!Zn(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function Et(t){return`resp_${t}`}function ls(t){return`chatcmpl-${t}`}function ds(t){return`msg_${t}`}function fe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function cs(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function ps(t){return`${JSON.stringify(t)}
14
- `}var hu=256,yu=128;function ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,yu)}var Ge=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=hu?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},_u=256;function wu(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Ve=class extends Error{},nt=class{conversations=new Map;thread(e,n){let r=wu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ve(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=_u)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},fs=new WeakMap;function At(t){let e=fs.get(t);return e||(e=new nt,fs.set(t,e)),e}function rt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function xe(t){return t.find(e=>e.type==="response.completed")?.response??null}function ot(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var $e=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},vu=["<tool_call>","<function="];function bu(t){return vu.find(e=>t.includes(e))}function Je(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function We(t,e,n){if(!(!t||e>0))return bu(n)}function st(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ie(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Su(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function er(t,e){let n=Su(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var me=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function it(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ve?new me(n.message,"previous_response_not_found",400,"previous_response_id"):new me(String(n instanceof Error?n.message:n),"invalid_input")}}function ms(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function tr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new me("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ms(e)!==void 0?{response_format:ms(e)}:{}},o)}async function It(t){let{body:e,clients:n,store:r,stats:o}=t,s=it(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await tr(n,e,s,!0,c?fe(c):void 0);return{responseId:i,events:Eu({events:f,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function ku(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?Ru(o[i++],a):a),...xu(r,n)]}function xu(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function Ru(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*Eu(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=L=>L.response&&typeof L.response=="object"?{...L,response:{...L.response,id:r}}:L,f=`item_${r.slice(5)}`,y=!1,g=!1,w=0;function*A(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],p=(L,q)=>{S.push({output_index:L,item:q})},m=!1,h=0,_="",k=0,v="";function*R(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:h,content_index:0,text:v};let L={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:L},p(h,L),v=""}let O=!1,x=0,I="",b=0,C="",B="";function*F(L){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:I,output_index:x,content_index:0,text:C},yield{type:"response.content_part.done",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:C}};let q={id:I,type:"message",role:"assistant",status:L,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:x,item:q},p(x,q),C=""}let z=new $e,H=null,Te=-1;function*X(L){if(!H)return;let q=H;H=null,yield{type:"response.function_call_arguments.done",item_id:q.fcId,output_index:q.outputIndex,arguments:q.args};let G={id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:q.args,status:L};yield{type:"response.output_item.done",output_index:q.outputIndex,item:G},p(q.outputIndex,G)}let re=!1;for await(let L of l.track(e,o,t.turn)){d.push(L);let q=String(L.type??"");if(q==="response.created"||q==="response.in_progress"){y=!0,yield c(L);continue}if(q==="response.output_item.added"){g=!0,yield c(L);continue}if(q==="response.reasoning_text.delta"&&!g){yield*A(),m||(m=!0,h=w++,k+=1,_=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:h,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(L.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:h,content_index:0,delta:L.delta};continue}if(q==="response.output_text.delta"&&!g){yield*A(),yield*R(),O||(O=!0,x=w++,b+=1,I=b===1?f:`${f}_${b}`,yield{type:"response.output_item.added",output_index:x,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:""}}),C+=String(L.delta??""),B+=String(L.delta??""),yield{type:q,item_id:I,output_index:x,content_index:0,delta:L.delta};continue}let G=g?null:ot(L);if(G){if(yield*A(),yield*R(),yield*F("completed"),z.add(G),G.tool_index!==Te){yield*X("completed"),Te=G.tool_index;let De=w++;H={fcId:`fc_${r.slice(5)}_${G.tool_index}`,outputIndex:De,callId:G.call_id,name:G.name,args:""},yield{type:"response.output_item.added",output_index:De,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(G.call_id&&(H.callId=G.call_id),G.name&&(H.name=G.name),H.args+=G.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:G.delta});continue}if(q==="response.completed"&&!g){let De=rt(L.response),Xe=We(s,z.size+De.length,B);if(Xe){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Je(o,Xe)}};break}if(yield*R(),yield*F("completed"),yield*X("completed"),z.size===0)for(let Q of De){let ge=w++,Fe=Q.id??Q.call_id??`fc_${ge}`,Mn=Q.arguments??"",$r={id:Fe,type:"function_call",call_id:Q.call_id??Fe,name:Q.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...$r,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Fe,output_index:ge,delta:Mn},yield{type:"response.function_call_arguments.done",item_id:Fe,output_index:ge,arguments:Mn};let Nr={...$r,arguments:Mn,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:Nr},p(ge,Nr)}let V=ku(S,L.response);yield V.length>0?c({...L,response:{...L.response,output:V}}):c(L);continue}yield c(L)}if(yield*R(),yield*F("incomplete"),yield*X("incomplete"),i&&!re){let L=xe(d);a.remember(r,n,er(L,st(d,L)),u)}}var Re=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},le=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Au=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function we(t){return!Au.some(e=>e.test(t))}function ve(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function de(t,e){if(t instanceof j)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=gs(t);return n||{message:ve(e?.inferenceId??null),redacted:!0}}function gs(t){return t instanceof Pe?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Y?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof D?{message:t.message,redacted:!1}:t instanceof Re?{message:t.message,redacted:!1}:t instanceof Le?{message:t.message,redacted:!1}:t instanceof ye?we(t.message)?{message:t.message,redacted:!1}:null:t instanceof he?{message:t.message,redacted:!1}:t instanceof le?{message:t.message,redacted:!1}:null}function at(t,e,n){let r=n??(i=>console.error(i)),o=gs(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&we(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${t} upstream failed while serving this request`)}function Ee(t){let e=t?.message;return typeof e=="string"&&e.length>0&&we(e)?e:null}function _e(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Iu="/v1/responses",Ou=64*1024*1024,Tu=8*1024*1024,Pu=16,hs=32,ys=3600*1e3,Cu=/^[A-Za-z0-9._-]{1,256}$/;function oe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Mu=oe(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function or(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Lu(t){for(;t.bufferedAmount>Tu&&t.readyState===Ne.WebSocket.OPEN;){let{promise:e,resolve:n}=or();setTimeout(n,5),await e}}var nr=class extends nt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Ve))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},rr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new nr(At(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ys/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ys).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(oe(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(oe(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(oe(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(oe(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(oe(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(oe(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Cu.test(o.stream_id)){this.sendFrame(Mu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=hs){this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${hs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Rt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await It({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Et(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Ne.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await Lu(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Rt(),o=Et(r);try{let s=it(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:_e(e);if(e instanceof me)return oe(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof D)return oe(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof j){let u=de(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),oe(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),oe(s.status,{type:s.openaiType,message:o},n);let i=de(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),oe(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ee(o),u=i??ve(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),oe(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=Pu;){let{promise:e,resolve:n}=or();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Ne.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Ne.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function un(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
14
+ `}var hu=256,yu=128;function ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,yu)}var Ge=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=hu?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},_u=256;function wu(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Ve=class extends Error{},nt=class{conversations=new Map;thread(e,n){let r=wu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ve(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=_u)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},fs=new WeakMap;function At(t){let e=fs.get(t);return e||(e=new nt,fs.set(t,e)),e}function rt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function xe(t){return t.find(e=>e.type==="response.completed")?.response??null}function ot(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var $e=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},vu=["<tool_call>","<function="];function bu(t){return vu.find(e=>t.includes(e))}function Je(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function We(t,e,n){if(!(!t||e>0))return bu(n)}function st(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ie(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Su(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function er(t,e){let n=Su(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var me=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function it(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ve?new me(n.message,"previous_response_not_found",400,"previous_response_id"):new me(String(n instanceof Error?n.message:n),"invalid_input")}}function ms(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function tr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new me("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ms(e)!==void 0?{response_format:ms(e)}:{}},o)}async function It(t){let{body:e,clients:n,store:r,stats:o}=t,s=it(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await tr(n,e,s,!0,c?fe(c):void 0);return{responseId:i,events:Eu({events:f,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function ku(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?Ru(o[i++],a):a),...xu(r,n)]}function xu(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function Ru(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*Eu(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=L=>L.response&&typeof L.response=="object"?{...L,response:{...L.response,id:r}}:L,f=`item_${r.slice(5)}`,y=!1,g=!1,w=0;function*A(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],p=(L,q)=>{S.push({output_index:L,item:q})},m=!1,h=0,_="",k=0,v="";function*R(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:h,content_index:0,text:v};let L={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:L},p(h,L),v=""}let O=!1,x=0,I="",b=0,C="",B="";function*F(L){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:I,output_index:x,content_index:0,text:C},yield{type:"response.content_part.done",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:C}};let q={id:I,type:"message",role:"assistant",status:L,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:x,item:q},p(x,q),C=""}let z=new $e,H=null,Te=-1;function*X(L){if(!H)return;let q=H;H=null,yield{type:"response.function_call_arguments.done",item_id:q.fcId,output_index:q.outputIndex,arguments:q.args};let G={id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:q.args,status:L};yield{type:"response.output_item.done",output_index:q.outputIndex,item:G},p(q.outputIndex,G)}let re=!1;for await(let L of l.track(e,o,t.turn)){d.push(L);let q=String(L.type??"");if(q==="response.created"||q==="response.in_progress"){y=!0,yield c(L);continue}if(q==="response.output_item.added"){g=!0,yield c(L);continue}if(q==="response.reasoning_text.delta"&&!g){yield*A(),m||(m=!0,h=w++,k+=1,_=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:h,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(L.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:h,content_index:0,delta:L.delta};continue}if(q==="response.output_text.delta"&&!g){yield*A(),yield*R(),O||(O=!0,x=w++,b+=1,I=b===1?f:`${f}_${b}`,yield{type:"response.output_item.added",output_index:x,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:""}}),C+=String(L.delta??""),B+=String(L.delta??""),yield{type:q,item_id:I,output_index:x,content_index:0,delta:L.delta};continue}let G=g?null:ot(L);if(G){if(yield*A(),yield*R(),yield*F("completed"),z.add(G),G.tool_index!==Te){yield*X("completed"),Te=G.tool_index;let De=w++;H={fcId:`fc_${r.slice(5)}_${G.tool_index}`,outputIndex:De,callId:G.call_id,name:G.name,args:""},yield{type:"response.output_item.added",output_index:De,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(G.call_id&&(H.callId=G.call_id),G.name&&(H.name=G.name),H.args+=G.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:G.delta});continue}if(q==="response.completed"&&!g){let De=rt(L.response),Xe=We(s,z.size+De.length,B);if(Xe){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Je(o,Xe)}};break}if(yield*R(),yield*F("completed"),yield*X("completed"),z.size===0)for(let Q of De){let ge=w++,Fe=Q.id??Q.call_id??`fc_${ge}`,Mn=Q.arguments??"",$r={id:Fe,type:"function_call",call_id:Q.call_id??Fe,name:Q.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...$r,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Fe,output_index:ge,delta:Mn},yield{type:"response.function_call_arguments.done",item_id:Fe,output_index:ge,arguments:Mn};let Nr={...$r,arguments:Mn,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:Nr},p(ge,Nr)}let V=ku(S,L.response);yield V.length>0?c({...L,response:{...L.response,output:V}}):c(L);continue}yield c(L)}if(yield*R(),yield*F("incomplete"),yield*X("incomplete"),i&&!re){let L=xe(d);a.remember(r,n,er(L,st(d,L)),u)}}var Re=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},le=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Au=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function we(t){return!Au.some(e=>e.test(t))}function ve(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function de(t,e){if(t instanceof j)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=gs(t);return n||{message:ve(e?.inferenceId??null),redacted:!0}}function gs(t){return t instanceof Pe?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Y?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof D?{message:t.message,redacted:!1}:t instanceof Re?{message:t.message,redacted:!1}:t instanceof Le?{message:t.message,redacted:!1}:t instanceof ye?we(t.message)?{message:t.message,redacted:!1}:null:t instanceof he?{message:t.message,redacted:!1}:t instanceof le?{message:t.message,redacted:!1}:null}function at(t,e,n){let r=n??(i=>console.error(i)),o=gs(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&we(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${_e(e)}`),`the ${t} upstream failed while serving this request`)}function Ee(t){let e=t?.message;return typeof e=="string"&&e.length>0&&we(e)?e:null}function _e(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Iu="/v1/responses",Ou=64*1024*1024,Tu=8*1024*1024,Pu=16,hs=32,ys=3600*1e3,Cu=/^[A-Za-z0-9._-]{1,256}$/;function oe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Mu=oe(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function or(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Lu(t){for(;t.bufferedAmount>Tu&&t.readyState===Ne.WebSocket.OPEN;){let{promise:e,resolve:n}=or();setTimeout(n,5),await e}}var nr=class extends nt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Ve))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},rr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new nr(At(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ys/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ys).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(oe(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(oe(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(oe(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(oe(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(oe(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(oe(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Cu.test(o.stream_id)){this.sendFrame(Mu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=hs){this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${hs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Rt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await It({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Et(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Ne.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await Lu(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Rt(),o=Et(r);try{let s=it(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:_e(e);if(e instanceof me)return oe(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof D)return oe(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof j){let u=de(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),oe(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),oe(s.status,{type:s.openaiType,message:o},n);let i=de(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),oe(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ee(o),u=i??ve(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),oe(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=Pu;){let{promise:e,resolve:n}=or();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Ne.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Ne.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function un(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
15
15
  `;t.end(`HTTP/1.1 ${e} ${r}\r
16
16
  Connection: close\r
17
17
  Content-Type: text/plain; charset=utf-8\r
18
18
  Content-Length: ${Buffer.byteLength(o)}\r
19
19
  \r
20
- ${o}`)}function _s(t,e){let n=new Ne.WebSocketServer({noServer:!0,maxPayload:Ou}),r=new Ge,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,f)=>{let y;try{y=new URL(d.url??"/","http://localhost")}catch{un(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),y.pathname!==Iu){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){un(c,401,"invalid local proxy api key");return}let w;try{w=await u(d)}catch(A){let S=e.statusOf?.(A)??null;un(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,f,A=>{s.delete(c),o.add(A),A.on("close",()=>o.delete(A));try{new rr(A,w,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(A),A.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&un(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=or();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let y of s)y.destroy();s.clear();for(let y of i)y.destroy();i.clear();for(let y of o)y.close(1001,"server shutting down");let f=setTimeout(()=>{for(let y of o)y.readyState!==Ne.WebSocket.CLOSED&&y.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var _r=require("@urun-sh/core");var ws=require("@urun-sh/core"),$u={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},Nu={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 Ot(t,e){let n=Nu[t.code];return e?`${n} (${e})`:n}function ln(t){if(t==null)return null;let e=$u[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 dn(t){if(t.kind==="create-failed")return ln(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ws.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return ln(e?"cold_start_exceeded":"queue_timeout")}var bs=Qe(require("os"),1),Ss=Qe(require("path"),1),ks=require("url"),xs=require("util");var vs="0.6.32";var Rs=4141,Du=vs,pn={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 ar(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 Es(t,e,n){let r={...t,...ar(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function As(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 Is(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Os(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Ts(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,ks.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 Ps(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 Cs(t){if(t[0]!=="--port")return null;let e=Ps(t[1]);return t.splice(0,2),e}function ur(t){let e=t.indexOf("--port");if(e===-1)return Rs;let n=Ps(t[e+1]);return t.splice(e,2),n}function Ms(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function sr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function ut(t){let e=Fu(sr(t,"URUN_BASE_URL")),n=sr(t,"URUN_ORG_ID"),r=sr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?cn(s,"URUN_API_URL"):vo,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?cn(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 Fu(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 cn(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 lr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Du}}function Bu(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 ju=250;async function dr(t,e=ju){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Ls=2e3;async function qu(t,e=Ls){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function $s(t,e,n=Rs,r=Ls){if(t!=null)return{mode:"spawn",port:t};let o=await dr(n);if(o!==null&&Bu(o,e)){let s=await qu(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 cr(t,e=bs.default.homedir()){return Ss.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var ir=["log","info","warn","error","debug","trace"];function Ns(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(ir.map(u=>[u,n[u]]));for(let u of ir)n[u]=(...a)=>{t.write(`${(0,xs.format)(...a)}
20
+ ${o}`)}function _s(t,e){let n=new Ne.WebSocketServer({noServer:!0,maxPayload:Ou}),r=new Ge,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,f)=>{let y;try{y=new URL(d.url??"/","http://localhost")}catch{un(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),y.pathname!==Iu){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){un(c,401,"invalid local proxy api key");return}let w;try{w=await u(d)}catch(A){let S=e.statusOf?.(A)??null;un(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,f,A=>{s.delete(c),o.add(A),A.on("close",()=>o.delete(A));try{new rr(A,w,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(A),A.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&un(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=or();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let y of s)y.destroy();s.clear();for(let y of i)y.destroy();i.clear();for(let y of o)y.close(1001,"server shutting down");let f=setTimeout(()=>{for(let y of o)y.readyState!==Ne.WebSocket.CLOSED&&y.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var _r=require("@urun-sh/core");var ws=require("@urun-sh/core"),$u={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},Nu={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 Ot(t,e){let n=Nu[t.code];return e?`${n} (${e})`:n}function ln(t){if(t==null)return null;let e=$u[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 dn(t){if(t.kind==="create-failed")return ln(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ws.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return ln(e?"cold_start_exceeded":"queue_timeout")}var bs=Qe(require("os"),1),Ss=Qe(require("path"),1),ks=require("url"),xs=require("util");var vs="0.6.33";var Rs=4141,Du=vs,pn={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 ar(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 Es(t,e,n){let r={...t,...ar(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function As(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 Is(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Os(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Ts(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,ks.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 Ps(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 Cs(t){if(t[0]!=="--port")return null;let e=Ps(t[1]);return t.splice(0,2),e}function ur(t){let e=t.indexOf("--port");if(e===-1)return Rs;let n=Ps(t[e+1]);return t.splice(e,2),n}function Ms(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function sr(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function ut(t){let e=Fu(sr(t,"URUN_BASE_URL")),n=sr(t,"URUN_ORG_ID"),r=sr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?cn(s,"URUN_API_URL"):vo,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?cn(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 Fu(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 cn(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 lr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Du}}function Bu(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 ju=250;async function dr(t,e=ju){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var Ls=2e3;async function qu(t,e=Ls){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function $s(t,e,n=Rs,r=Ls){if(t!=null)return{mode:"spawn",port:t};let o=await dr(n);if(o!==null&&Bu(o,e)){let s=await qu(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 cr(t,e=bs.default.homedir()){return Ss.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var ir=["log","info","warn","error","debug","trace"];function Ns(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(ir.map(u=>[u,n[u]]));for(let u of ir)n[u]=(...a)=>{t.write(`${(0,xs.format)(...a)}
21
21
  `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of ir)n[u]=i[u]}}var Hu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Us(t){let e=t?.code;return typeof e=="string"&&Hu.has(e)}function be(t,e){try{return t.write(e),!0}catch(n){if(Us(n))return!1;throw n}}function Ds(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Us(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 Fs(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
23
23
  `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
24
24
  `)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
25
- `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function Bs(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}var Js=require("ws");var Vs=require("@urun-sh/core");var qs=require("crypto");function T(t){return`${t}_${(0,qs.randomUUID)().replace(/-/g,"").slice(0,24)}`}var fn=4*1024*1024,pr=8*1024*1024,mn=512,gn=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function dt(t,e){return{type:"server_error",code:t,message:e}}function J(t){return{type:"error",event_id:T("event"),error:t}}function fr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Gu={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Vu={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ju={format:!0,voice:!0,speed:!0};function Wu(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function lt(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function js(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ku=10;function mr(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Ku})}function Tt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in Gu));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=lt(o.modalities,"modalities"),a=lt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=lt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Wu(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=mr(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,y]of Object.entries(l))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new P(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(y!=null&&y!==c[f])throw new P(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Vu))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&js(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Tt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Tt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ju))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&js(d.format,"audio.output.format"),d.speed!==void 0)throw new P("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function hn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function gr(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:T("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new P("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function yn(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var zu=1001,Yu=1011,Hs=t=>t.slice(0,120),Xu=/^[A-Za-z0-9+/=]*$/,Qu=2;function Zu(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Qu)return!1;return!0}var Pt=class{id=T("conn");ws;binding;onClosed;operatorLog;config=fr();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:T("event"),session:hn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof j&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(J(dt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:T("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:T("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:T("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:T("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=T("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ee("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>fn){this.fail(ee("frame_too_large",`frame exceeds the ${fn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ee("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ee("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(J({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(dt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Tt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(J(ee("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:T("event"),session:hn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=gr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(J(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:T("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(J(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(J(ee("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:T("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(J(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Xu.test(e.audio)){this.send(J(ee("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>gn){this.send(J(ee("buffer_full",`uncommitted input audio exceeds the ${gn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(J(ee("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=T("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(J(ee("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(J(ee("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(J(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(J(ee("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(J({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(J(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?lt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?lt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(J(ee("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:yn(this.items),c=mr(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=n.tools!==void 0?n.tools:this.config.tools,A=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...A!==void 0?{tool_choice:A}:{}};if(!(a&&!this.ensureVoice())){for(let p of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(p);this.inFlight=(async()=>{let p=[],m=v=>{this.responseFlushed?this.send(v):p.push(v)},h=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let v of p)this.send(v);p.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},k=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,d=yn(this.items)}let{input:v,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},O={...S,input:v,...a?this.compositeTurnAsk(n):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(O,i)}catch(I){this.upstreamTurnFault(I,u);return}try{for await(let I of x){if(this.cancelled)break;let b=I;if(b.type==="error"){let C=this.upstreamErrorBody(b);this.responseFlushed?this.send(J(C)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,C)});return}if(b.type==="response.output_text.delta"&&typeof b.delta=="string"){h(),_.messageOpen||(this.beginMessageItem(u,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta})),_.messageText+=b.delta;continue}if(b.type==="response.function_call_arguments.delta"){h();let C=typeof b.delta=="string"?b.delta:"",B=typeof b.call_id=="string"&&b.call_id.length>0?b.call_id:`${u}_fc_${_.nextOutputIndex}`,F=_.tools.get(B);if(!F){let z=typeof b.name=="string"&&b.name.length>0?b.name:void 0;F={outputIndex:_.nextOutputIndex++,name:z,args:""},_.tools.set(B,F);let H={id:B,object:"realtime.item",type:"function_call",call_id:B,name:z??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:F.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof b.name=="string"&&b.name.length>0&&(F.name=b.name),F.args+=C,m({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:B,response_id:u,output_index:F.outputIndex,call_id:B,name:F.name??"",delta:C});continue}if(b.type==="response.completed"){k=b.response??null;continue}}}catch(I){this.upstreamTurnFault(I,u);return}if(this.cancelled)return;this.closeOpenItems(u,_,l),h(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,k)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Zu(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(J({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:T("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:T("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Ee(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ve(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&we(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${_e(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(dt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof j){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Vs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=dt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(J(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(J(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>mn&&(this.items.shift(),this.send(J({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${mn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>pr){this.ws.close(zu,Hs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${_e(e)}`),r.message}fail(e,n){this.send(J(e)),this.ws.close(Yu,Hs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Gs(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Gs(this.id,e)}},hr=[];function Gs(t,e){hr.push({id:t,reason:e}),hr.length>256&&hr.shift()}var wr="/v1/realtime",el=t=>t.slice(0,120);function tl(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
+ `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function Bs(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}var Js=require("ws");var Vs=require("@urun-sh/core");var qs=require("crypto");function T(t){return`${t}_${(0,qs.randomUUID)().replace(/-/g,"").slice(0,24)}`}var fn=4*1024*1024,pr=8*1024*1024,mn=512,gn=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function dt(t,e){return{type:"server_error",code:t,message:e}}function J(t){return{type:"error",event_id:T("event"),error:t}}function fr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Gu={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Vu={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ju={format:!0,voice:!0,speed:!0};function Wu(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function lt(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function js(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ku=10;function mr(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Ku})}function Tt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in Gu));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=lt(o.modalities,"modalities"),a=lt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=lt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Wu(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=mr(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,y]of Object.entries(l))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new P(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(y!=null&&y!==c[f])throw new P(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Vu))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&js(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Tt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Tt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ju))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&js(d.format,"audio.output.format"),d.speed!==void 0)throw new P("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function hn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function gr(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:T("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new P("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function yn(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var zu=1001,Yu=1011,Hs=t=>t.slice(0,120),Xu=/^[A-Za-z0-9+/=]*$/,Qu=2;function Zu(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Qu)return!1;return!0}var Pt=class{id=T("conn");ws;binding;onClosed;operatorLog;config=fr();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:T("event"),session:hn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof j&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(J(dt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:T("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:T("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:T("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:T("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=T("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ee("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>fn){this.fail(ee("frame_too_large",`frame exceeds the ${fn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ee("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ee("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(J({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(dt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Tt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(J(ee("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:T("event"),session:hn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=gr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(J(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:T("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(J(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(J(ee("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:T("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(J(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Xu.test(e.audio)){this.send(J(ee("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>gn){this.send(J(ee("buffer_full",`uncommitted input audio exceeds the ${gn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(J(ee("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=T("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(J(ee("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(J(ee("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(J(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(J(ee("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(J({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(J(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?lt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?lt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(J(ee("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:yn(this.items),c=mr(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=n.tools!==void 0?n.tools:this.config.tools,A=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...A!==void 0?{tool_choice:A}:{}};if(!(a&&!this.ensureVoice())){for(let p of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(p);this.inFlight=(async()=>{let p=[],m=v=>{this.responseFlushed?this.send(v):p.push(v)},h=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let v of p)this.send(v);p.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},k=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,d=yn(this.items)}let{input:v,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},O={...S,input:v,...a?this.compositeTurnAsk(n):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(O,i)}catch(I){this.upstreamTurnFault(I,u);return}try{for await(let I of x){if(this.cancelled)break;let b=I;if(b.type==="error"){let C=this.upstreamErrorBody(b);this.responseFlushed?this.send(J(C)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,C)});return}if(b.type==="response.output_text.delta"&&typeof b.delta=="string"){h(),_.messageOpen||(this.beginMessageItem(u,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta})),_.messageText+=b.delta;continue}if(b.type==="response.function_call_arguments.delta"){h();let C=typeof b.delta=="string"?b.delta:"",B=typeof b.call_id=="string"&&b.call_id.length>0?b.call_id:`${u}_fc_${_.nextOutputIndex}`,F=_.tools.get(B);if(!F){let z=typeof b.name=="string"&&b.name.length>0?b.name:void 0;F={outputIndex:_.nextOutputIndex++,name:z,args:""},_.tools.set(B,F);let H={id:B,object:"realtime.item",type:"function_call",call_id:B,name:z??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:F.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof b.name=="string"&&b.name.length>0&&(F.name=b.name),F.args+=C,m({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:B,response_id:u,output_index:F.outputIndex,call_id:B,name:F.name??"",delta:C});continue}if(b.type==="response.completed"){k=b.response??null;continue}}}catch(I){this.upstreamTurnFault(I,u);return}if(this.cancelled)return;this.closeOpenItems(u,_,l),h(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,k)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Zu(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(J({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:T("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:T("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Ee(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ve(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&we(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${_e(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(dt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof j){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Vs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=dt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(J(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(J(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>mn&&(this.items.shift(),this.send(J({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${mn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>pr){this.ws.close(zu,Hs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${_e(e)}`),r.message}fail(e,n){this.send(J(e)),this.ws.close(Yu,Hs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Gs(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Gs(this.id,e)}},hr=[];function Gs(t,e){hr.push({id:t,reason:e}),hr.length>256&&hr.shift()}var wr="/v1/realtime",el=t=>t.slice(0,120);function tl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
@@ -64,7 +64,7 @@ data: ${JSON.stringify(m)}
64
64
  `),n.end();return}finally{C?.flush(),C?.dispose()}}let w="",A="",S=[],p=new $e;for await(let x of r.track(g,f,o)){S.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(w+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(A+=x.delta);let I=ot(x);if(I&&p.add(I),x.type==="error"){Cr(n,x,{inferenceId:o.id,operatorError:i});return}}let m=xe(S);Ye(o,m);let h=Or(m),_=h.length>0?h:Or({output:p.items()}),k=We(y,_.length,w);if(k){K(n,502,Je(f,k),"upstream_error");return}let v=_.map(({index:x,...I})=>I),R={role:"assistant",content:w||null},O=A||Ji(m);O&&(R.reasoning_content=O),v.length>0&&(R.tool_calls=v),ne(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:R,finish_reason:v.length>0?"tool_calls":"stop"}],usage:Hi(m)})}var wd="sense-latest";async function vd(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:wd,u=ie({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){K(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){K(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){K(n,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=l;let d=performance.now();r.model(u),await Pn(o,e,i),l.resolve_ms=Math.round(performance.now()-d);let c,f=performance.now();try{c=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},fe(o))}catch(p){if(p instanceof D){gt(n,"openai",p);return}if(p instanceof he){n.setHeader("retry-after","2"),K(n,503,p.message,"capacity_error");return}if(p instanceof le){n.setHeader("retry-after","2"),K(n,503,p.message,"capacity_error");return}throw p}l.dial_ms=Math.round(performance.now()-f);let y=[],g=null;try{for await(let p of r.track(c,u,o))if(g===null&&(g=performance.now(),l.first_event_ms=Math.round(g-f)),y.push(p),p.type==="error"){Cr(n,p,{inferenceId:o.id,operatorError:s});return}}catch(p){if(p instanceof D){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),gt(n,"openai",p);return}if(p instanceof he){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),K(n,503,p.message,"capacity_error");return}if(p instanceof le){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),K(n,503,p.message,"capacity_error");return}throw g!==null&&(l.stream_ms=Math.round(performance.now()-g)),p}g!==null&&(l.stream_ms=Math.round(performance.now()-g));let w=xe(y);if(w==null){K(n,502,"upstream produced no response.completed event","upstream_error");return}Ye(o,w);let A=st(y,w),S;try{S=JSON.parse(A)}catch{K(n,502,"systemone answer was not valid JSON","upstream_error");return}if(S===null||typeof S!="object"||Array.isArray(S)){K(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let p=S.timing;if(typeof p=="object"&&p!==null&&!Array.isArray(p)&&"question_fwd_ms"in p&&"head_ms"in p){let m=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;l.question_fwd_ms=m(p.question_fwd_ms),l.head_ms=m(p.head_ms)}}ne(n,200,S)}function bd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Bt=class extends Error{};function On(t){return new Bt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Sd(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function kd(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Bt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function xd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw On(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw On(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Rd(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw On(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:xd(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw On(u)}}return s(),r}function Tr(t){return rt(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function Ed(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Se(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){Se(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Se(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(R=>typeof R!="string"))){Se(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=ds(o.id),l=[],d;try{t.system&&l.push({role:"system",content:bd(t.system)});for(let R of i)l.push(...Rd(R));d=kd(t.tool_choice)}catch(R){if(R instanceof Bt){Se(n,400,"invalid_request_error",R.message);return}throw R}let c=ie(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Pn(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:l,stream:!0,tools:Sd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},fe(o))}catch(R){if(R instanceof D){gt(n,"anthropic",R);return}if(R instanceof he||R instanceof le){n.setHeader("retry-after","2"),Se(n,503,"capacity_error",R.message);return}throw R}let g=(R,O)=>{n.destroyed||n.write(`event: ${R}
65
65
  data: ${JSON.stringify({type:R,...O})}
66
66
 
67
- `)};if(t.stream===!0){let R=r.track(y,c,o);Pr(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,x="",I=0,b="none",C=()=>b,B=-1,F=-1,z=new $e,H=[],Te=()=>{b!=="none"&&(b="none",g("content_block_stop",{index:B}))},X=(V,Q)=>{Te(),b=V,B=I++,g("content_block_start",{index:B,content_block:Q})};for await(let V of R){if(n.destroyed)break;H.push(V);let Q=ot(V);if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:B,delta:{type:"thinking_delta",thinking:V.delta}});else if(V.type==="response.output_text.delta"&&typeof V.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),O+=1,x+=V.delta,g("content_block_delta",{index:B,delta:{type:"text_delta",text:V.delta}});else if(Q){let{call:ge}=z.add(Q);(C()!=="tool"||Q.tool_index!==F)&&(F=Q.tool_index,X("tool",{type:"tool_use",id:ge.id??`call_${Q.tool_index}`,name:ge.name??"",input:{}})),Q.delta&&g("content_block_delta",{index:B,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(V.type==="error"){o.streamError=!0;let ge=V.error,Fe=Ee(ge);Fe===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(V)}`),g("error",{error:{type:"api_error",message:Fe??ve(o.id)}}),n.end();return}}if(n.destroyed)return;let re=xe(H),L=rt(re),q=We(f,z.size+L.length,x);if(q){o.streamError=!0,g("error",{error:{type:"api_error",message:Je(c,q)}}),n.end();return}Te();let G=[];if(z.size===0)try{G=Tr(re)}catch(V){o.streamError=!0;let Q=de(V,{inferenceId:o.id});Q.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(V instanceof Error?V.message:V)}`),g("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&G.length===0&&(X("text",{type:"text",text:""}),Te()),G.forEach(V=>{let Q=I++;g("content_block_start",{index:Q,content_block:{...V,input:{}}}),g("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(V.input??{})}}),g("content_block_stop",{index:Q})});let De=z.size>0||G.length>0,Xe=An(re);Ye(o,re),g("message_delta",{delta:{stop_reason:De?"tool_use":"end_turn"},usage:Xe?{input_tokens:Xe.input_tokens,output_tokens:Xe.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let w="",A="",S=[],p=new $e;for await(let R of r.track(y,c,o)){S.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(A+=R.delta);let O=ot(R);if(O&&p.add(O),R.type==="error"){let x=R.error,I=x?.type==="invalid_request_error",b=Ee(x);b===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),Se(n,I?400:502,I?"invalid_request_error":"api_error",b??ve(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=xe(S);Ye(o,m);let h;try{h=Tr(m),h.length===0&&p.size>0&&(h=Tr({output:p.items()}))}catch(R){let O=de(R,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),Se(n,502,"api_error",O.message);return}let _=We(f,h.length,w);if(_){Se(n,502,"api_error",Je(c,_));return}let k=[],v=A||Ji(m);v&&k.push({type:"thinking",thinking:v}),(w||h.length===0)&&k.push({type:"text",text:w}),k.push(...h),ne(n,200,{id:a,type:"message",role:"assistant",content:k,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:An(m)??{input_tokens:0,output_tokens:0}})}function Ad(t){be(process.stdout,t)}function Id(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Ad,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new Ge;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),y=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),g=(m,h,_,k,v)=>y?Se(c,m,k,h):K(c,m,h,_,v),w=Zn(f.pathname),A=f.pathname.startsWith("/partners/"),S=w||A?{id:Rt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader(as,S.id),c.once("close",()=>{let m=cs({turn:S,method:d.method??"",path:f.pathname,res:c});i(ps(m)),a?.(m),ji({record:m,ledger:t.ledger??null,req:d})}));let p=()=>us(f.pathname,S);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){ne(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){ne(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=f.pathname===Pi?"canonical":f.pathname===Ir?"huggingface":null;if(m){if(d.method!=="POST"){g(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){g(501,`${f.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let R=v.authorize(d),O;try{O=await qi(d,Ci)}catch(b){if(b instanceof Ft){g(413,b.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=b=>v.lookup(R,b),I;try{if(m==="canonical"){let b=Mi(O),C=await x(b);En(C,b),I={requests:C}}else I=await Li(O,x)}catch(b){if(b instanceof Ue){g(b.status,b.message,"invalid_request_error","invalid_request_error");return}throw b}ne(c,200,I);return}if(d.method==="GET"&&f.pathname===bt){let v=await s(d);if(S&&(S.org=v.tenant??null),!v.openRouterModels){g(501,`GET ${bt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ne(c,200,await v.openRouterModels());return}if(f.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${Ir} and GET ${bt}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:bt}),c.end();return}ne(c,200,await h.listModels());return}if(d.method==="GET"&&f.pathname===ti){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(c,200,await h.listImageModels());return}if(ei(f.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:h,imageModels:h.supportsImages,stats:l,turn:p(),operatorLog:u};f.pathname===bn?await ci(d,c,v):await di(d,c,v);return}if(d.method==="GET"&&f.pathname===Ei){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await h.listSpeechToTextModels());return}if(Ri(f.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Rn}`,"not_implemented","not_implemented_error");return}let v={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:p(),operatorLog:u};await Oi(d,c,v);return}if(vi(f.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Lt}`,"not_implemented","not_implemented_error");return}let v={clients:h,speechModels:h.supportsSpeech,stats:l,turn:p(),operatorLog:u};await xi(d,c,v);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await qi(d)}catch(v){if(v instanceof Ft){g(413,v.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=Buffer.byteLength(JSON.stringify(_));if(f.pathname==="/v1/responses"){l.request("responses",k,k),await yd(_,h,At(h),c,l,p(),u);return}if(f.pathname==="/v1/chat/completions"){l.request("chat_completions",k,k),await _d(_,h,c,l,p(),d.headers[Sr],u);return}if(f.pathname==="/v1/systemone"){l.request("systemone",k,k),await vd(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages"){l.request("messages",k,k),await Ed(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",k,k),Se(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let h=String(m instanceof Error?m.message:m);if(!c.headersSent){let v=o?.(m)??null;if(v){v.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),g(v.status,h,v.openaiType,v.anthropicType);return}if(m instanceof Tn.SessionAllocationError){let O=ln(m.code);if(O){let x=m.retryAfterSeconds??(O.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof Tn.SessionFailedError){let O=dn(m);if(O){let x=O.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof ft){g(502,h,"upstream_error","api_error");return}if(m instanceof ye){m.retryable&&c.setHeader("Retry-After","1");let O=de(m,{inferenceId:S?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof Le){c.setHeader("Retry-After",String(m.retryAfterSeconds)),g(m.status,h,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let R=de(m,{inferenceId:S?.id??null});R.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(500,R.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let _=m instanceof ye?m.code:null,k=de(m,{inferenceId:S?.id??null});k.redacted&&u(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),c.destroyed||(y?c.write(`event: error
67
+ `)};if(t.stream===!0){let R=r.track(y,c,o);Pr(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,x="",I=0,b="none",C=()=>b,B=-1,F=-1,z=new $e,H=[],Te=()=>{b!=="none"&&(b="none",g("content_block_stop",{index:B}))},X=(V,Q)=>{Te(),b=V,B=I++,g("content_block_start",{index:B,content_block:Q})};for await(let V of R){if(n.destroyed)break;H.push(V);let Q=ot(V);if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:B,delta:{type:"thinking_delta",thinking:V.delta}});else if(V.type==="response.output_text.delta"&&typeof V.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),O+=1,x+=V.delta,g("content_block_delta",{index:B,delta:{type:"text_delta",text:V.delta}});else if(Q){let{call:ge}=z.add(Q);(C()!=="tool"||Q.tool_index!==F)&&(F=Q.tool_index,X("tool",{type:"tool_use",id:ge.id??`call_${Q.tool_index}`,name:ge.name??"",input:{}})),Q.delta&&g("content_block_delta",{index:B,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(V.type==="error"){o.streamError=!0;let ge=V.error,Fe=Ee(ge);Fe===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(V)}`),g("error",{error:{type:"api_error",message:Fe??ve(o.id)}}),n.end();return}}if(n.destroyed)return;let re=xe(H),L=rt(re),q=We(f,z.size+L.length,x);if(q){o.streamError=!0,g("error",{error:{type:"api_error",message:Je(c,q)}}),n.end();return}Te();let G=[];if(z.size===0)try{G=Tr(re)}catch(V){o.streamError=!0;let Q=de(V,{inferenceId:o.id});Q.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(V instanceof Error?V.message:V)}`),g("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&G.length===0&&(X("text",{type:"text",text:""}),Te()),G.forEach(V=>{let Q=I++;g("content_block_start",{index:Q,content_block:{...V,input:{}}}),g("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(V.input??{})}}),g("content_block_stop",{index:Q})});let De=z.size>0||G.length>0,Xe=An(re);Ye(o,re),g("message_delta",{delta:{stop_reason:De?"tool_use":"end_turn"},usage:Xe?{input_tokens:Xe.input_tokens,output_tokens:Xe.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let w="",A="",S=[],p=new $e;for await(let R of r.track(y,c,o)){S.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(A+=R.delta);let O=ot(R);if(O&&p.add(O),R.type==="error"){let x=R.error,I=x?.type==="invalid_request_error",b=Ee(x);b===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),Se(n,I?400:502,I?"invalid_request_error":"api_error",b??ve(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=xe(S);Ye(o,m);let h;try{h=Tr(m),h.length===0&&p.size>0&&(h=Tr({output:p.items()}))}catch(R){let O=de(R,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),Se(n,502,"api_error",O.message);return}let _=We(f,h.length,w);if(_){Se(n,502,"api_error",Je(c,_));return}let k=[],v=A||Ji(m);v&&k.push({type:"thinking",thinking:v}),(w||h.length===0)&&k.push({type:"text",text:w}),k.push(...h),ne(n,200,{id:a,type:"message",role:"assistant",content:k,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:An(m)??{input_tokens:0,output_tokens:0}})}function Ad(t){be(process.stdout,t)}function Id(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Ad,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new Ge;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),y=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),g=(m,h,_,k,v)=>y?Se(c,m,k,h):K(c,m,h,_,v),w=Zn(f.pathname),A=f.pathname.startsWith("/partners/"),S=w||A?{id:Rt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader(as,S.id),c.once("close",()=>{let m=cs({turn:S,method:d.method??"",path:f.pathname,res:c});i(ps(m)),a?.(m),ji({record:m,ledger:t.ledger??null,req:d})}));let p=()=>us(f.pathname,S);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){ne(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){ne(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=f.pathname===Pi?"canonical":f.pathname===Ir?"huggingface":null;if(m){if(d.method!=="POST"){g(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){g(501,`${f.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let R=v.authorize(d),O;try{O=await qi(d,Ci)}catch(b){if(b instanceof Ft){g(413,b.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=b=>v.lookup(R,b),I;try{if(m==="canonical"){let b=Mi(O),C=await x(b);En(C,b),I={requests:C}}else I=await Li(O,x)}catch(b){if(b instanceof Ue){g(b.status,b.message,"invalid_request_error","invalid_request_error");return}throw b}ne(c,200,I);return}if(d.method==="GET"&&f.pathname===bt){let v=await s(d);if(S&&(S.org=v.tenant??null),!v.openRouterModels){g(501,`GET ${bt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ne(c,200,await v.openRouterModels());return}if(f.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${Ir} and GET ${bt}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:bt}),c.end();return}ne(c,200,await h.listModels());return}if(d.method==="GET"&&f.pathname===ti){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(c,200,await h.listImageModels());return}if(ei(f.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:h,imageModels:h.supportsImages,stats:l,turn:p(),operatorLog:u};f.pathname===bn?await ci(d,c,v):await di(d,c,v);return}if(d.method==="GET"&&f.pathname===Ei){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await h.listSpeechToTextModels());return}if(Ri(f.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Rn}`,"not_implemented","not_implemented_error");return}let v={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:p(),operatorLog:u};await Oi(d,c,v);return}if(vi(f.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Lt}`,"not_implemented","not_implemented_error");return}let v={clients:h,speechModels:h.supportsSpeech,stats:l,turn:p(),operatorLog:u};await xi(d,c,v);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await qi(d)}catch(v){if(v instanceof Ft){g(413,v.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=Buffer.byteLength(JSON.stringify(_));if(f.pathname==="/v1/responses"){l.request("responses",k,k),await yd(_,h,At(h),c,l,p(),u);return}if(f.pathname==="/v1/chat/completions"){l.request("chat_completions",k,k),await _d(_,h,c,l,p(),d.headers[Sr],u);return}if(f.pathname==="/v1/systemone"){l.request("systemone",k,k),await vd(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages"){l.request("messages",k,k),await Ed(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",k,k),Se(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let h=String(m instanceof Error?m.message:m);if(!c.headersSent){let v=o?.(m)??null;if(v){v.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),g(v.status,h,v.openaiType,v.anthropicType,v.code);return}if(m instanceof Tn.SessionAllocationError){let O=ln(m.code);if(O){let x=m.retryAfterSeconds??(O.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof Tn.SessionFailedError){let O=dn(m);if(O){let x=O.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof ft){g(502,h,"upstream_error","api_error");return}if(m instanceof ye){m.retryable&&c.setHeader("Retry-After","1");let O=de(m,{inferenceId:S?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof Le){c.setHeader("Retry-After",String(m.retryAfterSeconds)),g(m.status,h,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let R=de(m,{inferenceId:S?.id??null});R.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(500,R.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let _=m instanceof ye?m.code:null,k=de(m,{inferenceId:S?.id??null});k.redacted&&u(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),c.destroyed||(y?c.write(`event: error
68
68
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:k.message}})}
69
69
 
70
70
  `):c.write(`data: ${JSON.stringify({error:{message:k.message,type:"upstream_error",code:_}})}
package/dist/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as J,b as q,c as H,d as Y,e as V}from"../chunk-KTMDSM7F.js";import"../chunk-CAR4AEQJ.js";import{E as K}from"../chunk-7OH7UJ2H.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-L6HTHDVV.js";import{a as v,b as $,c as C,d as U,e as I,f as L,g as N,h as O,i as x,j as _,k as g,m as G,n as P,o as D,p as M,q as A,r as W,s as b,t as B,u as j,v as F}from"../chunk-M3YMNU5P.js";import"../chunk-GL7EWL3V.js";import"../chunk-NN6TQQUG.js";import"../chunk-OOCRI7ZM.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{a as J,b as q,c as H,d as Y,e as V}from"../chunk-7D2HMQFC.js";import"../chunk-CAR4AEQJ.js";import{E as K}from"../chunk-GR3UAW6P.js";import"../chunk-3JWYIKHM.js";import{g as R}from"../chunk-6M5JK4YC.js";import"../chunk-L6HTHDVV.js";import{a as v,b as $,c as C,d as U,e as I,f as L,g as N,h as O,i as x,j as _,k as g,m as G,n as P,o as D,p as M,q as A,r as W,s as b,t as B,u as j,v as F}from"../chunk-NL3UBLXV.js";import"../chunk-GL7EWL3V.js";import"../chunk-NN6TQQUG.js";import"../chunk-OOCRI7ZM.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)}