@urun-sh/openai 0.6.40 → 0.6.41
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-PT5N7AY7.js → chunk-HBKAN6PP.js} +1 -1
- package/dist/{chunk-BWYY4IPR.js → chunk-ILYHXVNZ.js} +1 -1
- package/dist/{chunk-G5VRFFBE.js → chunk-PAAFRUQZ.js} +18 -18
- package/dist/{chunk-L6CT7ZVO.js → chunk-VVQSFACF.js} +1 -1
- package/dist/hosted/bin.cjs +27 -27
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +26 -26
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +2 -2
- package/dist/pooler/bin.cjs +10 -10
- package/dist/pooler/bin.js +10 -10
- package/dist/proxy/cli.cjs +26 -26
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +22 -22
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-
|
|
1
|
+
import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-HBKAN6PP.js";import{A as wt,B as bt,C as vt,D as _t,E as St,b as tt,d as nt,e as oe,j as rt,k as ot,m as it,n as at,o as lt,p as ct,q as dt,r as ut,s as ft,u as pt,v as ie,w as ht,x as gt,y as mt,z as yt}from"./chunk-PAAFRUQZ.js";import{a as et}from"./chunk-QTHFMDZY.js";import{a as At}from"./chunk-G7CSAISC.js";import{a as kt}from"./chunk-L4QBHSVY.js";import{l as st,m as se}from"./chunk-ILYHXVNZ.js";import{a as Lt,c as X,e as xe}from"./chunk-KKCUIOL4.js";import{a as Xe}from"./chunk-4NMMWAKD.js";import{b as qe,d as Ne}from"./chunk-GX243AIV.js";import{e as Qe,j as ne,n as Ze,o as re,p as Ie}from"./chunk-HPUX2H65.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as K,Gauge as ae,Histogram as le,Registry as fn,collectDefaultMetrics as pn}from"@prometheus-io/client";import{createServer as hn}from"http";var lo=9464,Ct="/metrics",ce="(other)",gn="(none)",mn=64,yn=128,wn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",pt,gt,Qe],bn=new Set(wn);function vn(t){return bn.has(t)?t:ce}function _n(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var de=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?gn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,ce):(this.admitted.add(e),e):ce}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ue=class{registry=new fn;modelLabel=new de(mn);orgLabel=new de(yn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ae({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new K({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new le({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new le({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new K({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new K({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new K({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of mt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ae({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},yt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},wt()/1e3)}}),this.labelCardinality=new ae({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new K({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new ae({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new le({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new le({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new K({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new K({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&pn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=vn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let c=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?ce:e.method,status_class:_n(e.status),stream:c,model:s,org:i}),this.duration.observe({lane:n,stream:c,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Pt(t){return hn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ct){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ct}
|
|
2
2
|
`);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
3
3
|
`);return}n.end()})})}L();import{createHash as Nt}from"crypto";import{createServer as Sn}from"http";var ho=9465,kn="x-urun-key-id",En="x-urun-key-fingerprint",Rn="urun-ratelimit-bucket:",Ln="urun-ratelimit-tier:",Tt="anonymous",An=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Cn(t){return Nt("sha256").update(`${Rn}${t}`).digest("hex")}function Pn(t){return Nt("sha256").update(`${Ln}${t}`).digest("hex")}function Tn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return An.test(n)?n:null}function It(){return Sn((t,e)=>{let n=Tn(t.headers.authorization);e.setHeader(kn,n===null?Tt:Cn(n)),e.setHeader(En,n===null?Tt:Pn(n)),e.writeHead(200),e.end()})}L();import{createClientToken as Nn,ClientTokenError as In}from"@urun-sh/core";import{createPublicKey as On,verify as Un}from"crypto";var Ot="urun-session-gateway",xn="machine",$n=3e5;function Dn(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var I=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},H=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function he(t){let e=(t??"").trim();if(e==="")throw new I("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new I("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Hn=60,Mn=6e4,Fn=4096;function Wn(t){return t===401||t===403}var fe=class{constructor(e){this.opts=e;this.mint=e.mint??Nn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new I("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Mn)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Hn});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof In&&Wn(s.status)?(this.cache.delete(e),new I("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new H("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new H("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=Fn){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function Ut(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var pe=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<$n)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof H?i:new H("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new I("malformed machine token");let s,i;try{s=Ut(n),i=Ut(r)}catch{throw new I("malformed machine token")}if(s.alg!=="RS256")throw new I(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",c=typeof i.iss=="string"?i.iss:"";if(c===""||!this.opts.issuers.includes(c))throw new I(`machine token issuer is not one this endpoint accepts (${JSON.stringify(c)})`);if(i.aud!==Ot)throw new I(`machine token audience must be ${Ot} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==xn)throw new I(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new I("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new I("machine token is expired \u2014 re-mint and retry");let h=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,k=await this.jwksKeys(!1),v=a===""?void 0:k.find(w=>w.kid===a&&h(w));if(v===void 0&&(k=await this.jwksKeys(!0),v=a===""?void 0:k.find(w=>w.kid===a&&h(w))),v===void 0)throw new I(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),S=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),g=!1;try{let w=On({key:v,format:"jwk"});g=Un("RSA-SHA256",f,w,S)}catch{g=!1}if(!g)throw new I("machine token signature failed verification");return{apiKey:e,orgId:u,credential:"machine"}}};function $e(t,e,n){return n!==null&&Dn(t)?n.verify(t):e.resolve(t)}L();var Gn=8080,De="serve",So="0.0.0.0";function Kn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function ko(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Gn:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=st(se(Kn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?se(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let c=i?{catalogUrl:se(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let h=u?{keyId:d,key:u}:void 0,k={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},v=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],f=v.filter((b,_)=>Object.values(k)[_]==="");if(f.length!==0&&f.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the lane plane`);let S=f.length===0?k:void 0,g={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],A=w.filter((b,_)=>Object.values(g)[_]==="");if(A.length!==0&&A.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${A.join(", ")}, which would half-configure the pooler cutover`);let E=A.length===0?g:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},m=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],C=m.filter((b,_)=>Object.values(p)[_]==="");if(C.length!==0&&C.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${C.join(", ")}, which would half-configure the machine-identity rung`);let T=p.issuers.split(",").map(b=>b.trim()).filter(b=>b!=="");if(T.length===0&&C.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let l=Number(p.tokenTtlS);if(C.length===0&&(!Number.isFinite(l)||l<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let y=C.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:T,tokenTtlS:l}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:c,ledgerSigning:h,lane:S,pooler:E,machine:y}}L();import{createHash as Qn,randomUUID as Ht}from"crypto";L();import{request as Bn}from"http";var jn="/pooler/v1/inference",B=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Jn=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Vn=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},$t=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),zn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await $t(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new B(t.status,e,n,t.retryAfterSeconds)};async function Yn(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${jn}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Jn(e),firstMessage:Vn(e)}});return new Promise((a,c)=>{let u=Bn({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let h=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:d})});u.on("error",d=>c(new B(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var xt=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*qn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
4
4
|
|