@urun-sh/openai 0.6.47 → 0.6.49
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-VRNM6ZKU.js → chunk-2KMMXZLV.js} +1 -1
- package/dist/{chunk-5D7TVOAX.js → chunk-3JZAWWVV.js} +1 -1
- package/dist/{chunk-2KN45E7P.js → chunk-ELH2AYM6.js} +1 -1
- package/dist/{chunk-LROCLDDN.js → chunk-NZ5EWOMJ.js} +1 -1
- package/dist/{chunk-P2YVKUSQ.js → chunk-X23WP5HQ.js} +2 -2
- package/dist/hosted/bin.cjs +1 -1
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +36 -33
- package/dist/pooler/bin.cjs +5 -5
- package/dist/pooler/bin.js +9 -9
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
package/dist/hosted/index.cjs
CHANGED
|
@@ -9,7 +9,7 @@ Connection: close\r
|
|
|
9
9
|
\r
|
|
10
10
|
${h}\r
|
|
11
11
|
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(l=>l===void 0?i():a(l)))})(),s)}var ze=require("ws");var Xi=require("crypto"),Qi="Inference-Id";function at(){return(0,Xi.randomUUID)()}function So(t){return t==="/v1"||t.startsWith("/v1/")}function Zi(t,e){if(!So(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 mn(t){return`resp_${t}`}function ea(t){return`chatcmpl-${t}`}function ta(t){return`msg_${t}`}function ve(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function na(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 ra(t){return`${JSON.stringify(t)}
|
|
12
|
-
`}var tc=256,nc=128;function me(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,nc)}var lt=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>=tc?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},rc=256;function oc(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 ut=class extends Error{},At=class{conversations=new Map;thread(e,n){let r=oc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ut(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=rc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},oa=new WeakMap;function gn(t){let e=oa.get(t);return e||(e=new At,oa.set(t,e)),e}function It(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Me(t){return t.find(e=>e.type==="response.completed")?.response??null}function Tt(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 Ve=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}))}},sc=["<tool_call>","<function="];function ic(t){return sc.find(e=>t.includes(e))}function dt(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 ct(t,e,n){if(!(!t||e>0))return ic(n)}function Ot(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 Fe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ac(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 ko(t,e){let n=ac(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Pt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ut?new be(n.message,"previous_response_not_found",400,"previous_response_id"):new be(String(n instanceof Error?n.message:n),"invalid_input")}}function sa(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ro(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new be("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...sa(e)!==void 0?{response_format:sa(e)}:{}},o)}async function hn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Pt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,l=e.store!==!1,u=me(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await Ro(n,e,s,!0,c?ve(c):void 0);return{responseId:i,events:cc({events:p,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function lc(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?dc(o[i++],l):l),...uc(r,n)]}function uc(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function dc(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 s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*cc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=D=>D.response&&typeof D.response=="object"?{...D,response:{...D.response,id:r}}:D,p=`item_${r.slice(5)}`,h=!1,m=!1,w=0;function*R(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],b=(D,j)=>{v.push({output_index:D,item:j})},f=!1,g=0,y="",k=0,x="";function*E(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:x};let D={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:x}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:D},b(g,D),x=""}let I=!1,S=0,T="",_=0,A="",O="";function*P(D){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:T,output_index:S,content_index:0,text:A},yield{type:"response.content_part.done",item_id:T,output_index:S,content_index:0,part:{type:"output_text",text:A}};let j={id:T,type:"message",role:"assistant",status:D,content:[{type:"output_text",text:A}]};yield{type:"response.output_item.done",output_index:S,item:j},b(S,j),A=""}let C=new Ve,$=null,F=-1;function*B(D){if(!$)return;let j=$;$=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let z={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:D};yield{type:"response.output_item.done",output_index:j.outputIndex,item:z},b(j.outputIndex,z)}let K=!1;for await(let D of u.track(e,o,t.turn)){d.push(D);let j=String(D.type??"");if(j==="response.created"||j==="response.in_progress"){h=!0,yield c(D);continue}if(j==="response.output_item.added"){m=!0,yield c(D);continue}if(j==="response.reasoning_text.delta"&&!m){yield*R(),f||(f=!0,g=w++,k+=1,y=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),x+=String(D.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:D.delta};continue}if(j==="response.output_text.delta"&&!m){yield*R(),yield*E(),I||(I=!0,S=w++,_+=1,T=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:S,item:{id:T,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:T,output_index:S,content_index:0,part:{type:"output_text",text:""}}),A+=String(D.delta??""),O+=String(D.delta??""),yield{type:j,item_id:T,output_index:S,content_index:0,delta:D.delta};continue}let z=m?null:Tt(D);if(z){if(yield*R(),yield*E(),yield*P("completed"),C.add(z),z.tool_index!==F){yield*B("completed"),F=z.tool_index;let Ze=w++;$={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:Ze,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:Ze,item:{id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:"",status:"in_progress"}}}$&&(z.call_id&&($.callId=z.call_id),z.name&&($.name=z.name),$.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:$.fcId,output_index:$.outputIndex,delta:z.delta});continue}if(j==="response.completed"&&!m){let Ze=It(D.response),St=ct(s,C.size+Ze.length,O);if(St){K=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:dt(o,St)}};break}if(yield*E(),yield*P("completed"),yield*B("completed"),C.size===0)for(let re of Ze){let xe=w++,et=re.id??re.call_id??`fc_${xe}`,eo=re.arguments??"",Qs={id:et,type:"function_call",call_id:re.call_id??et,name:re.name??""};yield{type:"response.output_item.added",output_index:xe,item:{...Qs,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:et,output_index:xe,delta:eo},yield{type:"response.function_call_arguments.done",item_id:et,output_index:xe,arguments:eo};let Zs={...Qs,arguments:eo,status:"completed"};yield{type:"response.output_item.done",output_index:xe,item:Zs},b(xe,Zs)}let Q=lc(v,D.response);yield Q.length>0?c({...D,response:{...D.response,output:Q}}):c(D);continue}yield c(D)}if(yield*E(),yield*P("incomplete"),yield*B("incomplete"),i&&!K){let D=Me(d);l.remember(r,n,ko(D,Ot(d,D)),a)}}var Se=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ue=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var pt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};var Ke=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)}},yn=class extends Ke{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Eo=class extends Ke{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},Ae=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},er=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new yn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let l=r+n-Date.now();if(l<=0)throw new Eo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var xo=require("@urun-sh/core"),Ie=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)}},Ao=33e4;function ia(t,e=Ao){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new tr),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof G||u instanceof xo.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof tr?(await r.return?.(void 0),new Ie("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ie("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ie("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var tr=class extends Error{constructor(){super("stream idle timeout")}};function aa(t){return t instanceof Ie?!1:t instanceof G?!0:t instanceof xo.SessionFailedError?t.kind==="transport-failed":!1}var pc=[/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 Te(t){return!pc.some(e=>e.test(t))}function Oe(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 we(t,e){if(t instanceof G)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=la(t);return n||{message:Oe(e?.inferenceId??null),redacted:!0}}function la(t){return t instanceof qe?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ee?{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 Ke?{message:t.message,redacted:!1}:t instanceof Ie?Te(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ae?{message:t.message,redacted:!1}:t instanceof ue?{message:t.message,redacted:!1}:null}function Ct(t,e,n){let r=n??(i=>console.error(i)),o=la(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Te(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed while serving this request`)}function Ne(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Te(e)?e:null}function ke(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Oo="/v1/responses",fc=64*1024*1024,mc=8*1024*1024,gc=16,ua=32,da=3600*1e3,hc=/^[A-Za-z0-9._-]{1,256}$/;function ge(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var yc=ge(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 Po(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function wc(t){for(;t.bufferedAmount>mc&&t.readyState===ze.WebSocket.OPEN;){let{promise:e,resolve:n}=Po();setTimeout(n,5),await e}}var Io=class extends At{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 ut))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},To=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new Io(gn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${da/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},da).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(ge(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(ge(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(ge(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(ge(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(ge(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(ge(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!hc.test(o.stream_id)){this.sendFrame(yc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ua){this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ua}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=at();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await hn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==ze.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await wc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=at(),o=mn(r);try{let s=Pt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:ke(e);if(e instanceof be)return ge(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 ge(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof G){let a=we(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}`),ge(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),ge(s.status,{type:s.openaiType,message:o},n);let i=we(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ge(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ne(o),a=i??Oe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ge(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=gc;){let{promise:e,resolve:n}=Po();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!==ze.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!==ze.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function nr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
12
|
+
`}var tc=256,nc=128;function me(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,nc)}var lt=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>=tc?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},rc=256;function oc(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 ut=class extends Error{},At=class{conversations=new Map;thread(e,n){let r=oc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ut(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=rc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},oa=new WeakMap;function gn(t){let e=oa.get(t);return e||(e=new At,oa.set(t,e)),e}function It(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Me(t){return t.find(e=>e.type==="response.completed")?.response??null}function Tt(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 Ve=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}))}},sc=["<tool_call>","<function="];function ic(t){return sc.find(e=>t.includes(e))}function dt(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 ct(t,e,n){if(!(!t||e>0))return ic(n)}function Ot(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 Fe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ac(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 ko(t,e){let n=ac(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Pt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ut?new be(n.message,"previous_response_not_found",400,"previous_response_id"):new be(String(n instanceof Error?n.message:n),"invalid_input")}}function sa(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ro(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new be("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...sa(e)!==void 0?{response_format:sa(e)}:{}},o)}async function hn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Pt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,l=e.store!==!1,u=me(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await Ro(n,e,s,!0,c?ve(c):void 0);return{responseId:i,events:cc({events:p,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function lc(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?dc(o[i++],l):l),...uc(r,n)]}function uc(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function dc(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 s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*cc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=D=>D.response&&typeof D.response=="object"?{...D,response:{...D.response,id:r}}:D,p=`item_${r.slice(5)}`,h=!1,m=!1,w=0;function*R(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],b=(D,j)=>{v.push({output_index:D,item:j})},f=!1,g=0,y="",k=0,x="";function*E(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:x};let D={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:x}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:D},b(g,D),x=""}let I=!1,S=0,T="",_=0,A="",O="";function*P(D){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:T,output_index:S,content_index:0,text:A},yield{type:"response.content_part.done",item_id:T,output_index:S,content_index:0,part:{type:"output_text",text:A}};let j={id:T,type:"message",role:"assistant",status:D,content:[{type:"output_text",text:A}]};yield{type:"response.output_item.done",output_index:S,item:j},b(S,j),A=""}let C=new Ve,$=null,F=-1;function*B(D){if(!$)return;let j=$;$=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let z={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:D};yield{type:"response.output_item.done",output_index:j.outputIndex,item:z},b(j.outputIndex,z)}let K=!1;for await(let D of u.track(e,o,t.turn)){d.push(D);let j=String(D.type??"");if(j==="response.created"||j==="response.in_progress"){h=!0,yield c(D);continue}if(j==="response.output_item.added"){m=!0,yield c(D);continue}if(j==="response.reasoning_text.delta"&&!m){yield*R(),f||(f=!0,g=w++,k+=1,y=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),x+=String(D.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:D.delta};continue}if(j==="response.output_text.delta"&&!m){yield*R(),yield*E(),I||(I=!0,S=w++,_+=1,T=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:S,item:{id:T,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:T,output_index:S,content_index:0,part:{type:"output_text",text:""}}),A+=String(D.delta??""),O+=String(D.delta??""),yield{type:j,item_id:T,output_index:S,content_index:0,delta:D.delta};continue}let z=m?null:Tt(D);if(z){if(yield*R(),yield*E(),yield*P("completed"),C.add(z),z.tool_index!==F){yield*B("completed"),F=z.tool_index;let Ze=w++;$={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:Ze,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:Ze,item:{id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:"",status:"in_progress"}}}$&&(z.call_id&&($.callId=z.call_id),z.name&&($.name=z.name),$.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:$.fcId,output_index:$.outputIndex,delta:z.delta});continue}if(j==="response.completed"&&!m){let Ze=It(D.response),St=ct(s,C.size+Ze.length,O);if(St){K=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:dt(o,St)}};break}if(yield*E(),yield*P("completed"),yield*B("completed"),C.size===0)for(let re of Ze){let xe=w++,et=re.id??re.call_id??`fc_${xe}`,eo=re.arguments??"",Qs={id:et,type:"function_call",call_id:re.call_id??et,name:re.name??""};yield{type:"response.output_item.added",output_index:xe,item:{...Qs,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:et,output_index:xe,delta:eo},yield{type:"response.function_call_arguments.done",item_id:et,output_index:xe,arguments:eo};let Zs={...Qs,arguments:eo,status:"completed"};yield{type:"response.output_item.done",output_index:xe,item:Zs},b(xe,Zs)}let Q=lc(v,D.response);yield Q.length>0?c({...D,response:{...D.response,output:Q}}):c(D);continue}yield c(D)}if(yield*E(),yield*P("incomplete"),yield*B("incomplete"),i&&!K){let D=Me(d);l.remember(r,n,ko(D,Ot(d,D)),a)}}var Se=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ue=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var pt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};var Ke=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)}},yn=class extends Ke{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Eo=class extends Ke{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},Ae=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},er=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new yn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let l=r+n-Date.now();if(l<=0)throw new Eo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var xo=require("@urun-sh/core"),Ie=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)}},Ao=33e4;function ia(t,e=Ao){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new tr),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof G||u instanceof xo.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof tr?(await r.return?.(void 0),new Ie("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ie("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ie("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var tr=class extends Error{constructor(){super("stream idle timeout")}};function aa(t){return t instanceof Ie?!1:t instanceof G?!0:t instanceof xo.SessionFailedError?t.kind==="transport-failed":!1}var pc=[/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 Te(t){return!pc.some(e=>e.test(t))}function Oe(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 we(t,e){if(t instanceof G)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=la(t);return n||{message:Oe(e?.inferenceId??null),redacted:!0}}function la(t){return t instanceof qe?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ee?{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 Ke?{message:t.message,redacted:!1}:t instanceof Ie?Te(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ae?{message:t.message,redacted:!1}:t instanceof ue?{message:t.message,redacted:!1}:null}function Ct(t,e,n){let r=n??(i=>console.error(i)),o=la(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Te(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed while serving this request`)}function Ne(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Te(e)?e:null}function ke(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Oo="/v1/responses",fc=64*1024*1024,mc=8*1024*1024,gc=16,ua=32,da=3600*1e3,hc=/^[A-Za-z0-9._-]{1,256}$/;function ge(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var yc=ge(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 Po(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function wc(t){for(;t.bufferedAmount>mc&&t.readyState===ze.WebSocket.OPEN;){let{promise:e,resolve:n}=Po();setTimeout(n,5),await e}}var Io=class extends At{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 ut))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},To=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new Io(gn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${da/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},da).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(ge(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(ge(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(ge(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(ge(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(ge(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(ge(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!hc.test(o.stream_id)){this.sendFrame(yc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ua){this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ua}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=at();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await hn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==ze.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await wc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=at(),o=mn(r);try{let s=Pt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:ke(e);if(e instanceof be)return ge(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 ge(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof G){let a=we(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}`),ge(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),ge(s.status,{type:s.openaiType,message:o},n);let i=we(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ge(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ne(o),a=i??Oe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ge(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=gc;){let{promise:e,resolve:n}=Po();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!==ze.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!==ze.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function nr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
13
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
14
14
|
Connection: close\r
|
|
15
15
|
Content-Type: text/plain; charset=utf-8\r
|
package/dist/hosted/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-
|
|
1
|
+
import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-ELH2AYM6.js";import"../chunk-NZ5EWOMJ.js";import"../chunk-CAR4AEQJ.js";import"../chunk-X23WP5HQ.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-2KMMXZLV.js";import"../chunk-XGAF2NDT.js";import"../chunk-3JZAWWVV.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
|