@urun-sh/openai 0.6.55 → 0.6.56
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.
- package/dist/{chunk-Z74YK7AL.js → chunk-6R3TCKOH.js} +1 -1
- package/dist/{chunk-BVM4ZQ2Y.js → chunk-B3GQYAJ5.js} +1 -1
- package/dist/{chunk-PPEND4SP.js → chunk-MBIJRS4O.js} +11 -11
- package/dist/{chunk-HLSJAQHY.js → chunk-NMNR3SQ5.js} +1 -1
- package/dist/{chunk-4UE7XH7T.js → chunk-WXO7IIRV.js} +1 -1
- package/dist/{composite-C1oeSkNz.d.cts → composite-CIOofxp2.d.cts} +10 -6
- package/dist/{composite-CmDZAzTq.d.ts → composite-lokLYIya.d.ts} +1 -1
- package/dist/hosted/bin.cjs +2 -2
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +2 -2
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +3 -3
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +9 -9
- package/dist/proxy/index.d.cts +8 -2
- package/dist/proxy/index.d.ts +4 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
package/dist/proxy/index.cjs
CHANGED
|
@@ -4,25 +4,25 @@ Connection: close\r
|
|
|
4
4
|
\r
|
|
5
5
|
${f}\r
|
|
6
6
|
`),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}function wr(t,e,n=new We){new jt(t,e,n)}var Oe=require("ws");var vr=require("crypto"),br="Inference-Id";function ft(){return(0,vr.randomUUID)()}function yn(t){return t==="/v1"||t.startsWith("/v1/")}function Sr(t,e){if(!yn(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 mt(t){return`resp_${t}`}function kr(t){return`chatcmpl-${t}`}function xr(t){return`msg_${t}`}function pe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Rr(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_seconds:null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Er(t){return`${JSON.stringify(t)}
|
|
7
|
-
`}var _i=256,wi=128;function se(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,wi)}var $e=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>=_i?"(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,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},vi=256;function bi(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 Le=class extends Error{},Ke=class{conversations=new Map;thread(e,n){let r=bi(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Le(`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 i of this.conversations.keys()){if(this.conversations.size<=vi)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Ar=new WeakMap;function ht(t){let e=Ar.get(t);return e||(e=new Ke,Ar.set(t,e)),e}function ze(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function be(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ye(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 Te=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}))}},Si=["<tool_call>","<function="];function ki(t){return Si.find(e=>t.includes(e))}function Ne(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 Ue(t,e,n){if(!(!t||e>0))return ki(n)}function Xe(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 Ae(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function xi(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 _n(t,e){let n=xi(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var fe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Qe(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Le?new fe(n.message,"previous_response_not_found",400,"previous_response_id"):new fe(String(n instanceof Error?n.message:n),"invalid_input")}}function Ir(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function wn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new fe("instructions must be a string","invalid_instructions");let i=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,...i!==void 0?{instructions:i}:{},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}:{},...Ir(e)!==void 0?{response_format:Ir(e)}:{}},o)}async function gt(t){let{body:e,clients:n,store:r,stats:o}=t,i=Qe(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=se(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await wn(n,e,i,!0,c?pe(c):void 0);return{responseId:s,events:Ii({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Ri(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?Ai(o[s++],u):u),...Ei(r,n)]}function Ei(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??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.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"?!a&&!u.has(o(d)):!0})}function Ai(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Ii(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=C=>C.response&&typeof C.response=="object"?{...C,response:{...C.response,id:r}}:C,p=`item_${r.slice(5)}`,f=!1,m=!1,b=0;function*k(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let _=[],y=(C,N)=>{_.push({output_index:C,item:N})},h=!1,v=0,$="",P=0,I="";function*x(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:$,output_index:v,content_index:0,text:I};let C={id:$,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:I}],status:"completed"};yield{type:"response.output_item.done",output_index:v,item:C},y(v,C),I=""}let A=!1,g=0,w="",E=0,M="",F="";function*j(C){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:w,output_index:g,content_index:0,text:M},yield{type:"response.content_part.done",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:M}};let N={id:w,type:"message",role:"assistant",status:C,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:g,item:N},y(g,N),M=""}let L=new Te,D=null,G=-1;function*O(C){if(!D)return;let N=D;D=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let W={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:C};yield{type:"response.output_item.done",output_index:N.outputIndex,item:W},y(N.outputIndex,W)}let z=!1;for await(let C of l.track(e,o,t.turn)){d.push(C);let N=String(C.type??"");if(N==="response.created"||N==="response.in_progress"){f=!0,yield c(C);continue}if(N==="response.output_item.added"){m=!0,yield c(C);continue}if(N==="response.reasoning_text.delta"&&!m){yield*k(),h||(h=!0,v=b++,P+=1,$=P===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${P}`,yield{type:"response.output_item.added",output_index:v,item:{id:$,type:"reasoning",summary:[],content:[],status:"in_progress"}}),I+=String(C.delta??""),yield{type:"response.reasoning_text.delta",item_id:$,output_index:v,content_index:0,delta:C.delta};continue}if(N==="response.output_text.delta"&&!m){yield*k(),yield*x(),A||(A=!0,g=b++,E+=1,w=E===1?p:`${p}_${E}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:""}}),M+=String(C.delta??""),F+=String(C.delta??""),yield{type:N,item_id:w,output_index:g,content_index:0,delta:C.delta};continue}let W=m?null:Ye(C);if(W){if(yield*k(),yield*x(),yield*j("completed"),L.add(W),W.tool_index!==G){yield*O("completed"),G=W.tool_index;let ve=b++;D={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:ve,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:ve,item:{id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:"",status:"in_progress"}}}D&&(W.call_id&&(D.callId=W.call_id),W.name&&(D.name=W.name),D.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:D.fcId,output_index:D.outputIndex,delta:W.delta});continue}if(N==="response.completed"&&!m){let ve=ze(C.response),Ge=Ue(i,L.size+ve.length,F);if(Ge){z=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ne(o,Ge)}};break}if(yield*x(),yield*j("completed"),yield*O("completed"),L.size===0)for(let ee of ve){let he=b++,Ce=ee.id??ee.call_id??`fc_${he}`,fn=ee.arguments??"",zn={id:Ce,type:"function_call",call_id:ee.call_id??Ce,name:ee.name??""};yield{type:"response.output_item.added",output_index:he,item:{...zn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ce,output_index:he,delta:fn},yield{type:"response.function_call_arguments.done",item_id:Ce,output_index:he,arguments:fn};let Yn={...zn,arguments:fn,status:"completed"};yield{type:"response.output_item.done",output_index:he,item:Yn},y(he,Yn)}let Y=Ri(_,C.response);yield Y.length>0?c({...C,response:{...C.response,output:Y}}):c(C);continue}yield c(C)}if(yield*x(),yield*j("incomplete"),yield*O("incomplete"),s&&!z){let C=be(d);u.remember(r,n,_n(C,Xe(d,C)),a)}}var Se=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 Ze=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ge=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var Ti=require("@urun-sh/core"),De=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var Oi=[/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 ye(t){return!Oi.some(e=>e.test(t))}function _e(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 X)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=Tr(t);return n||{message:_e(e?.inferenceId??null),redacted:!0}}function Tr(t){return t instanceof $t?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof dt?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof J?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:t instanceof Ze?{message:t.message,redacted:!1}:t instanceof De?ye(t.message)?{message:t.message,redacted:!1}:null:t instanceof ge?{message:t.message,redacted:!1}:t instanceof le?{message:t.message,redacted:!1}:null}function et(t,e,n){let r=n??(s=>console.error(s)),o=Tr(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${me(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ye(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${me(e)}`),`the ${t} upstream failed while serving this request`)}function ke(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ye(e)?e:null}function me(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Pi="/v1/responses",Ci=64*1024*1024,Mi=8*1024*1024,$i=16,Or=32,Pr=3600*1e3,Li=/^[A-Za-z0-9._-]{1,256}$/;function ae(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ni=ae(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Sn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ui(t){for(;t.bufferedAmount>Mi&&t.readyState===Oe.WebSocket.OPEN;){let{promise:e,resolve:n}=Sn();setTimeout(n,5),await e}}var vn=class extends Ke{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 Le))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},bn=class{constructor(e,n,r,o,i){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=i;this.store=new vn(ht(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Pr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Pr).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(ae(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ae(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ae(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ae(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(ae(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ae(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Li.test(o.stream_id)){this.sendFrame(Ni);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Or){this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Or}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).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=ft();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await gt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mt(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(i.responseId,n??null);let s=i.events;this.activeTurns.add(s);try{for await(let a of s){if(this.closed||this.ws.readyState!==Oe.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ui(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=ft(),o=mt(r);try{let i=Qe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,i,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(i){this.failTurn(i,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(n??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:me(e);if(e instanceof fe)return ae(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof J)return ae(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=de(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ae(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),ae(i.status,{type:i.openaiType,message:o},n);let s=de(e,{inferenceId:r});return s.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ae(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=ke(o),a=s??_e(r);return s===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ae(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=$i;){let{promise:e,resolve:n}=Sn();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!==Oe.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!==Oe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Jt(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
7
|
+
`}var _i=256,wi=128;function se(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,wi)}var $e=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>=_i?"(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,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},vi=256;function bi(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 Le=class extends Error{},Ke=class{conversations=new Map;thread(e,n){let r=bi(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Le(`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 i of this.conversations.keys()){if(this.conversations.size<=vi)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Ar=new WeakMap;function ht(t){let e=Ar.get(t);return e||(e=new Ke,Ar.set(t,e)),e}function ze(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function be(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ye(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 Te=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}))}},Si=["<tool_call>","<function="];function ki(t){return Si.find(e=>t.includes(e))}function Ne(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 Ue(t,e,n){if(!(!t||e>0))return ki(n)}function Xe(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 Ae(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function xi(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 _n(t,e){let n=xi(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var fe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Qe(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Le?new fe(n.message,"previous_response_not_found",400,"previous_response_id"):new fe(String(n instanceof Error?n.message:n),"invalid_input")}}function Ir(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function wn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new fe("instructions must be a string","invalid_instructions");let i=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,...i!==void 0?{instructions:i}:{},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}:{},...Ir(e)!==void 0?{response_format:Ir(e)}:{}},o)}async function gt(t){let{body:e,clients:n,store:r,stats:o}=t,i=Qe(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=se(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await wn(n,e,i,!0,c?pe(c):void 0);return{responseId:s,events:Ii({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Ri(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?Ai(o[s++],u):u),...Ei(r,n)]}function Ei(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??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.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"?!a&&!u.has(o(d)):!0})}function Ai(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Ii(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=C=>C.response&&typeof C.response=="object"?{...C,response:{...C.response,id:r}}:C,p=`item_${r.slice(5)}`,f=!1,m=!1,b=0;function*k(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let _=[],y=(C,N)=>{_.push({output_index:C,item:N})},h=!1,v=0,$="",P=0,I="";function*R(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:$,output_index:v,content_index:0,text:I};let C={id:$,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:I}],status:"completed"};yield{type:"response.output_item.done",output_index:v,item:C},y(v,C),I=""}let A=!1,g=0,w="",E=0,M="",F="";function*j(C){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:w,output_index:g,content_index:0,text:M},yield{type:"response.content_part.done",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:M}};let N={id:w,type:"message",role:"assistant",status:C,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:g,item:N},y(g,N),M=""}let L=new Te,D=null,G=-1;function*O(C){if(!D)return;let N=D;D=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let W={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:C};yield{type:"response.output_item.done",output_index:N.outputIndex,item:W},y(N.outputIndex,W)}let z=!1;for await(let C of l.track(e,o,t.turn)){d.push(C);let N=String(C.type??"");if(N==="response.created"||N==="response.in_progress"){f=!0,yield c(C);continue}if(N==="response.output_item.added"){m=!0,yield c(C);continue}if(N==="response.reasoning_text.delta"&&!m){yield*k(),h||(h=!0,v=b++,P+=1,$=P===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${P}`,yield{type:"response.output_item.added",output_index:v,item:{id:$,type:"reasoning",summary:[],content:[],status:"in_progress"}}),I+=String(C.delta??""),yield{type:"response.reasoning_text.delta",item_id:$,output_index:v,content_index:0,delta:C.delta};continue}if(N==="response.output_text.delta"&&!m){yield*k(),yield*R(),A||(A=!0,g=b++,E+=1,w=E===1?p:`${p}_${E}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:""}}),M+=String(C.delta??""),F+=String(C.delta??""),yield{type:N,item_id:w,output_index:g,content_index:0,delta:C.delta};continue}let W=m?null:Ye(C);if(W){if(yield*k(),yield*R(),yield*j("completed"),L.add(W),W.tool_index!==G){yield*O("completed"),G=W.tool_index;let ve=b++;D={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:ve,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:ve,item:{id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:"",status:"in_progress"}}}D&&(W.call_id&&(D.callId=W.call_id),W.name&&(D.name=W.name),D.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:D.fcId,output_index:D.outputIndex,delta:W.delta});continue}if(N==="response.completed"&&!m){let ve=ze(C.response),Ge=Ue(i,L.size+ve.length,F);if(Ge){z=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ne(o,Ge)}};break}if(yield*R(),yield*j("completed"),yield*O("completed"),L.size===0)for(let ee of ve){let he=b++,Ce=ee.id??ee.call_id??`fc_${he}`,fn=ee.arguments??"",zn={id:Ce,type:"function_call",call_id:ee.call_id??Ce,name:ee.name??""};yield{type:"response.output_item.added",output_index:he,item:{...zn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ce,output_index:he,delta:fn},yield{type:"response.function_call_arguments.done",item_id:Ce,output_index:he,arguments:fn};let Yn={...zn,arguments:fn,status:"completed"};yield{type:"response.output_item.done",output_index:he,item:Yn},y(he,Yn)}let Y=Ri(_,C.response);yield Y.length>0?c({...C,response:{...C.response,output:Y}}):c(C);continue}yield c(C)}if(yield*R(),yield*j("incomplete"),yield*O("incomplete"),s&&!z){let C=be(d);u.remember(r,n,_n(C,Xe(d,C)),a)}}var Se=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 Ze=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ge=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var Ti=require("@urun-sh/core"),De=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var Oi=[/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 ye(t){return!Oi.some(e=>e.test(t))}function _e(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 X)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=Tr(t);return n||{message:_e(e?.inferenceId??null),redacted:!0}}function Tr(t){return t instanceof $t?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof dt?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof J?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:t instanceof Ze?{message:t.message,redacted:!1}:t instanceof De?ye(t.message)?{message:t.message,redacted:!1}:null:t instanceof ge?{message:t.message,redacted:!1}:t instanceof le?{message:t.message,redacted:!1}:null}function et(t,e,n){let r=n??(s=>console.error(s)),o=Tr(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${me(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ye(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${me(e)}`),`the ${t} upstream failed while serving this request`)}function ke(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ye(e)?e:null}function me(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Pi="/v1/responses",Ci=64*1024*1024,Mi=8*1024*1024,$i=16,Or=32,Pr=3600*1e3,Li=/^[A-Za-z0-9._-]{1,256}$/;function ae(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ni=ae(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Sn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ui(t){for(;t.bufferedAmount>Mi&&t.readyState===Oe.WebSocket.OPEN;){let{promise:e,resolve:n}=Sn();setTimeout(n,5),await e}}var vn=class extends Ke{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 Le))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},bn=class{constructor(e,n,r,o,i){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=i;this.store=new vn(ht(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Pr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Pr).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(ae(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ae(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ae(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ae(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(ae(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ae(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Li.test(o.stream_id)){this.sendFrame(Ni);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Or){this.sendFrame(ae(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Or}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).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=ft();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await gt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mt(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(i.responseId,n??null);let s=i.events;this.activeTurns.add(s);try{for await(let a of s){if(this.closed||this.ws.readyState!==Oe.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ui(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=ft(),o=mt(r);try{let i=Qe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,i,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(i){this.failTurn(i,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(n??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:me(e);if(e instanceof fe)return ae(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof J)return ae(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=de(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ae(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),ae(i.status,{type:i.openaiType,message:o},n);let s=de(e,{inferenceId:r});return s.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ae(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=ke(o),a=s??_e(r);return s===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ae(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=$i;){let{promise:e,resolve:n}=Sn();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!==Oe.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!==Oe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Jt(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
8
8
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
9
9
|
Connection: close\r
|
|
10
10
|
Content-Type: text/plain; charset=utf-8\r
|
|
11
11
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
12
12
|
\r
|
|
13
|
-
${o}`)}function Cr(t,e){let n=new Oe.WebSocketServer({noServer:!0,maxPayload:Ci}),r=new $e,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Jt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),f.pathname!==Pi){s.add(c);return}i.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Jt(c,401,"invalid local proxy api key");return}let b;try{b=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Jt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(m=!0,n.handleUpgrade(d,c,p,k=>{i.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new bn(k,b,r,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Jt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Sn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let p=setTimeout(()=>{for(let f of o)f.readyState!==Oe.WebSocket.CLOSED&&f.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Mn=require("@urun-sh/core");var Mr=require("@urun-sh/core"),Di={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},Fi={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 yt(t,e){let n=Fi[t.code];return e?`${n} (${e})`:n}function Gt(t){if(t==null)return null;let e=Di[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 Vt(t){if(t.kind==="create-failed")return Gt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Mr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Gt(e?"cold_start_exceeded":"queue_timeout")}var Bi=Qn(require("os"),1),qi=Qn(require("path"),1),ji=require("url"),Hi=require("util");var Ji=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Gi(t){let e=t?.code;return typeof e=="string"&&Ji.has(e)}function Fe(t,e){try{return t.write(e),!0}catch(n){if(Gi(n))return!1;throw n}}var wt=require("ws");var Ur=require("@urun-sh/core");var Lr=require("crypto");function R(t){return`${t}_${(0,Lr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Wt=4*1024*1024,kn=8*1024*1024,xn=512,nt=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function xe(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:R("event"),error:t}}function Rn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Vi={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},Wi={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ki={format:!0,voice:!0,speed:!0};function zi(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function tt(t,e){if(!Array.isArray(t)||t.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function $r(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Yi=10;function En(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:Yi})}function _t(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new T("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in Vi));if(i.length>0)throw new T(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=tt(o.modalities,"modalities"),u=tt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new T('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new T(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=tt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new T('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!zi(u))throw new T(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new T("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");s.instructions=En(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!n.voice)throw new T("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new T(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new T("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new T(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new T("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new T("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new T("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,f]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new T(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(f!=null&&f!==c[p])throw new T(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new T("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new T("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new T(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new T(`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")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new T("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Wi))throw new T(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&$r(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=_t({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=_t({turn_detection:d.turn_detection},s,n,r);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ki))throw new T(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&$r(d.format,"audio.output.format"),d.speed!==void 0)throw new T("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new T("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new T("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Kt(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 An(t,e){let n=t;if(!n||typeof n!="object")throw new T("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 T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("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 T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new T("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new T("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new T(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new T("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new T("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new T("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new T("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new T("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new T(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new T(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function zt(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 i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Xi=1001,Qi=1011,Zi=6e4,es=3e5,In=3;var Yt=class extends Error{},Xt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Be=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Tn=t=>t.slice(0,120),ts=/^[A-Za-z0-9+/=]*$/,ns=600;function On(t){return Lt(Buffer.from(t,"base64"))}var qe=class{id=R("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Rn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Zi,this.responseDeadlineMs=e.responseDeadlineMs??es,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.binding.onSessionEnd?.(n=>{n.reason===mn&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:R("event"),session:Kt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(V(xe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("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:R("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(i=>i.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:R("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:R("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:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),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:R("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:R("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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 s=R("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:R("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Wt){this.fail(Q("frame_too_large",`frame exceeds the ${Wt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(V({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(o instanceof Yt){this.fail(xe(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
14
|
-
${o?.stack??me(o)}`),this.send(V(xe(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=_t(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(V(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:R("event"),session:Kt(this.config,this.sessionId)});return}case"conversation.item.create":{let n=An(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(i=>i.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:R("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(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:R("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(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("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(V(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:R("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(V(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ts.test(e.audio)){this.send(V(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>nt&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${nt}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${nt} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>nt&&this.pendingAudioBytes.length>0;){let i=this.pendingAudioBytes.shift();o-=Buffer.byteLength(i.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(V(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("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:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:R("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:R("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(V(Q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(Q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(V(Q("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,Tn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Yt("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(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let i;if(o||this.turnStallMs<=0){o=!1;let s=n.next();s.catch(()=>{}),i=r?await Promise.race([s,r]):await s}else{let s,a=new Promise((d,c)=>{s=setTimeout(()=>c(new Xt),this.turnStallMs)}),u=n.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(s))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return this.config.model&&i.model===void 0&&(i.model=this.config.model),r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(V(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?tt(r.modalities,"response.modalities"):void 0,i=r.output_modalities!==void 0?tt(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&i!==void 0&&o.slice().sort().join(",")!==i.slice().sort().join(","))throw new T("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((i??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(V(Q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},u=new Promise((x,A)=>{a=()=>A(new Be)});this.turnCancelled=u,this.wakeTurnCancelled=()=>a(),u.catch(()=>{});let l=()=>{},d=new Promise((x,A)=>{l=()=>A(new Be)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=R("req"),f=`resp_${p}`;this.activeResponseId=f,this.activeRequestId=p;let m=this.binding.composite===!0,b=m?0:this.items.length,k=m?null:zt(this.items),_=En(typeof r.instructions=="string"?r.instructions:this.config.instructions),y=typeof r.temperature=="number"?r.temperature:this.config.temperature,h=r.max_output_tokens??this.config.maxOutputTokens,v=h==="inf"||h===void 0?void 0:h,$=r.tools!==void 0?r.tools:this.config.tools,P=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,I={stream:!0,...this.config.model?{model:this.config.model}:{},..._!==void 0?{instructions:_}:{},...y!==void 0?{temperature:y}:{},...v!==void 0?{max_output_tokens:v}:{},...$!==void 0?{tools:$}:{},...P!==void 0?{tool_choice:P}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,A);this.inFlight=(async()=>{let x=[],A=F=>{this.responseFlushed?this.send(F):x.push(F)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(f,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(f,"in_progress")});for(let F of x)this.send(F);x.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},E=null,M=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(f,w,b),g(),this.send({type:"response.done",event_id:R("event"),response:this.responseObject(f,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(G=>{this.pendingTranscriptSettled=G}),this.cancelled||this.closed))throw new Be;b=this.items.length,k=zt(this.items)}let{input:F,sawAudioOnlyItem:j}=k??{input:[],sawAudioOnlyItem:!1},L={...I,input:F,...m?this.compositeTurnAsk(r):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let D;try{let G=this.upstreamStream(L,p);Promise.resolve(G).catch(O=>{O instanceof X&&this.failSessionGone(O)}),D=await Promise.race([G,d])}catch(G){if(G instanceof Be){this.deadlineFired&&!this.closed&&M();return}this.upstreamTurnFault(G,f);return}g();try{for await(let G of this.stallBoundedTurn(D)){if(this.cancelled)break;let O=G;if(O.type==="error"){let z=this.upstreamErrorBody(O);w.contentFlowed?this.send(V(z)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(f,z)});return}if(O.type==="response.output_text.delta"&&typeof O.delta=="string"){g(),w.contentFlowed=!0,w.messageOpen||(this.beginMessageItem(f,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:R("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:O.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:R("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:O.delta})),w.messageText+=O.delta;continue}if(O.type==="response.function_call_arguments.delta"){g(),w.contentFlowed=!0;let z=typeof O.delta=="string"?O.delta:"",C=typeof O.call_id=="string"&&O.call_id.length>0?O.call_id:`${f}_fc_${w.nextOutputIndex}`,N=w.tools.get(C);if(!N){let W=typeof O.name=="string"&&O.name.length>0?O.name:void 0;N={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(C,N);let ve={id:C,object:"realtime.item",type:"function_call",call_id:C,name:W??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:R("event"),response_id:f,output_index:N.outputIndex,item:ve}),this.emitAssistantItemAdded(ve)}typeof O.name=="string"&&O.name.length>0&&(N.name=O.name),N.args+=z,A({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:C,response_id:f,output_index:N.outputIndex,call_id:C,name:N.name??"",delta:z});continue}if(O.type==="response.completed"){E=O.response??null;continue}}}catch(G){if(this.closed)return;if(G instanceof Be){this.deadlineFired&&M();return}if(this.cancelled)return;if(G instanceof Xt)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${f} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(G,f);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&M();return}this.closeOpenItems(f,w,b),g(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(f,b,E)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(w.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=In){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${In} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(V(xe("member_unresponsive",`the member served no content for ${In} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(On(n))return;this.openDuplexResponse()}else if(On(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=ns){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(On(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({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:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${R("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:R("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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:R("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:R("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:R("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:R("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:R("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`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:R("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:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:R("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:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.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,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,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=ke(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??_e(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(xe(hn,"the organization is out of credits \u2014 top up to continue"),hn))}failSessionGone(e){if(e instanceof X&&e.reason===mn){this.failInsufficientCredits();return}let n=e instanceof Error&&ye(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: ${me(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(xe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ur.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=xe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>xn&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(V(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>gn){this.send(V(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${gn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(V(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(V(xe(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>kn){this.ws.close(Xi,Tn("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: ${me(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Qi,Tn(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.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Nr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Nr(this.id,e)}},Pn=[];function Nr(t,e){Pn.push({id:t,reason:e}),Pn.length>256&&Pn.shift()}var vt="/v1/realtime",Dr="urun.admission",Fr=t=>t.slice(0,120);function rs(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
|
|
13
|
+
${o}`)}function Cr(t,e){let n=new Oe.WebSocketServer({noServer:!0,maxPayload:Ci}),r=new $e,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Jt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),f.pathname!==Pi){s.add(c);return}i.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Jt(c,401,"invalid local proxy api key");return}let b;try{b=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Jt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(m=!0,n.handleUpgrade(d,c,p,k=>{i.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new bn(k,b,r,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Jt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Sn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let p=setTimeout(()=>{for(let f of o)f.readyState!==Oe.WebSocket.CLOSED&&f.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Mn=require("@urun-sh/core");var Mr=require("@urun-sh/core"),Di={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},Fi={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 yt(t,e){let n=Fi[t.code];return e?`${n} (${e})`:n}function Gt(t){if(t==null)return null;let e=Di[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 Vt(t){if(t.kind==="create-failed")return Gt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Mr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Gt(e?"cold_start_exceeded":"queue_timeout")}var Bi=Qn(require("os"),1),qi=Qn(require("path"),1),ji=require("url"),Hi=require("util");var Ji=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Gi(t){let e=t?.code;return typeof e=="string"&&Ji.has(e)}function Fe(t,e){try{return t.write(e),!0}catch(n){if(Gi(n))return!1;throw n}}var wt=require("ws");var Ur=require("@urun-sh/core");var Lr=require("crypto");function x(t){return`${t}_${(0,Lr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Wt=4*1024*1024,kn=8*1024*1024,xn=512,nt=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function xe(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:x("event"),error:t}}function Rn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Vi={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},Wi={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ki={format:!0,voice:!0,speed:!0};function zi(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function tt(t,e){if(!Array.isArray(t)||t.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function $r(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Yi=10;function En(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:Yi})}function _t(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new T("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in Vi));if(i.length>0)throw new T(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=tt(o.modalities,"modalities"),u=tt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new T('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new T(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=tt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new T('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!zi(u))throw new T(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new T("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");s.instructions=En(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!n.voice)throw new T("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new T(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new T("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new T(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new T("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new T("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new T("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,f]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new T(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(f!=null&&f!==c[p])throw new T(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new T("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new T("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new T(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new T(`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")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new T("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Wi))throw new T(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&$r(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=_t({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=_t({turn_detection:d.turn_detection},s,n,r);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ki))throw new T(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&$r(d.format,"audio.output.format"),d.speed!==void 0)throw new T("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new T("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new T("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Kt(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 An(t,e){let n=t;if(!n||typeof n!="object")throw new T("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 T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:x("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 T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new T("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new T("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new T(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new T("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new T("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new T("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new T("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new T("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new T(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:x("item"),type:"message",role:r,content:o}}throw new T(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function zt(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 i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Xi=1001,Qi=1011,Zi=6e4,es=3e5,In=3;var Yt=class extends Error{},Xt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Be=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Tn=t=>t.slice(0,120),ts=/^[A-Za-z0-9+/=]*$/,ns=600;function On(t){return Lt(Buffer.from(t,"base64"))}var qe=class{id=x("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Rn();sessionId=x("sess");conversationId=x("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Zi,this.responseDeadlineMs=e.responseDeadlineMs??es,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.binding.onSessionEnd?.(n=>{n.reason===mn&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:x("event"),session:Kt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:x("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(V(xe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("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:x("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(i=>i.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:x("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:x("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:x("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:x("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:x("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:x("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 s=x("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:x("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Wt){this.fail(Q("frame_too_large",`frame exceeds the ${Wt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(V({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(o instanceof Yt){this.fail(xe(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
14
|
+
${o?.stack??me(o)}`),this.send(V(xe(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=_t(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(V(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:x("event"),session:Kt(this.config,this.sessionId)});return}case"conversation.item.create":{let n=An(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(i=>i.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:x("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(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:x("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(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:x("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(V(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:x("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(V(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ts.test(e.audio)){this.send(V(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>nt&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${nt}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${nt} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>nt&&this.pendingAudioBytes.length>0;){let i=this.pendingAudioBytes.shift();o-=Buffer.byteLength(i.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:x("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(V(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=x("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:x("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:x("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:x("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(V(Q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(Q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(V(Q("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,Tn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Yt("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(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let i;if(o||this.turnStallMs<=0){o=!1;let s=n.next();s.catch(()=>{}),i=r?await Promise.race([s,r]):await s}else{let s,a=new Promise((d,c)=>{s=setTimeout(()=>c(new Xt),this.turnStallMs)}),u=n.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(s))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return this.config.model&&i.model===void 0&&(i.model=this.config.model),r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(V(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?tt(r.modalities,"response.modalities"):void 0,i=r.output_modalities!==void 0?tt(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&i!==void 0&&o.slice().sort().join(",")!==i.slice().sort().join(","))throw new T("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((i??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(V(Q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},u=new Promise((R,A)=>{a=()=>A(new Be)});this.turnCancelled=u,this.wakeTurnCancelled=()=>a(),u.catch(()=>{});let l=()=>{},d=new Promise((R,A)=>{l=()=>A(new Be)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=x("req"),f=`resp_${p}`;this.activeResponseId=f,this.activeRequestId=p;let m=this.binding.composite===!0,b=m?0:this.items.length,k=m?null:zt(this.items),_=En(typeof r.instructions=="string"?r.instructions:this.config.instructions),y=typeof r.temperature=="number"?r.temperature:this.config.temperature,h=r.max_output_tokens??this.config.maxOutputTokens,v=h==="inf"||h===void 0?void 0:h,$=r.tools!==void 0?r.tools:this.config.tools,P=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,I={stream:!0,...this.config.model?{model:this.config.model}:{},..._!==void 0?{instructions:_}:{},...y!==void 0?{temperature:y}:{},...v!==void 0?{max_output_tokens:v}:{},...$!==void 0?{tools:$}:{},...P!==void 0?{tool_choice:P}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:R,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R,A);this.inFlight=(async()=>{let R=[],A=F=>{this.responseFlushed?this.send(F):R.push(F)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:x("event"),response:this.responseObject(f,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(f,"in_progress")});for(let F of R)this.send(F);R.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},E=null,M=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(f,w,b),g(),this.send({type:"response.done",event_id:x("event"),response:this.responseObject(f,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(G=>{this.pendingTranscriptSettled=G}),this.cancelled||this.closed))throw new Be;b=this.items.length,k=zt(this.items)}let{input:F,sawAudioOnlyItem:j}=k??{input:[],sawAudioOnlyItem:!1},L={...I,input:F,...m?this.compositeTurnAsk(r):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let D;try{let G=this.upstreamStream(L,p);Promise.resolve(G).catch(O=>{O instanceof X&&this.failSessionGone(O)}),D=await Promise.race([G,d])}catch(G){if(G instanceof Be){this.deadlineFired&&!this.closed&&M();return}this.upstreamTurnFault(G,f);return}g();try{for await(let G of this.stallBoundedTurn(D)){if(this.cancelled)break;let O=G;if(O.type==="error"){let z=this.upstreamErrorBody(O);w.contentFlowed?this.send(V(z)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(f,z)});return}if(O.type==="response.output_text.delta"&&typeof O.delta=="string"){g(),w.contentFlowed=!0,w.messageOpen||(this.beginMessageItem(f,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:x("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:O.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:x("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:O.delta})),w.messageText+=O.delta;continue}if(O.type==="response.function_call_arguments.delta"){g(),w.contentFlowed=!0;let z=typeof O.delta=="string"?O.delta:"",C=typeof O.call_id=="string"&&O.call_id.length>0?O.call_id:`${f}_fc_${w.nextOutputIndex}`,N=w.tools.get(C);if(!N){let W=typeof O.name=="string"&&O.name.length>0?O.name:void 0;N={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(C,N);let ve={id:C,object:"realtime.item",type:"function_call",call_id:C,name:W??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:x("event"),response_id:f,output_index:N.outputIndex,item:ve}),this.emitAssistantItemAdded(ve)}typeof O.name=="string"&&O.name.length>0&&(N.name=O.name),N.args+=z,A({type:"response.function_call_arguments.delta",event_id:x("event"),item_id:C,response_id:f,output_index:N.outputIndex,call_id:C,name:N.name??"",delta:z});continue}if(O.type==="response.completed"){E=O.response??null;continue}}}catch(G){if(this.closed)return;if(G instanceof Be){this.deadlineFired&&M();return}if(this.cancelled)return;if(G instanceof Xt)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${f} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(G,f);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&M();return}this.closeOpenItems(f,w,b),g(),this.send({type:"response.done",event_id:x("event"),response:this.doneResponse(f,b,E)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(w.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=In){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${In} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(V(xe("member_unresponsive",`the member served no content for ${In} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(On(n)||this.userTurnOpen)return;this.openDuplexResponse()}else if(On(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=ns){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(On(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({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:x("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${x("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:x("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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:x("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:x("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:x("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:x("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:x("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`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:x("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:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:x("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:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:x("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.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,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,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=ke(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??_e(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(xe(hn,"the organization is out of credits \u2014 top up to continue"),hn))}failSessionGone(e){if(e instanceof X&&e.reason===mn){this.failInsufficientCredits();return}let n=e instanceof Error&&ye(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: ${me(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(xe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ur.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=xe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:x("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>xn&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(V(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>gn){this.send(V(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${gn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(V(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(V(xe(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>kn){this.ws.close(Xi,Tn("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: ${me(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Qi,Tn(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.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Nr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Nr(this.id,e)}},Pn=[];function Nr(t,e){Pn.push({id:t,reason:e}),Pn.length>256&&Pn.shift()}var vt="/v1/realtime",Dr="urun.admission",Fr=t=>t.slice(0,120);function rs(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
|
|
15
15
|
Connection: close\r
|
|
16
16
|
Content-Type: text/plain\r
|
|
17
17
|
\r
|
|
18
18
|
${Fr(n)}\r
|
|
19
19
|
`),t.destroy()}function os(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
20
|
-
`}function is(t){Fe(process.stdout,t)}function ss(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Cn(t){return t.audioSession?.audio.sessionId??void 0}function bt(t,e){let n=new wt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==vt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=
|
|
21
|
-
`)}}}),d({stage:"admit",conn:u,model:l,...Cn(g)===void 0?{}:{session:Cn(g)}}),F()}catch(O){j(O)}};if(h!==null){let D=$??[];$=null,L(h,D);return}n.handleUpgrade(o,i,s,D=>L(D,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,I).then(async g=>{if(c.signal.aborted){_();let w=Cn(g);try{await g.release?.()}catch(E){y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",release_failed:E instanceof Error?E.message:String(E)});return}y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",released:!0}),i.destroy();return}_(),await x(g)}).catch(g=>{let w=g instanceof Mn.SessionFailedError?Vt(g):null,E=null;if(g!==null&&typeof g=="object"&&"status"in g){let L=g.status;typeof L=="number"&&(E=L)}let M=E??w?.status??502,F=g instanceof Error?g.message:String(g),j=E!==null?F:w!==null?yt(w,g instanceof Mn.SessionFailedError&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):de(g).message;if(y({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:F,status:M}}),h!==null&&!c.signal.aborted){let L=JSON.stringify({type:Dr,event_id:R("event"),status:M<500?"rejected":"failed",reason:j});h.readyState===wt.WebSocket.OPEN&&h.send(L),h.close(1011,Fr(j));return}i.destroyed||rs(i,M,j)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var Jr=require("crypto");var Ln="x-urun-profile",St="voice";var ue=class extends Error{status=400},as=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,us=/\s/;function ls(t){return as.test(t)}function $n(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ue(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Br(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ue(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ue(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ue(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function qr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ue(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new ue(`the ${Ln} header is empty \u2014 the only profile this lane accepts is "${St}" (omit the header for the ordinary lane)`);if(l!==St)throw new ue(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${St}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==St)throw new ue(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${St}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ue("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ue("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Br(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Br(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:$n(u,"sentence_flush",!0),includeReasoning:$n(u,"include_reasoning",!1),metadata:$n(u,"metadata",!1)}}var rt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&ls(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(us.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ie=(t,e)=>Object.assign(new Error(e),{status:t}),ps='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Un=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Nn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?Ie(404,n.message):n}};async function jr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ie(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${ps}`);if(o==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(f){throw f instanceof J?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(f){throw f instanceof J?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Nn(t,n.stt),s=await Nn(t,e),a=await Nn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,fs({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(i,p)}catch(f){throw f instanceof X?Un("stt",n.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Hr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var kt=class extends Error{};async function*fs(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,b=null,k=[],_=null,y=new Promise((w,E)=>{n&&n.addEventListener("abort",()=>E(new kt),{once:!0})}),h=()=>f||n?.aborted===!0,v=async w=>{if(h())return;let E;try{E=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:w}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(F){throw F instanceof X?Un("tts",u.tts,F):F}let M=E[Symbol.asyncIterator]();b=M;try{for(;;){let F=M.next(),j;try{j=await Promise.race([F,y])}catch(D){if(F.catch(()=>{}),D instanceof kt)return;throw D}if(j.done)return;let L=j.value;if(L.type==="error"){let D=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${D}`)}if(L.type==="response.completed")return}}finally{b===M&&(b=null)}},$=async()=>{for(;k.length>0&&!h();){let w=k.shift();await v(w)}},P=w=>{if(w===""||h()||(k.push(w),_!==null))return;let E=$();_=E,E.then(()=>{_===E&&(_=null)},M=>{_===E&&(_=null),m??=M})},I=()=>{f=!0,k.length=0;let w=b;if(b=null,w){let E=w.return?.();E&&E.catch(()=>{})}},x=async()=>{for(;k.length>0||_!==null;){let w=_;if(w===null){await v(k.shift());continue}await w}},A=p?new rt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},w=>P(w)):null,g=null;try{let w;try{w=await o.createResponseOn(i,d)}catch(M){throw M instanceof X?Un("chat",a,M):M}let E=w[Symbol.asyncIterator]();try{for(;;){let M=E.next(),F;try{F=await Promise.race([M,y])}catch(D){if(M.catch(()=>{}),D instanceof kt)break;throw D}if(F.done)break;let j=F.value;if(h())return;let L=j;if(L.type==="error"){yield j;return}if(L.type==="response.output_text.delta"&&typeof L.delta=="string"){yield j,A?.push(L.delta);continue}if(L.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if(L.type==="response.completed"){g=j.response;continue}}}finally{Promise.resolve(E.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await x(),g!==null&&(yield{type:"response.completed",response:g})}finally{A?.dispose(),I();try{if(m instanceof X)throw m}finally{r?.()}}}var ce=(t,e)=>Object.assign(new Error(e),{status:t});function Dn(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ms(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var hs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Fn(t,e,n,r,o){if(!t.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await t.supportsAudio(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(!i){let f=null;if(t.realtimeCompanionsFor)try{f=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(f!==null)return await jr(t,e,f,n,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(s&&!t.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(f!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${hs}`);if(r==="transcription"&&!s)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(f){throw f instanceof le?ce(503,f.message):f}let u=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Jr.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,l,o).catch(f=>{throw t.releaseSessionHandle?.(a),f})},p={clients:{createResponse:async f=>await t.createResponseOn(a,f,l)},voice:i,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(a,n)),s&&(p.turns=f=>t.openTurnsOn(a,f)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(p.presence={touch:f=>t.touchSessionPresence?.(a,f),detach:f=>t.detachSessionPresence?.(a,f)}),t.endDedicatedSession&&(p.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(p.onSessionEnd=f=>t.onSessionEnd(a,f)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Qt(t,e,n){let r=Hr(t,n);return{resolve:async(o,i,s)=>{if(e!==void 0){let a=o.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw ce(401,"invalid local proxy api key")}return Fn(r,Dn(o),i,ms(o),s)}}}var U=class extends Error{},ie=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function it(t,e){if(t!=null)throw new U(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Bn(t){let e=xt(t);return e!==null&&e<=1?e:null}function Gr(t,e){if(!ne(t))throw new U("decisions requires a JSON object body");it(t.prompt_cache_key,"prompt_cache_key"),it(t.prompt_cache_options,"prompt_cache_options"),it(t.safety_identifier,"safety_identifier");let n=[],r=gs(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new U("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=vs(o[l],l,o.length,n);if(a.has(c.key))throw new U(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),i[c.key]=d,s.push(c)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function gs(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new U("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)_s(o,r,e);return ys(r)}function ys(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
20
|
+
`}function is(t){Fe(process.stdout,t)}function ss(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Cn(t){return t.audioSession?.audio.sessionId??void 0}function bt(t,e){let n=new wt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==vt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=x("rtup"),l=ss(o),d=g=>{(e.log??is)(os(g))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,f=g=>{p??=g,c.abort(new Error(p))},m=()=>f("client socket closed"),b=()=>f("client socket closed (half-close)"),k=g=>f(`client socket error: ${g.message}`);i.once("close",m),i.once("end",b),i.once("error",k);let _=()=>{i.removeListener("close",m),i.removeListener("end",b),i.removeListener("error",k)},y=g=>{d({stage:"close",conn:u,model:l,...g})},h=null,v=!1,$=null,P=g=>JSON.stringify({type:Dr,event_id:x("event"),...g}),I=g=>{if(h!==null){h.readyState===wt.WebSocket.OPEN&&h.send(P(g));return}v||(v=!0,n.handleUpgrade(o,i,s,w=>{h=w,$=[],w.on("message",E=>{$?.push(String(E))}),d({stage:"waiting",conn:u,model:l,status:g.status}),w.send(P(g))}))},R=g=>{let w=g,E=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!E&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((F,j)=>{let L=(D,G)=>{try{let O=Date.now();new qe({ws:D,binding:g,operatorLog:e.operatorLog,...G.length>0?{replayFrames:G}:{},onClosed:(z,C)=>{y({while:"live",reason:C.reason});try{e.onSessionEnded?.({req:o,binding:g,connected_ms:Math.max(0,Date.now()-O),reason:C.reason})}catch(N){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${N instanceof Error?N.message:String(N)}
|
|
21
|
+
`)}}}),d({stage:"admit",conn:u,model:l,...Cn(g)===void 0?{}:{session:Cn(g)}}),F()}catch(O){j(O)}};if(h!==null){let D=$??[];$=null,L(h,D);return}n.handleUpgrade(o,i,s,D=>L(D,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,I).then(async g=>{if(c.signal.aborted){_();let w=Cn(g);try{await g.release?.()}catch(E){y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",release_failed:E instanceof Error?E.message:String(E)});return}y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",released:!0}),i.destroy();return}_(),await R(g)}).catch(g=>{let w=g instanceof Mn.SessionFailedError?Vt(g):null,E=null;if(g!==null&&typeof g=="object"&&"status"in g){let L=g.status;typeof L=="number"&&(E=L)}let M=E??w?.status??502,F=g instanceof Error?g.message:String(g),j=E!==null?F:w!==null?yt(w,g instanceof Mn.SessionFailedError&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):de(g).message;if(y({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:F,status:M}}),h!==null&&!c.signal.aborted){let L=JSON.stringify({type:Dr,event_id:x("event"),status:M<500?"rejected":"failed",reason:j});h.readyState===wt.WebSocket.OPEN&&h.send(L),h.close(1011,Fr(j));return}i.destroyed||rs(i,M,j)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var Jr=require("crypto");var Ln="x-urun-profile",St="voice";var ue=class extends Error{status=400},as=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,us=/\s/;function ls(t){return as.test(t)}function $n(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ue(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Br(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ue(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ue(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ue(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function qr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ue(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new ue(`the ${Ln} header is empty \u2014 the only profile this lane accepts is "${St}" (omit the header for the ordinary lane)`);if(l!==St)throw new ue(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${St}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==St)throw new ue(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${St}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ue("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ue("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Br(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Br(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:$n(u,"sentence_flush",!0),includeReasoning:$n(u,"include_reasoning",!1),metadata:$n(u,"metadata",!1)}}var rt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&ls(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(us.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ie=(t,e)=>Object.assign(new Error(e),{status:t}),ps='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Un=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Nn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?Ie(404,n.message):n}};async function jr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ie(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${ps}`);if(o==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(f){throw f instanceof J?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(f){throw f instanceof J?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Nn(t,n.stt),s=await Nn(t,e),a=await Nn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,fs({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(i,p)}catch(f){throw f instanceof X?Un("stt",n.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Hr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var kt=class extends Error{};async function*fs(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,b=null,k=[],_=null,y=new Promise((w,E)=>{n&&n.addEventListener("abort",()=>E(new kt),{once:!0})}),h=()=>f||n?.aborted===!0,v=async w=>{if(h())return;let E;try{E=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:w}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(F){throw F instanceof X?Un("tts",u.tts,F):F}let M=E[Symbol.asyncIterator]();b=M;try{for(;;){let F=M.next(),j;try{j=await Promise.race([F,y])}catch(D){if(F.catch(()=>{}),D instanceof kt)return;throw D}if(j.done)return;let L=j.value;if(L.type==="error"){let D=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${D}`)}if(L.type==="response.completed")return}}finally{b===M&&(b=null)}},$=async()=>{for(;k.length>0&&!h();){let w=k.shift();await v(w)}},P=w=>{if(w===""||h()||(k.push(w),_!==null))return;let E=$();_=E,E.then(()=>{_===E&&(_=null)},M=>{_===E&&(_=null),m??=M})},I=()=>{f=!0,k.length=0;let w=b;if(b=null,w){let E=w.return?.();E&&E.catch(()=>{})}},R=async()=>{for(;k.length>0||_!==null;){let w=_;if(w===null){await v(k.shift());continue}await w}},A=p?new rt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},w=>P(w)):null,g=null;try{let w;try{w=await o.createResponseOn(i,d)}catch(M){throw M instanceof X?Un("chat",a,M):M}let E=w[Symbol.asyncIterator]();try{for(;;){let M=E.next(),F;try{F=await Promise.race([M,y])}catch(D){if(M.catch(()=>{}),D instanceof kt)break;throw D}if(F.done)break;let j=F.value;if(h())return;let L=j;if(L.type==="error"){yield j;return}if(L.type==="response.output_text.delta"&&typeof L.delta=="string"){yield j,A?.push(L.delta);continue}if(L.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if(L.type==="response.completed"){g=j.response;continue}}}finally{Promise.resolve(E.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await R(),g!==null&&(yield{type:"response.completed",response:g})}finally{A?.dispose(),I();try{if(m instanceof X)throw m}finally{r?.()}}}var ce=(t,e)=>Object.assign(new Error(e),{status:t});function Dn(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ms(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var hs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Fn(t,e,n,r,o){if(!t.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await t.supportsAudio(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(!i){let f=null;if(t.realtimeCompanionsFor)try{f=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(f!==null)return await jr(t,e,f,n,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(s&&!t.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(f!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${hs}`);if(r==="transcription"&&!s)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(f){throw f instanceof le?ce(503,f.message):f}let u=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Jr.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,l,o).catch(f=>{throw t.releaseSessionHandle?.(a),f})},p={clients:{createResponse:async f=>await t.createResponseOn(a,f,l)},voice:i,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(a,n)),s&&(p.turns=f=>t.openTurnsOn(a,f)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(p.presence={touch:f=>t.touchSessionPresence?.(a,f),detach:f=>t.detachSessionPresence?.(a,f)}),t.endDedicatedSession&&(p.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(p.onSessionEnd=f=>t.onSessionEnd(a,f)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Qt(t,e,n){let r=Hr(t,n);return{resolve:async(o,i,s)=>{if(e!==void 0){let a=o.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw ce(401,"invalid local proxy api key")}return Fn(r,Dn(o),i,ms(o),s)}}}var U=class extends Error{},ie=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function it(t,e){if(t!=null)throw new U(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Bn(t){let e=xt(t);return e!==null&&e<=1?e:null}function Gr(t,e){if(!ne(t))throw new U("decisions requires a JSON object body");it(t.prompt_cache_key,"prompt_cache_key"),it(t.prompt_cache_options,"prompt_cache_options"),it(t.safety_identifier,"safety_identifier");let n=[],r=gs(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new U("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=vs(o[l],l,o.length,n);if(a.has(c.key))throw new U(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),i[c.key]=d,s.push(c)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function gs(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new U("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)_s(o,r,e);return ys(r)}function ys(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
22
22
|
|
|
23
23
|
`)}function _s(t,e,n){if(!ne(t))throw new U("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){ws(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=t.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Vr(i,e,n,void 0,!1);return}throw new U(`${o} output must be a string or an array of parts`)}default:throw new U(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function ws(t,e,n,r){e==="assistant"&&it(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new U(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of o){if(!ne(i))throw new U("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")n.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")n.push({role:e,text:`[refusal] ${i.refusal}`});else throw new U(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Vr(o,n,r,e)}function Vr(t,e,n,r,o=!0){for(let i of t){if(!ne(i))throw new U("decisions content parts must be JSON objects");switch(it(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new U("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!o)throw new U("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new U("input_json data must be an object or an array of objects");e.push({role:r,json:s});break}case"input_image":{n.push(Wr(i));break}default:throw new U(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Wr(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new U("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new U("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new U("input_image data URL carries no image data");let i=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(i?o.length%4!==0:o.length%4===1))throw new U("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let s=t.detail;if(s!=null&&s!=="low"&&s!=="high"&&s!=="auto"&&s!=="original")throw new U("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(s==="low"||s==="high")&&(a.detail=s),a}function vs(t,e,n,r){if(!ne(t))throw new U(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new U(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let i=t.name;if(i!==void 0&&typeof i!="string")throw new U(`questions[${e}] name must be a string`);let s=i??null,a=s??`q${e}`,u=bs(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:s}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new U(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let b of l){if(!ne(b))throw new U(`questions[${e}] choices must be JSON objects`);let k=b.value;if(typeof k!="string"&&typeof k!="boolean")throw new U(`questions[${e}] choice value must be a string or boolean`);let _=String(k);if(c.has(_))throw new U(`questions[${e}] has duplicate choice value ${JSON.stringify(_)} (choices must be unique)`);c.add(_);let y=b.description;if(y!==void 0&&typeof y!="string")throw new U(`questions[${e}] choice description must be a string`);d.push(k),p.push(y)}let f=l.map((b,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:u,options:f},spec:{type:o,key:a,name:s,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new U(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let f of l){if(!ne(f)||typeof f.label!="string")throw new U(`questions[${e}] score levels must carry a string label`);if(d.includes(f.label))throw new U(`questions[${e}] has duplicate level label ${JSON.stringify(f.label)}`);d.push(f.label);let m=f.description;if(m!==void 0&&typeof m!="string")throw new U(`questions[${e}] score level description must be a string`);let b=m!==void 0?`${f.label}: ${m}`:f.label;if(c.includes(b))throw new U(`questions[${e}] has duplicate score criterion ${JSON.stringify(b)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(b)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:s,levelLabels:d}}}}}function bs(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new U(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let i of t){if(!ne(i))throw new U(`questions[${e}] instruction parts must be JSON objects`);switch(it(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new U(`questions[${e}] input_text requires a string text`);o.push(i.text);break}case"input_image":{if(n>1)throw new U(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Wr(i));break}case"input_json":{let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new U(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(s));break}default:throw new U(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return o.join(`
|
|
24
24
|
|
|
25
|
-
`)}function Kr(t,e){if(!ne(e))throw new ie("decision answer was not a JSON object");let n=e.answers;if(!ne(n))throw new ie("decision answer carried no answers object");let r=[];for(let o of t){let i=n[o.key];if(!ne(i)||i.skipped===!0){r.push({type:"refusal",name:o.name});continue}let s=ne(i.probabilities)?i.probabilities:{};switch(o.type){case"predicate":{let a=Bn(i.noul);if(a===null)throw new ie(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],u=i.choice;if(typeof u!="string")throw new ie(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new ie(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=xt(i.confidence);if(d===null)throw new ie(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let f=Bn(s[String(p)]);f!==null&&c.push({value:p,probability:f})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=xt(i.score);if(u===null)throw new ie(`the score answer for "${o.key}" carries no numeric score to translate`);let l=xt(i.confidence);if(l===null)throw new ie(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=Bn(s[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}r.push({type:"score",name:o.name,score:u,confidence:l,probabilities:d});continue}}}return r}function ot(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Ss(t){let e=ne(t.input_tokens_details)?t.input_tokens_details.cached_tokens:void 0,n=e!==void 0?e:t.cached_tokens;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:0}function zr(t){if(t==null)return null;if(!ne(t))throw new ie("decision reply carried a usage receipt that is not a JSON object");let e=ot(t.prompt_tokens)??ot(t.input_tokens),n=ot(t.completion_tokens)??ot(t.output_tokens);if(e===null||n===null)throw new ie("decision reply carried a usage receipt with no usable token counts");let r=xt(t.ttft_ms),o=ot(t.total_tokens)??ot(e+n);if(o===null)throw new ie("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Ss(t)},output_tokens:n,output_tokens_details:{reasoning_tokens:0},total_tokens:o,...r!==null?{ttft_ms:r}:{}}}var re=class extends Error{};async function Zt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new re(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new re(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function en(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new re(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof re?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var Yr="/v1/images/generations",tn="/v1/images/edits";function Xr(t){return t===Yr||t===tn}var Qr="/v1/images/models";async function Zr(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ks=16*1024*1024,eo=64*1024*1024;function to(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Rt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function no(t,e,n,r,o,i){let s=i??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let m of a){if(m.type==="error"){let b=m.error??{},k=typeof b.message=="string"&&b.message.length>0&&ye(b.message)?b.message:null;throw k===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new q(502,"the image upstream failed while serving this request")):new q(502,`image upstream error: ${k}`)}if(m.type==="response.completed"){u=m.response??null;break}}if(u===null)throw new q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ae(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(to(p)===null)throw new q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function ro(t,e){if(t instanceof q)return t;if(t instanceof Se)throw t;return t instanceof J?new q(404,t.message):new q(502,et("image",t,e))}async function oo(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Rt(r,new q(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function io(t,e){t&&(t.outputUnits=e.images.length)}function so(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var xs={model:!0,prompt:!0,response_format:!0,n:!0};async function ao(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??eo;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Yr}`);let i;try{i=JSON.parse((await Zt(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof re?new q(413,p.message):new q(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new q(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!xs[p])throw new q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new q(400,"model must be a string","model");await Zr(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await oo(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await no(n.clients,u,c,n.turn?pe(n.turn):void 0,n.turn,r);io(n.turn,p),so(e,p)}catch(p){throw ro(p,r)}}catch(i){if(i instanceof re){Rt(e,new q(413,i.message));return}if(i instanceof q){Rt(e,i);return}throw i}}var Rs={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function uo(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??eo,i=n.maxImagePartBytes??ks;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await en(t,o)}catch(m){throw m instanceof re?new q(413,m.message):new q(400,String(m instanceof Error?m.message:m))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new q(400,"model must be a string field","model");let d=l===null?void 0:l;await Zr(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of a.keys())if(!Rs[m])throw new q(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let p=[];for(let m of["image","image[]"])for(let b of a.getAll(m)){if(!(b instanceof File))throw new q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(b.size>i)throw new q(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let k=new Uint8Array(await b.arrayBuffer()),_=to(k);if(_===null)throw new q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:k,mime:_})}if(p.length===0)throw new q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await oo(n.imageModels,d,"edit",e))return;let f=[{type:"input_text",text:u}];for(let{bytes:m,mime:b}of p)f.push({type:"input_image",image_url:`data:${b};base64,${Buffer.from(m).toString("base64")}`});try{let m=await no(n.clients,d,f,n.turn?pe(n.turn):void 0,n.turn,r);io(n.turn,m),so(e,m)}catch(m){throw ro(m,r)}}catch(s){if(s instanceof re){Rt(e,new q(413,s.message));return}if(s instanceof q){Rt(e,s);return}throw s}}var Et="/v1/audio/speech";function _o(t){return t===Et}var lo=4096,co=18e4,po=5e3,Es=64*1024*1024,fo=8,mo=5,ho=1024*1024,st="voice_applied",rn="X-Urun-Voice-Applied",B=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function qn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var on=class extends B{constructor(e){super(502,e)}};function wo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function vo(t){return new B(502,`the runtime's ${st} receipt ${JSON.stringify(t)} cannot be relayed as the ${rn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function As(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function bo(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}function Is(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var go=new WeakMap,nn=new WeakMap;function Ts(t,e){let n=nn.get(t)??0;if(n>=fo)throw new B(503,`this model's speech queue is full \u2014 ${fo} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${mo}s`,void 0,mo);nn.set(t,n+1);let r=go.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return go.set(t,i),(async()=>{await r;try{return await e()}finally{nn.set(t,(nn.get(t)??1)-1),o()}})()}async function Os(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof X))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{clearTimeout(i)})}function je(t,e){if(t instanceof B)return t;if(t instanceof Se)throw t;return t instanceof J?new B(404,t.message):new B(502,et("speech",t,e))}async function yo(t,e,n,r,o,i,s,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Ts(e,async()=>{if(s?.()===!0)return null;let p=!1,f=!1,m=!1,b,k=new Promise(w=>{b=w}),_=[],y,h=!1,v=null,$=()=>{v!==null&&(clearTimeout(y),y=setTimeout(()=>{h=!0,v?.()},o.capMs))},P=()=>{f&&!m&&_.length>=o.quietRunFrames&&(m=!0,b())},I=e.onOutputAudio(w=>{let E=Buffer.from(w,"base64");if(E.byteLength===0)return;$();let M=Lt(E);if(!p){if(M)return;p=!0}if(M){_.push(E),P();return}for(let F of _)c(F);_.length=0,c(E),P()}),x=null,A,g;try{g=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let E=()=>(clearTimeout(A),new Promise(L=>{A=setTimeout(L,i.capMs)})),M=E(),F=!1;for(;;){let L=g.next(),D=await Promise.race([L,M]);if(D===void 0){F=!0,L.catch(()=>{});break}if(D.done)break;let G=D.value;if(M=E(),G.type==="error"){let O=G.error??{};await g.return?.();let z=typeof O.message=="string"&&O.message.length>0&&ye(O.message)?O.message:null;throw z===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(G)}`),new B(502,"the speech upstream failed while serving this request")):new B(502,`speech upstream error: ${z}`)}if(G.type==="response.completed"){x=G.response??null,f=!0,u?.(x),P(),await g.return?.();break}}if(clearTimeout(A),F)throw new B(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(x===null)throw new B(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise(L=>{v=L});if($(),await Promise.race([k,j]),clearTimeout(y),y=void 0,v=null,r.voice!==void 0){let L=x[st];if(typeof L!="string"||L!==r.voice){let D=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof L=="string"?`${st} ${JSON.stringify(L)}`:`no ${st} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new on(D):new B(502,D)}}if(!p)throw new B(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(h&&!m&&_.length<1)throw new B(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return x}catch(w){throw w instanceof on||await Os(t,n,g,i.returnBoundMs),w}finally{clearTimeout(y),clearTimeout(A),I()}})}function Ps(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",rn)),t.write(a,u=>{u||(i+=a.byteLength,bo(e,i))}),t.writableLength>ho&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${ho} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[st];if(typeof u=="string"){if(!wo(u))throw vo(u);t.addTrailers({[rn]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function Cs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw je(i,r)}return o?!0:(qn(n,new B(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ms={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},$s="wav, pcm";async function So(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Es,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Et}`);let a;try{a=JSON.parse((await Zt(t,o)).toString("utf8")||"{}")}catch(v){throw v instanceof re?new B(413,v.message):new B(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new B(400,"request body must be a JSON object");let u=a;for(let v of Object.keys(u))if(!Ms[v])throw new B(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new B(400,"input is required and must be a non-empty string","input");if(l.length>lo)throw new B(400,`input is ${l.length} chars \u2014 over the ${lo}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new B(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new B(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new B(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Et} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(v){throw je(v,r)}if(p.defect!==null)throw new B(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let f=typeof c=="string"?c:void 0;if(f!==void 0&&p.published.length>0&&!p.published.includes(f))throw new B(400,`voice ${JSON.stringify(f)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=u.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new B(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${$s} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new B(400,"stream_format, when present, must be a string","stream_format");let b=u.speed;if(b!==void 0){if(typeof b!="number"||!Number.isFinite(b))throw new B(400,"speed, when present, must be a number","speed");if(b!==1)throw new B(400,`speed=${JSON.stringify(b)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=u.instructions;if(k!==void 0){if(typeof k!="string")throw new B(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new B(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await As(n.turn,n.clients,d);let _=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",_,_),!await Cs(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new B(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new B(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw je(v,r)}let h;try{h=await n.clients.openAudioOn(y)}catch(v){throw je(v,r)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(m==="wav"){let v=[],$=await yo(n.clients,h,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??co,returnBoundMs:n.turnReturnBoundMs??po},s,I=>v.push(I),I=>{n.turn&&(n.turn.outputSeconds=Ae(I))},r);if($===null||s())return;let P=Buffer.concat(v);if(f===void 0){let I=$[st];if(typeof I=="string"){if(!wo(I))throw vo(I);e.setHeader(rn,I)}}bo(n.turn,P.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Is(P.byteLength),P]))}else{let v=Ps(e,n.turn,s,f===void 0),$;try{$=await yo(n.clients,h,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??co,returnBoundMs:n.turnReturnBoundMs??po},s,v.sink,P=>{n.turn&&(n.turn.outputSeconds=Ae(P))},r)}catch(P){let I=je(P,r);if(!v.started())throw I;n.turn&&(n.turn.streamError=!0),v.fail(I);return}if($===null)return;try{await v.finish($)}catch(P){let I=je(P,r);n.turn&&(n.turn.streamError=!0),v.fail(I);return}}}catch(v){throw je(v,r)}}catch(a){if(a instanceof re){qn(e,new B(413,a.message));return}if(a instanceof B){qn(e,a);return}throw a}}var sn="/v1/audio/transcriptions";function ko(t){return t===sn}var xo="/v1/audio/models",Ls=16*1024*1024,Ns=64*1024*1024,Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function jn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Ro(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Us(t){if(!Ro(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ds(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Fs(t,e){t&&(t.outputUnits=e.seconds)}async function Bs(t,e,n,r,o,i,s){let a=s??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},f=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&ye(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Z(f==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Z(f==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Z(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ae(d)),Xe(l,d)}function Eo(t,e){if(t instanceof Z)return t;if(t instanceof Se)throw t;return t instanceof J?new Z(404,t.message):new Z(502,et("transcription",t,e))}async function qs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw Eo(i,r)}return o?!0:(jn(n,new Z(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var js=new Set(["file","model","language","response_format"]);async function Ao(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ns,i=n.maxAudioPartBytes??Ls;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${sn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await en(t,o)}catch(y){throw y instanceof re?new Z(413,y.message):new Z(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of a.keys()){if(!js.has(y))throw new Z(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,h]of u)if(h>1)throw new Z(400,`form field "${y}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let l=a.get("model");if(l!==null&&typeof l!="string")throw new Z(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Z(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,f=a.get("response_format")??"json";if(f!=="json")throw new Z(400,`response_format ${JSON.stringify(f)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new Z(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>i)throw new Z(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let b=new Uint8Array(await m.arrayBuffer());if(!Ro(b))throw new Z(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let k=Us(b);if(k===null)throw new Z(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ds(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",b.length,b.length),!await qs(n.transcriptionModels,d,e,r))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(b).toString("base64"),format:"wav"}}];try{let y=await Bs(n.clients,d,_,p,n.turn?pe(n.turn):void 0,n.turn,r);Fs(n.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw Eo(y,r)}}catch(s){if(s instanceof re){jn(e,new Z(413,s.message));return}if(s instanceof Z){jn(e,s);return}throw s}}var To="/v1/usage/requests",Io=1e4,Hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},at=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Oo=1024*1024;function Hn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Pe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Pe(`"${e}" must be an array of uuid strings`);if(n.length>Io)throw new Pe(`"${e}" carries ${n.length} ids; at most ${Io} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Hs.test(i))throw new Pe(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Po(t){return Hn(t,"inference_ids")}function an(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new at(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new at(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var cn=require("@urun-sh/core");var Jn="/partners/huggingface/v1/billing/requests";function Js(t){return Hn(t,"requestIds")}function Gs(t){return t>=200&&t<=399}function Vs(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Gs(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Co(t,e){let n=Js(t),r=await e(n);return an(r,n),Vs(r)}var Ws={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Ks(t){return Ws[t]??null}var No=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function zs(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ys(t){return t==="surface"}function Xs(t){let e=t?.ledgerFailureReason;return No.includes(e)?e:"unknown"}var Qs=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Mo=["priced","unpriced"],Zs={written:Mo,already_written:Mo,skipped:Qs,failed:No},xd=Object.entries(Zs).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ea(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function ta(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var na=256,$o=4096,It=12e4,ra=250,oa=8e3,Tt=[],Lo=new Set,Ot=0,At=!1;var ia=new Set;function sa(){return Ot===0&&Tt.length===0}function aa(){if(sa()){At=!1;for(let t of[...ia])t()}}function Uo(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
25
|
+
`)}function Kr(t,e){if(!ne(e))throw new ie("decision answer was not a JSON object");let n=e.answers;if(!ne(n))throw new ie("decision answer carried no answers object");let r=[];for(let o of t){let i=n[o.key];if(!ne(i)||i.skipped===!0){r.push({type:"refusal",name:o.name});continue}let s=ne(i.probabilities)?i.probabilities:{};switch(o.type){case"predicate":{let a=Bn(i.noul);if(a===null)throw new ie(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],u=i.choice;if(typeof u!="string")throw new ie(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new ie(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=xt(i.confidence);if(d===null)throw new ie(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let f=Bn(s[String(p)]);f!==null&&c.push({value:p,probability:f})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=xt(i.score);if(u===null)throw new ie(`the score answer for "${o.key}" carries no numeric score to translate`);let l=xt(i.confidence);if(l===null)throw new ie(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=Bn(s[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}r.push({type:"score",name:o.name,score:u,confidence:l,probabilities:d});continue}}}return r}function ot(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Ss(t){let e=ne(t.input_tokens_details)?t.input_tokens_details.cached_tokens:void 0,n=e!==void 0?e:t.cached_tokens;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:0}function zr(t){if(t==null)return null;if(!ne(t))throw new ie("decision reply carried a usage receipt that is not a JSON object");let e=ot(t.prompt_tokens)??ot(t.input_tokens),n=ot(t.completion_tokens)??ot(t.output_tokens);if(e===null||n===null)throw new ie("decision reply carried a usage receipt with no usable token counts");let r=xt(t.ttft_ms),o=ot(t.total_tokens)??ot(e+n);if(o===null)throw new ie("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Ss(t)},output_tokens:n,output_tokens_details:{reasoning_tokens:0},total_tokens:o,...r!==null?{ttft_ms:r}:{}}}var re=class extends Error{};async function Zt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new re(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new re(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function en(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new re(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof re?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var Yr="/v1/images/generations",tn="/v1/images/edits";function Xr(t){return t===Yr||t===tn}var Qr="/v1/images/models";async function Zr(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ks=16*1024*1024,eo=64*1024*1024;function to(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Rt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function no(t,e,n,r,o,i){let s=i??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let m of a){if(m.type==="error"){let b=m.error??{},k=typeof b.message=="string"&&b.message.length>0&&ye(b.message)?b.message:null;throw k===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new q(502,"the image upstream failed while serving this request")):new q(502,`image upstream error: ${k}`)}if(m.type==="response.completed"){u=m.response??null;break}}if(u===null)throw new q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ae(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(to(p)===null)throw new q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function ro(t,e){if(t instanceof q)return t;if(t instanceof Se)throw t;return t instanceof J?new q(404,t.message):new q(502,et("image",t,e))}async function oo(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Rt(r,new q(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function io(t,e){t&&(t.outputUnits=e.images.length)}function so(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var xs={model:!0,prompt:!0,response_format:!0,n:!0};async function ao(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??eo;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Yr}`);let i;try{i=JSON.parse((await Zt(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof re?new q(413,p.message):new q(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new q(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!xs[p])throw new q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new q(400,"model must be a string","model");await Zr(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await oo(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await no(n.clients,u,c,n.turn?pe(n.turn):void 0,n.turn,r);io(n.turn,p),so(e,p)}catch(p){throw ro(p,r)}}catch(i){if(i instanceof re){Rt(e,new q(413,i.message));return}if(i instanceof q){Rt(e,i);return}throw i}}var Rs={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function uo(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??eo,i=n.maxImagePartBytes??ks;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await en(t,o)}catch(m){throw m instanceof re?new q(413,m.message):new q(400,String(m instanceof Error?m.message:m))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new q(400,"model must be a string field","model");let d=l===null?void 0:l;await Zr(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of a.keys())if(!Rs[m])throw new q(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let p=[];for(let m of["image","image[]"])for(let b of a.getAll(m)){if(!(b instanceof File))throw new q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(b.size>i)throw new q(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let k=new Uint8Array(await b.arrayBuffer()),_=to(k);if(_===null)throw new q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:k,mime:_})}if(p.length===0)throw new q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await oo(n.imageModels,d,"edit",e))return;let f=[{type:"input_text",text:u}];for(let{bytes:m,mime:b}of p)f.push({type:"input_image",image_url:`data:${b};base64,${Buffer.from(m).toString("base64")}`});try{let m=await no(n.clients,d,f,n.turn?pe(n.turn):void 0,n.turn,r);io(n.turn,m),so(e,m)}catch(m){throw ro(m,r)}}catch(s){if(s instanceof re){Rt(e,new q(413,s.message));return}if(s instanceof q){Rt(e,s);return}throw s}}var Et="/v1/audio/speech";function _o(t){return t===Et}var lo=4096,co=18e4,po=5e3,Es=64*1024*1024,fo=8,mo=5,ho=1024*1024,st="voice_applied",rn="X-Urun-Voice-Applied",B=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function qn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var on=class extends B{constructor(e){super(502,e)}};function wo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function vo(t){return new B(502,`the runtime's ${st} receipt ${JSON.stringify(t)} cannot be relayed as the ${rn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function As(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function bo(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}function Is(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var go=new WeakMap,nn=new WeakMap;function Ts(t,e){let n=nn.get(t)??0;if(n>=fo)throw new B(503,`this model's speech queue is full \u2014 ${fo} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${mo}s`,void 0,mo);nn.set(t,n+1);let r=go.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return go.set(t,i),(async()=>{await r;try{return await e()}finally{nn.set(t,(nn.get(t)??1)-1),o()}})()}async function Os(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof X))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{clearTimeout(i)})}function je(t,e){if(t instanceof B)return t;if(t instanceof Se)throw t;return t instanceof J?new B(404,t.message):new B(502,et("speech",t,e))}async function yo(t,e,n,r,o,i,s,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Ts(e,async()=>{if(s?.()===!0)return null;let p=!1,f=!1,m=!1,b,k=new Promise(w=>{b=w}),_=[],y,h=!1,v=null,$=()=>{v!==null&&(clearTimeout(y),y=setTimeout(()=>{h=!0,v?.()},o.capMs))},P=()=>{f&&!m&&_.length>=o.quietRunFrames&&(m=!0,b())},I=e.onOutputAudio(w=>{let E=Buffer.from(w,"base64");if(E.byteLength===0)return;$();let M=Lt(E);if(!p){if(M)return;p=!0}if(M){_.push(E),P();return}for(let F of _)c(F);_.length=0,c(E),P()}),R=null,A,g;try{g=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let E=()=>(clearTimeout(A),new Promise(L=>{A=setTimeout(L,i.capMs)})),M=E(),F=!1;for(;;){let L=g.next(),D=await Promise.race([L,M]);if(D===void 0){F=!0,L.catch(()=>{});break}if(D.done)break;let G=D.value;if(M=E(),G.type==="error"){let O=G.error??{};await g.return?.();let z=typeof O.message=="string"&&O.message.length>0&&ye(O.message)?O.message:null;throw z===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(G)}`),new B(502,"the speech upstream failed while serving this request")):new B(502,`speech upstream error: ${z}`)}if(G.type==="response.completed"){R=G.response??null,f=!0,u?.(R),P(),await g.return?.();break}}if(clearTimeout(A),F)throw new B(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(R===null)throw new B(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise(L=>{v=L});if($(),await Promise.race([k,j]),clearTimeout(y),y=void 0,v=null,r.voice!==void 0){let L=R[st];if(typeof L!="string"||L!==r.voice){let D=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof L=="string"?`${st} ${JSON.stringify(L)}`:`no ${st} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new on(D):new B(502,D)}}if(!p)throw new B(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(h&&!m&&_.length<1)throw new B(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return R}catch(w){throw w instanceof on||await Os(t,n,g,i.returnBoundMs),w}finally{clearTimeout(y),clearTimeout(A),I()}})}function Ps(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",rn)),t.write(a,u=>{u||(i+=a.byteLength,bo(e,i))}),t.writableLength>ho&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${ho} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[st];if(typeof u=="string"){if(!wo(u))throw vo(u);t.addTrailers({[rn]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function Cs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw je(i,r)}return o?!0:(qn(n,new B(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ms={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},$s="wav, pcm";async function So(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Es,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Et}`);let a;try{a=JSON.parse((await Zt(t,o)).toString("utf8")||"{}")}catch(v){throw v instanceof re?new B(413,v.message):new B(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new B(400,"request body must be a JSON object");let u=a;for(let v of Object.keys(u))if(!Ms[v])throw new B(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new B(400,"input is required and must be a non-empty string","input");if(l.length>lo)throw new B(400,`input is ${l.length} chars \u2014 over the ${lo}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new B(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new B(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new B(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Et} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(v){throw je(v,r)}if(p.defect!==null)throw new B(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let f=typeof c=="string"?c:void 0;if(f!==void 0&&p.published.length>0&&!p.published.includes(f))throw new B(400,`voice ${JSON.stringify(f)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=u.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new B(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${$s} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new B(400,"stream_format, when present, must be a string","stream_format");let b=u.speed;if(b!==void 0){if(typeof b!="number"||!Number.isFinite(b))throw new B(400,"speed, when present, must be a number","speed");if(b!==1)throw new B(400,`speed=${JSON.stringify(b)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=u.instructions;if(k!==void 0){if(typeof k!="string")throw new B(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new B(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await As(n.turn,n.clients,d);let _=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",_,_),!await Cs(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new B(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new B(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw je(v,r)}let h;try{h=await n.clients.openAudioOn(y)}catch(v){throw je(v,r)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(m==="wav"){let v=[],$=await yo(n.clients,h,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??co,returnBoundMs:n.turnReturnBoundMs??po},s,I=>v.push(I),I=>{n.turn&&(n.turn.outputSeconds=Ae(I))},r);if($===null||s())return;let P=Buffer.concat(v);if(f===void 0){let I=$[st];if(typeof I=="string"){if(!wo(I))throw vo(I);e.setHeader(rn,I)}}bo(n.turn,P.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Is(P.byteLength),P]))}else{let v=Ps(e,n.turn,s,f===void 0),$;try{$=await yo(n.clients,h,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??co,returnBoundMs:n.turnReturnBoundMs??po},s,v.sink,P=>{n.turn&&(n.turn.outputSeconds=Ae(P))},r)}catch(P){let I=je(P,r);if(!v.started())throw I;n.turn&&(n.turn.streamError=!0),v.fail(I);return}if($===null)return;try{await v.finish($)}catch(P){let I=je(P,r);n.turn&&(n.turn.streamError=!0),v.fail(I);return}}}catch(v){throw je(v,r)}}catch(a){if(a instanceof re){qn(e,new B(413,a.message));return}if(a instanceof B){qn(e,a);return}throw a}}var sn="/v1/audio/transcriptions";function ko(t){return t===sn}var xo="/v1/audio/models",Ls=16*1024*1024,Ns=64*1024*1024,Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function jn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Ro(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Us(t){if(!Ro(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ds(t,e,n){if(t){if(t.model=se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Fs(t,e){t&&(t.outputUnits=e.seconds)}async function Bs(t,e,n,r,o,i,s){let a=s??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},f=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&ye(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Z(f==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Z(f==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Z(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ae(d)),Xe(l,d)}function Eo(t,e){if(t instanceof Z)return t;if(t instanceof Se)throw t;return t instanceof J?new Z(404,t.message):new Z(502,et("transcription",t,e))}async function qs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw Eo(i,r)}return o?!0:(jn(n,new Z(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var js=new Set(["file","model","language","response_format"]);async function Ao(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ns,i=n.maxAudioPartBytes??Ls;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${sn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await en(t,o)}catch(y){throw y instanceof re?new Z(413,y.message):new Z(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of a.keys()){if(!js.has(y))throw new Z(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,h]of u)if(h>1)throw new Z(400,`form field "${y}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let l=a.get("model");if(l!==null&&typeof l!="string")throw new Z(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Z(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,f=a.get("response_format")??"json";if(f!=="json")throw new Z(400,`response_format ${JSON.stringify(f)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new Z(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>i)throw new Z(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let b=new Uint8Array(await m.arrayBuffer());if(!Ro(b))throw new Z(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let k=Us(b);if(k===null)throw new Z(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ds(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",b.length,b.length),!await qs(n.transcriptionModels,d,e,r))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(b).toString("base64"),format:"wav"}}];try{let y=await Bs(n.clients,d,_,p,n.turn?pe(n.turn):void 0,n.turn,r);Fs(n.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw Eo(y,r)}}catch(s){if(s instanceof re){jn(e,new Z(413,s.message));return}if(s instanceof Z){jn(e,s);return}throw s}}var To="/v1/usage/requests",Io=1e4,Hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},at=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Oo=1024*1024;function Hn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Pe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Pe(`"${e}" must be an array of uuid strings`);if(n.length>Io)throw new Pe(`"${e}" carries ${n.length} ids; at most ${Io} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Hs.test(i))throw new Pe(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Po(t){return Hn(t,"inference_ids")}function an(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new at(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new at(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var cn=require("@urun-sh/core");var Jn="/partners/huggingface/v1/billing/requests";function Js(t){return Hn(t,"requestIds")}function Gs(t){return t>=200&&t<=399}function Vs(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Gs(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Co(t,e){let n=Js(t),r=await e(n);return an(r,n),Vs(r)}var Ws={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Ks(t){return Ws[t]??null}var No=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function zs(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ys(t){return t==="surface"}function Xs(t){let e=t?.ledgerFailureReason;return No.includes(e)?e:"unknown"}var Qs=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Mo=["priced","unpriced"],Zs={written:Mo,already_written:Mo,skipped:Qs,failed:No},xd=Object.entries(Zs).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ea(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function ta(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var na=256,$o=4096,It=12e4,ra=250,oa=8e3,Tt=[],Lo=new Set,Ot=0,At=!1;var ia=new Set;function sa(){return Ot===0&&Tt.length===0}function aa(){if(sa()){At=!1;for(let t of[...ia])t()}}function Uo(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
26
26
|
`}function ua(t){Fe(process.stdout,t)}function Do(t,e){try{t(e)}catch{}}function Fo(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ua,o=Ks(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),Do(r,Uo("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:ta(e),completed_at:e.ts,billable_outcome:ea(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Tt.length>=$o){s("queue_full",`${Tt.length} ledger writes are already waiting (capacity ${$o}, ${Ot} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Tt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Ot<na&&(Ot+=1,la())}async function la(){try{for(;;){let t=da();if(t===void 0)return;Lo.add(t);try{await ca(t)}finally{Lo.delete(t)}}}finally{Ot-=1,aa()}}function da(){let t=Date.now();for(;;){let e=Tt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<It)return e;ut(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${It}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function ca(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);ut(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=zs(o);if(i!==null){ut(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Xs(o),a=Date.now()-t.queuedAt;if(At){ut(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Ys(s)&&a<It){if(await fa(pa(t.attempts)),At||Date.now()-t.queuedAt>=It){let u=Date.now()-t.queuedAt;ut(t,{outcome:"failed",reason:At?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:At?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${It}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}ut(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function pa(t){return Math.min(oa,ra*2**Math.max(0,t-1))}function fa(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function ut(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Do(t.report,Uo(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Wn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ma(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Kn(t,e,n){let r=e.error,o=r?.type??"upstream_error",i=n?.operatorError??(d=>console.error(d)),s=ke(r),a=s??_e(n?.inferenceId??null);s===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),oe(t,l,{error:{message:a,type:o,code:u}})}function we(t,e,n,r){oe(t,e,{type:"error",error:{type:n,message:r}})}function lt(t,e,n){if(e==="anthropic"){oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ha=64*1024*1024,Pt=class extends Error{};async function Bo(t,e=ha){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Pt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function He(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Ho(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function un(t){let e=Ho(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function qo(t){let e=un(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:ga(t)},completion_tokens_details:{reasoning_tokens:0}}}function ga(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function ya(t,e){let n=Ho(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function _a(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function wa(t,e){let n=_a(e);n&&(t.timing=n),t.outputSeconds=Ae(e)}function Je(t,e){ya(t,e),wa(t,e)}async function pn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Jo(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function va(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var ln=class extends Error{};function ba(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new ln(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Sa(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:ba(n.role,n.content)})}return e}function Gn(t){return ze(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function ka(t,e,n,r,o,i,s){let a=mt(i.id),u=t.stream===!0;if(i.model=se(t),i.stream=u,await pn(i,e,typeof t.model=="string"?t.model:void 0),u){let y;try{y=await gt({body:t,clients:e,store:n,stats:o,responseId:a,turn:i})}catch(h){if(h instanceof J){lt(r,"openai",h);return}if(h instanceof fe){K(r,h.status,h.message);return}if(h instanceof ge||h instanceof le){r.setHeader("retry-after","2"),K(r,503,h.message,"capacity_error");return}throw h}Wn(r);for await(let h of y.events){if(h.type==="error"){i.streamError=!0;let v=h.error,$=ke(v),P=$??_e(i.id);$===null&&s(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),r.write(`event: error
|
|
27
27
|
data: ${JSON.stringify({error:{message:P,type:v?.type??"upstream_error",code:v?.code??null}})}
|
|
28
28
|
|
|
@@ -55,10 +55,10 @@ data: ${JSON.stringify(h)}
|
|
|
55
55
|
|
|
56
56
|
`),n.write(`data: [DONE]
|
|
57
57
|
|
|
58
|
-
`),n.end();return}finally{M?.flush(),M?.dispose()}}let b="",k="",_=[],y=new Te;for await(let g of r.track(m,p,o)){_.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(b+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(k+=g.delta);let w=Ye(g);if(w&&y.add(w),g.type==="error"){Kn(n,g,{inferenceId:o.id,operatorError:s});return}}let h=be(_);Je(o,h);let v=Gn(h),$=v.length>0?v:Gn({output:y.items()}),P=Ue(f,$.length,b);if(P){K(n,502,Ne(p,P),"upstream_error");return}let I=$.map(({index:g,...w})=>w),
|
|
59
|
-
data: ${JSON.stringify({type:
|
|
58
|
+
`),n.end();return}finally{M?.flush(),M?.dispose()}}let b="",k="",_=[],y=new Te;for await(let g of r.track(m,p,o)){_.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(b+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(k+=g.delta);let w=Ye(g);if(w&&y.add(w),g.type==="error"){Kn(n,g,{inferenceId:o.id,operatorError:s});return}}let h=be(_);Je(o,h);let v=Gn(h),$=v.length>0?v:Gn({output:y.items()}),P=Ue(f,$.length,b);if(P){K(n,502,Ne(p,P),"upstream_error");return}let I=$.map(({index:g,...w})=>w),R={role:"assistant",content:b||null},A=k||Jo(h);A&&(R.reasoning_content=A),I.length>0&&(R.tool_calls=I),oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:R,finish_reason:I.length>0?"tool_calls":"stop"}],usage:qo(h)})}var Go="sense-latest";async function Ra(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Go,a=se({model:s});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){K(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){K(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){K(n,400,"systemone media, when present, must be an array");return}let l=await Vo(t,s,a,e,n,r,o,i);l!==null&&oe(n,200,l.answer)}async function Vo(t,e,n,r,o,i,s,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=u;let l=performance.now();i.model(n),await pn(s,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},pe(s))}catch(_){if(_ instanceof J)return lt(o,"openai",_),null;if(_ instanceof ge||_ instanceof le)return o.setHeader("retry-after","2"),K(o,503,_.message,"capacity_error"),null;throw _}u.dial_ms=Math.round(performance.now()-c);let p=[],f=null;try{for await(let _ of i.track(d,n,s))if(f===null&&(f=performance.now(),u.first_event_ms=Math.round(f-c)),p.push(_),_.type==="error")return Kn(o,_,{inferenceId:s.id,operatorError:a}),null}catch(_){if(_ instanceof J)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),lt(o,"openai",_),null;if(_ instanceof ge||_ instanceof le)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),o.setHeader("retry-after","2"),K(o,503,_.message,"capacity_error"),null;throw f!==null&&(u.stream_ms=Math.round(performance.now()-f)),_}f!==null&&(u.stream_ms=Math.round(performance.now()-f));let m=be(p);if(m==null)return K(o,502,"upstream produced no response.completed event","upstream_error"),null;Je(s,m);let b=Xe(p,m),k;try{k=JSON.parse(b)}catch{return K(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return K(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let _=k.timing;if(typeof _=="object"&&_!==null&&!Array.isArray(_)&&"question_fwd_ms"in _&&"head_ms"in _){let y=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=y(_.question_fwd_ms),u.head_ms=y(_.head_ms)}}return{answer:k,completed:m}}async function Ea(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"decisions requires a JSON object body");return}let s=typeof t.model=="string"&&t.model?t.model:Go,a=se({model:s});o.model=a,o.stream=!1;let u;try{u=Gr(t,s)}catch(p){if(p instanceof U){K(n,400,p.message);return}throw p}let l=await Vo(u.systemone,s,a,e,n,r,o,i);if(l===null)return;let d;try{d=Kr(u.specs,l.answer)}catch(p){if(p instanceof ie){K(n,502,p.message,"upstream_error");return}throw p}let c;try{c=zr(l.completed.usage)}catch(p){if(p instanceof ie){K(n,502,p.message,"upstream_error");return}throw p}oe(n,200,{model:s,answers:d,...c===null?{}:{usage:c}})}function Aa(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Ct=class extends Error{};function dn(t){return new Ct(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ia(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 Ta(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 Ct(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Oa(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw dn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw dn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Pa(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw dn(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:Oa(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw dn(a)}}return i(),r}function Vn(t){return ze(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 Ca(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){we(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){we(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){we(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"))){we(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=xr(o.id),l=[],d;try{t.system&&l.push({role:"system",content:Aa(t.system)});for(let R of s)l.push(...Pa(R));d=Ta(t.tool_choice)}catch(R){if(R instanceof Ct){we(n,400,"invalid_request_error",R.message);return}throw R}let c=se(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 p=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:l,stream:!0,tools:Ia(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},pe(o))}catch(R){if(R instanceof J){lt(n,"anthropic",R);return}if(R instanceof ge||R instanceof le){n.setHeader("retry-after","2"),we(n,503,"capacity_error",R.message);return}throw R}let m=(R,A)=>{n.destroyed||n.write(`event: ${R}
|
|
59
|
+
data: ${JSON.stringify({type:R,...A})}
|
|
60
60
|
|
|
61
|
-
`)};if(t.stream===!0){let x=r.track(f,c,o);Wn(n),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,g="",w=0,E="none",M=()=>E,F=-1,j=-1,L=new Te,D=[],G=()=>{E!=="none"&&(E="none",m("content_block_stop",{index:F}))},O=(Y,ee)=>{G(),E=Y,F=w++,m("content_block_start",{index:F,content_block:ee})};for await(let Y of x){if(n.destroyed)break;D.push(Y);let ee=Ye(Y);if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")M()!=="thinking"&&O("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:F,delta:{type:"thinking_delta",thinking:Y.delta}});else if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")M()!=="text"&&O("text",{type:"text",text:""}),A+=1,g+=Y.delta,m("content_block_delta",{index:F,delta:{type:"text_delta",text:Y.delta}});else if(ee){let{call:he}=L.add(ee);(M()!=="tool"||ee.tool_index!==j)&&(j=ee.tool_index,O("tool",{type:"tool_use",id:he.id??`call_${ee.tool_index}`,name:he.name??"",input:{}})),ee.delta&&m("content_block_delta",{index:F,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(Y.type==="error"){o.streamError=!0;let he=Y.error,Ce=ke(he);Ce===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),m("error",{error:{type:"api_error",message:Ce??_e(o.id)}}),n.end();return}}if(n.destroyed)return;let z=be(D),C=ze(z),N=Ue(p,L.size+C.length,g);if(N){o.streamError=!0,m("error",{error:{type:"api_error",message:Ne(c,N)}}),n.end();return}G();let W=[];if(L.size===0)try{W=Vn(z)}catch(Y){o.streamError=!0;let ee=de(Y,{inferenceId:o.id});ee.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Y instanceof Error?Y.message:Y)}`),m("error",{error:{type:"api_error",message:ee.message}}),n.end();return}w===0&&W.length===0&&(O("text",{type:"text",text:""}),G()),W.forEach(Y=>{let ee=w++;m("content_block_start",{index:ee,content_block:{...Y,input:{}}}),m("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(Y.input??{})}}),m("content_block_stop",{index:ee})});let ve=L.size>0||W.length>0,Ge=un(z);Je(o,z),m("message_delta",{delta:{stop_reason:ve?"tool_use":"end_turn"},usage:Ge?{input_tokens:Ge.input_tokens,output_tokens:Ge.output_tokens}:{output_tokens:A}}),m("message_stop",{}),n.end();return}let b="",k="",_=[],y=new Te;for await(let x of r.track(f,c,o)){_.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(b+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(k+=x.delta);let A=Ye(x);if(A&&y.add(A),x.type==="error"){let g=x.error,w=g?.type==="invalid_request_error",E=ke(g);E===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(x)}`),we(n,w?400:502,w?"invalid_request_error":"api_error",E??_e(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let h=be(_);Je(o,h);let v;try{v=Vn(h),v.length===0&&y.size>0&&(v=Vn({output:y.items()}))}catch(x){let A=de(x,{inferenceId:o.id});A.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(x instanceof Error?x.message:x)}`),we(n,502,"api_error",A.message);return}let $=Ue(p,v.length,b);if($){we(n,502,"api_error",Ne(c,$));return}let P=[],I=k||Jo(h);I&&P.push({type:"thinking",thinking:I}),(b||v.length===0)&&P.push({type:"text",text:b}),P.push(...v),oe(n,200,{id:u,type:"message",role:"assistant",content:P,model:a,stop_reason:v.length>0?"tool_use":"end_turn",usage:un(h)??{input_tokens:0,output_tokens:0}})}function Ma(t){Fe(process.stdout,t)}function $a(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Ma,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new $e;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),f=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(h,v,$,P,I)=>f?we(c,h,P,v):K(c,h,v,$,I),b=yn(p.pathname),k=p.pathname.startsWith("/partners/"),_=b||k?{id:ft(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;_&&(c.setHeader(br,_.id),c.once("close",()=>{let h=Rr({turn:_,method:d.method??"",path:p.pathname,res:c});s(Er(h)),u?.(h),Fo({record:h,ledger:t.ledger??null,req:d})}));let y=()=>Sr(p.pathname,_);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===To?"canonical":p.pathname===Jn?"huggingface":null;if(h){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let I=t.usage;if(!I){m(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let x=I.authorize(d),A;try{A=await Bo(d,Oo)}catch(E){if(E instanceof Pt){m(413,E.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=E=>I.lookup(x,E),w;try{if(h==="canonical"){let E=Po(A),M=await g(E);an(M,E),w={requests:M}}else w=await Co(A,g)}catch(E){if(E instanceof Pe){m(E.status,E.message,"invalid_request_error","invalid_request_error");return}throw E}oe(c,200,w);return}if(d.method==="GET"&&p.pathname===ct){let I=await i(d);if(_&&(_.org=I.tenant??null),!I.openRouterModels){m(501,`GET ${ct} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await I.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Jn} and GET ${ct}`,"invalid_request_error","not_found_error");return}let v=await i(d);if(_&&(_.org=v.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ct}),c.end();return}oe(c,200,await v.listModels());return}if(d.method==="GET"&&p.pathname===Qr){if(!v.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listImageModels());return}if(Xr(p.pathname)){if(!v.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let I={clients:v,imageModels:v.supportsImages,stats:l,turn:y(),operatorLog:a};p.pathname===tn?await uo(d,c,I):await ao(d,c,I);return}if(d.method==="GET"&&p.pathname===xo){if(!v.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listSpeechToTextModels());return}if(ko(p.pathname)){if(!v.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${sn}`,"not_implemented","not_implemented_error");return}let I={clients:v,transcriptionModels:v.supportsTranscription,stats:l,turn:y(),operatorLog:a};await Ao(d,c,I);return}if(_o(p.pathname)){if(!v.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Et}`,"not_implemented","not_implemented_error");return}let I={clients:v,speechModels:v.supportsSpeech,stats:l,turn:y(),operatorLog:a};await So(d,c,I);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let $;try{$=await Bo(d)}catch(I){if(I instanceof Pt){m(413,I.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=Buffer.byteLength(JSON.stringify($));if(p.pathname==="/v1/responses"){l.request("responses",P,P),await ka($,v,ht(v),c,l,y(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",P,P),await xa($,v,c,l,y(),d.headers[Ln],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",P,P),await Ra($,v,c,l,y(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",P,P),await Ea($,v,c,l,y(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",P,P),await Ca($,v,c,l,y(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",P,P),we(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let v=String(h instanceof Error?h.message:h);if(!c.headersSent){let I=o?.(h)??null;if(I){I.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${I.operatorDetail}`),m(I.status,v,I.openaiType,I.anthropicType,I.code);return}if(h instanceof cn.SessionAllocationError){let A=Gt(h.code);if(A){let g=h.retryAfterSeconds??(A.status===429?30:void 0);g!==void 0&&c.setHeader("Retry-After",String(g)),m(A.status,yt(A,h.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof cn.SessionFailedError){let A=Vt(h);if(A){let g=A.status===429?30:void 0;g!==void 0&&c.setHeader("Retry-After",String(g)),m(A.status,yt(A,h.status.sessionId?`session ${h.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof at){m(502,v,"upstream_error","api_error");return}if(h instanceof De){h.retryable&&c.setHeader("Retry-After","1");let A=de(h,{inferenceId:_?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),m(502,A.message,"upstream_error","api_error",h.code);return}if(h instanceof Ze){c.setHeader("Retry-After",String(h.retryAfterSeconds)),m(h.status,v,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let x=de(h,{inferenceId:_?.id??null});x.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),m(500,x.message,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0);let $=h instanceof De?h.code:null,P=de(h,{inferenceId:_?.id??null});P.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),c.destroyed||(f?c.write(`event: error
|
|
61
|
+
`)};if(t.stream===!0){let R=r.track(f,c,o);Wn(n),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,g="",w=0,E="none",M=()=>E,F=-1,j=-1,L=new Te,D=[],G=()=>{E!=="none"&&(E="none",m("content_block_stop",{index:F}))},O=(Y,ee)=>{G(),E=Y,F=w++,m("content_block_start",{index:F,content_block:ee})};for await(let Y of R){if(n.destroyed)break;D.push(Y);let ee=Ye(Y);if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")M()!=="thinking"&&O("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:F,delta:{type:"thinking_delta",thinking:Y.delta}});else if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")M()!=="text"&&O("text",{type:"text",text:""}),A+=1,g+=Y.delta,m("content_block_delta",{index:F,delta:{type:"text_delta",text:Y.delta}});else if(ee){let{call:he}=L.add(ee);(M()!=="tool"||ee.tool_index!==j)&&(j=ee.tool_index,O("tool",{type:"tool_use",id:he.id??`call_${ee.tool_index}`,name:he.name??"",input:{}})),ee.delta&&m("content_block_delta",{index:F,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(Y.type==="error"){o.streamError=!0;let he=Y.error,Ce=ke(he);Ce===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),m("error",{error:{type:"api_error",message:Ce??_e(o.id)}}),n.end();return}}if(n.destroyed)return;let z=be(D),C=ze(z),N=Ue(p,L.size+C.length,g);if(N){o.streamError=!0,m("error",{error:{type:"api_error",message:Ne(c,N)}}),n.end();return}G();let W=[];if(L.size===0)try{W=Vn(z)}catch(Y){o.streamError=!0;let ee=de(Y,{inferenceId:o.id});ee.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Y instanceof Error?Y.message:Y)}`),m("error",{error:{type:"api_error",message:ee.message}}),n.end();return}w===0&&W.length===0&&(O("text",{type:"text",text:""}),G()),W.forEach(Y=>{let ee=w++;m("content_block_start",{index:ee,content_block:{...Y,input:{}}}),m("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(Y.input??{})}}),m("content_block_stop",{index:ee})});let ve=L.size>0||W.length>0,Ge=un(z);Je(o,z),m("message_delta",{delta:{stop_reason:ve?"tool_use":"end_turn"},usage:Ge?{input_tokens:Ge.input_tokens,output_tokens:Ge.output_tokens}:{output_tokens:A}}),m("message_stop",{}),n.end();return}let b="",k="",_=[],y=new Te;for await(let R of r.track(f,c,o)){_.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(b+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(k+=R.delta);let A=Ye(R);if(A&&y.add(A),R.type==="error"){let g=R.error,w=g?.type==="invalid_request_error",E=ke(g);E===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),we(n,w?400:502,w?"invalid_request_error":"api_error",E??_e(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let h=be(_);Je(o,h);let v;try{v=Vn(h),v.length===0&&y.size>0&&(v=Vn({output:y.items()}))}catch(R){let A=de(R,{inferenceId:o.id});A.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),we(n,502,"api_error",A.message);return}let $=Ue(p,v.length,b);if($){we(n,502,"api_error",Ne(c,$));return}let P=[],I=k||Jo(h);I&&P.push({type:"thinking",thinking:I}),(b||v.length===0)&&P.push({type:"text",text:b}),P.push(...v),oe(n,200,{id:u,type:"message",role:"assistant",content:P,model:a,stop_reason:v.length>0?"tool_use":"end_turn",usage:un(h)??{input_tokens:0,output_tokens:0}})}function Ma(t){Fe(process.stdout,t)}function $a(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Ma,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new $e;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),f=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(h,v,$,P,I)=>f?we(c,h,P,v):K(c,h,v,$,I),b=yn(p.pathname),k=p.pathname.startsWith("/partners/"),_=b||k?{id:ft(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;_&&(c.setHeader(br,_.id),c.once("close",()=>{let h=Rr({turn:_,method:d.method??"",path:p.pathname,res:c});s(Er(h)),u?.(h),Fo({record:h,ledger:t.ledger??null,req:d})}));let y=()=>Sr(p.pathname,_);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===To?"canonical":p.pathname===Jn?"huggingface":null;if(h){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let I=t.usage;if(!I){m(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let R=I.authorize(d),A;try{A=await Bo(d,Oo)}catch(E){if(E instanceof Pt){m(413,E.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=E=>I.lookup(R,E),w;try{if(h==="canonical"){let E=Po(A),M=await g(E);an(M,E),w={requests:M}}else w=await Co(A,g)}catch(E){if(E instanceof Pe){m(E.status,E.message,"invalid_request_error","invalid_request_error");return}throw E}oe(c,200,w);return}if(d.method==="GET"&&p.pathname===ct){let I=await i(d);if(_&&(_.org=I.tenant??null),!I.openRouterModels){m(501,`GET ${ct} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await I.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Jn} and GET ${ct}`,"invalid_request_error","not_found_error");return}let v=await i(d);if(_&&(_.org=v.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ct}),c.end();return}oe(c,200,await v.listModels());return}if(d.method==="GET"&&p.pathname===Qr){if(!v.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listImageModels());return}if(Xr(p.pathname)){if(!v.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let I={clients:v,imageModels:v.supportsImages,stats:l,turn:y(),operatorLog:a};p.pathname===tn?await uo(d,c,I):await ao(d,c,I);return}if(d.method==="GET"&&p.pathname===xo){if(!v.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listSpeechToTextModels());return}if(ko(p.pathname)){if(!v.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${sn}`,"not_implemented","not_implemented_error");return}let I={clients:v,transcriptionModels:v.supportsTranscription,stats:l,turn:y(),operatorLog:a};await Ao(d,c,I);return}if(_o(p.pathname)){if(!v.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Et}`,"not_implemented","not_implemented_error");return}let I={clients:v,speechModels:v.supportsSpeech,stats:l,turn:y(),operatorLog:a};await So(d,c,I);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let $;try{$=await Bo(d)}catch(I){if(I instanceof Pt){m(413,I.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=Buffer.byteLength(JSON.stringify($));if(p.pathname==="/v1/responses"){l.request("responses",P,P),await ka($,v,ht(v),c,l,y(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",P,P),await xa($,v,c,l,y(),d.headers[Ln],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",P,P),await Ra($,v,c,l,y(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",P,P),await Ea($,v,c,l,y(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",P,P),await Ca($,v,c,l,y(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",P,P),we(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let v=String(h instanceof Error?h.message:h);if(!c.headersSent){let I=o?.(h)??null;if(I){I.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${I.operatorDetail}`),m(I.status,v,I.openaiType,I.anthropicType,I.code);return}if(h instanceof cn.SessionAllocationError){let A=Gt(h.code);if(A){let g=h.retryAfterSeconds??(A.status===429?30:void 0);g!==void 0&&c.setHeader("Retry-After",String(g)),m(A.status,yt(A,h.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof cn.SessionFailedError){let A=Vt(h);if(A){let g=A.status===429?30:void 0;g!==void 0&&c.setHeader("Retry-After",String(g)),m(A.status,yt(A,h.status.sessionId?`session ${h.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof at){m(502,v,"upstream_error","api_error");return}if(h instanceof De){h.retryable&&c.setHeader("Retry-After","1");let A=de(h,{inferenceId:_?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),m(502,A.message,"upstream_error","api_error",h.code);return}if(h instanceof Ze){c.setHeader("Retry-After",String(h.retryAfterSeconds)),m(h.status,v,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let R=de(h,{inferenceId:_?.id??null});R.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),m(500,R.message,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0);let $=h instanceof De?h.code:null,P=de(h,{inferenceId:_?.id??null});P.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),c.destroyed||(f?c.write(`event: error
|
|
62
62
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:P.message}})}
|
|
63
63
|
|
|
64
64
|
`):c.write(`data: ${JSON.stringify({error:{message:P.message,type:"upstream_error",code:$}})}
|