@urun-sh/openai 0.6.34 → 0.6.35
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-2L7UL6BM.js → chunk-5VMB5HKE.js} +1 -1
- package/dist/{chunk-CY4RJOTS.js → chunk-ITPXS7D4.js} +1 -1
- package/dist/{chunk-AVMTHHBR.js → chunk-LOPBORFM.js} +1 -1
- package/dist/{chunk-LDBKLCCU.js → chunk-UO6N5FH7.js} +1 -1
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +30 -30
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +1 -1
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as lt,c as _e,d as ct,e as ve}from"./chunk-
|
|
1
|
+
import{a as lt,c as _e,d as ct,e as ve}from"./chunk-UO6N5FH7.js";import{A as rt,B as ot,C as st,D as it,b as Fe,d as Ge,e as q,j as je,k as We,m as Be,n as Je,o as Ve,p as ze,q as Ye,r as qe,t as Xe,u as Q,v as Qe,w as Ze,x as et,y as tt,z as nt}from"./chunk-LOPBORFM.js";import{a as He}from"./chunk-3JWYIKHM.js";import{a as dt,b as ut,c as ft}from"./chunk-PAYCMH5F.js";import{a as at}from"./chunk-GQTWIDJ6.js";import{l as Ke,m as X}from"./chunk-ITPXS7D4.js";import{a as $e}from"./chunk-EV4DZCHN.js";import{b as xe,d as we}from"./chunk-ETX6IX25.js";import{e as De,j as Y,n as Me,o as be}from"./chunk-6K7NOPD5.js";import{c as E}from"./chunk-YSFSRI3D.js";E();import{Counter as H,Gauge as Z,Histogram as ee,Registry as Gt,collectDefaultMetrics as jt}from"@prometheus-io/client";import{createServer as Wt}from"http";var Pr=9464,pt="/metrics",te="(other)",Kt="(none)",Bt=64,Jt=128,Vt=["/v1/responses","/v1/chat/completions","/v1/systemone","/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",Xe,Ze,De],zt=new Set(Vt);function Yt(e){return zt.has(e)?e:te}function qt(e){return e===null?"none":e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":e>=200?"2xx":"1xx"}var ne=class{constructor(t){this.max=t}max;admitted=new Set;overflows=0;of(t,n=!0){return t===null||t===""?Kt:this.admitted.has(t)?t:n?this.admitted.size>=this.max?(this.overflows+=1,te):(this.admitted.add(t),t):te}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},re=class{registry=new Gt;modelLabel=new ne(Bt);orgLabel=new ne(Jt);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(t={}){this.buildInfo=new Z({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 H({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 ee({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 ee({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 H({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 H({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 H({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 et)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Z({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"},tt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},nt()/1e3)}}),this.labelCardinality=new Z({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 H({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 Z({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 ee({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 ee({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 H({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 H({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]}),t.defaultMetrics!==!1&&jt({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(t){this.ledgerWrites.inc({outcome:t.outcome,reason:t.reason})}observeLaneReady(t,n){this.lanesReady.set({model:this.modelLabel.of(t)},n)}observeLanePick(t,n){this.lanePickMs.observe({model:this.modelLabel.of(t)},n)}observeLaneFirstEvent(t,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(t)},n)}observeLane503Fast(t){this.lane503Fast.inc({model:this.modelLabel.of(t)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(t){let n=Yt(t.path),r=t.status!==null&&!(t.status>=400&&t.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(t.model,r),i=this.orgLabel.of(t.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 d=t.stream===!0?"true":"false";this.requests.inc({lane:n,method:t.method===""?te:t.method,status_class:qt(t.status),stream:d,model:s,org:i}),this.duration.observe({lane:n,stream:d,model:s,org:i},t.duration_ms/1e3),t.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},t.ttft_ms/1e3),t.stream_error&&this.streamErrors.inc({lane:n,model:s}),t.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function gt(e){return Wt((t,n)=>{(async()=>{let r=(t.url??"/").split("?")[0];if(t.method!=="GET"||r!==pt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${t.method} ${r} \u2014 this port serves only GET ${pt}
|
|
2
2
|
`);return}let o=await e.scrape();n.writeHead(200,{"content-type":e.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()})})}E();import{createHash as mt}from"crypto";import{createServer as Xt}from"http";var $r=9465,Qt="x-urun-key-id",Zt="x-urun-key-fingerprint",en="urun-ratelimit-bucket:",tn="urun-ratelimit-tier:",ht="anonymous",nn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function rn(e){return mt("sha256").update(`${en}${e}`).digest("hex")}function on(e){return mt("sha256").update(`${tn}${e}`).digest("hex")}function sn(e){let t=/^Bearer[ \t]+(\S.*)$/i.exec((e??"").trim());if(!t)return null;let n=t[1].trim();return nn.test(n)?n:null}function yt(){return Xt((e,t)=>{let n=sn(e.headers.authorization);t.setHeader(Qt,n===null?ht:rn(n)),t.setHeader(Zt,n===null?ht:on(n)),t.writeHead(200),t.end()})}E();import{createClientToken as an,ClientTokenError as ln}from"@urun-sh/core";import{createPublicKey as cn,verify as dn}from"crypto";var wt="urun-session-gateway",un="machine",fn=3e5;function pn(e){let t=e.split(".");return t.length===3&&t[0]!==""&&t[1]!==""&&t[2]!==""}var N=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},J=class extends Error{status=402;code;constructor(t){super(t==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":t==="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=t}},$=class extends Error{detail;constructor(t,n){super(t),this.name="ControlPlaneUnavailableError",this.detail=n}};function ie(e){let t=(e??"").trim();if(t==="")throw new N("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(t);if(!n)throw new N("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var gn=60,hn=6e4,mn=4096;function yn(e){return e===401||e===403}var oe=class{constructor(t){this.opts=t;this.mint=t.mint??an,this.now=t.now??Date.now}opts;cache=new Map;mint;now;async resolve(t){if(t==="")throw new N("empty Authorization bearer token");let n=this.cache.get(t);if(n&&this.now()-n.at<hn)return{apiKey:t,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(t,{baseUrl:this.opts.gatewayUrl,expiresIn:gn});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 ln&&yn(s.status)?(this.cache.delete(t),new N("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new $("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 $("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>=mn){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(t,{orgId:r,at:this.now(),...o}),{apiKey:t,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function bt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}var se=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch,this.now=t.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(t){if(!t&&this.jwks!==null&&this.now()-this.jwks.at<fn)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 $("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 $("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 $("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 $?i:new $("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(t){let[n,r,o]=t.split(".");if(n===void 0||r===void 0||o===void 0)throw new N("malformed machine token");let s,i;try{s=bt(n),i=bt(r)}catch{throw new N("malformed machine token")}if(s.alg!=="RS256")throw new N(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",d=typeof i.iss=="string"?i.iss:"";if(d===""||!this.opts.issuers.includes(d))throw new N(`machine token issuer is not one this endpoint accepts (${JSON.stringify(d)})`);if(i.aud!==wt)throw new N(`machine token audience must be ${wt} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==un)throw new N(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let c=typeof i.org_id=="string"?i.org_id:"";if(c==="")throw new N("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 N("machine token is expired \u2014 re-mint and retry");let y=u=>u.kty==="RSA"&&u.n!==void 0&&u.e!==void 0,l=await this.jwksKeys(!1),m=a===""?void 0:l.find(u=>u.kid===a&&y(u));if(m===void 0&&(l=await this.jwksKeys(!0),m=a===""?void 0:l.find(u=>u.kid===a&&y(u))),m===void 0)throw new N(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let k=Buffer.from(`${n}.${r}`,"ascii"),S=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),C=!1;try{let u=cn({key:m,format:"jwk"});C=dn("RSA-SHA256",k,u,S)}catch{C=!1}if(!C)throw new N("machine token signature failed verification");return{apiKey:t,orgId:c,credential:"machine"}}};function Se(e,t,n){return n!==null&&pn(e)?n.verify(e):t.resolve(e)}E();var wn=8080,ke="serve",Kr="0.0.0.0";function bn(e,t,n){let r=(e[t]??"").trim();if(!r)throw new Error(`${t} is not set \u2014 ${n}`);return r}function Br(e=process.env){let t=(e.PORT??"").trim(),n=t===""?wn:Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(t)}`);let r=Ke(X(bn(e,"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=(e.URUN_API_URL??"").trim(),s=o?X(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(e.URUN_CATALOG_URL??"").trim(),a=(e.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 d=i?{catalogUrl:X(i,"URUN_CATALOG_URL"),anonKey:a}:null,c=(e.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(e.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!f)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 y=c?{keyId:f,key:c}:void 0,l={docHostUrl:(e.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(e.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(e.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(e.URUN_LANE_SELF_ADDRESS??"").trim()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],k=m.filter((h,A)=>Object.values(l)[A]==="");if(k.length!==0&&k.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${k.join(", ")}, which would half-configure the lane plane`);let S=k.length===0?l:void 0,C={baseUrl:(e.URUN_POOLER_URL??"").trim(),token:(e.URUN_POOLER_TOKEN??"").trim(),region:(e.URUN_POOLER_REGION??"").trim()},u=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=u.filter((h,A)=>Object.values(C)[A]==="");if(g.length!==0&&g.length!==u.length)throw new Error(`${u.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let _=g.length===0?C:void 0,R={jwksBaseUrl:(e.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(e.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(e.URUN_MACHINE_TOKEN_TTL_S??"").trim()},v=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],P=v.filter((h,A)=>Object.values(R)[A]==="");if(P.length!==0&&P.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${P.join(", ")}, which would half-configure the machine-identity rung`);let p=R.issuers.split(",").map(h=>h.trim()).filter(h=>h!=="");if(p.length===0&&P.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 w=Number(R.tokenTtlS);if(P.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(R.tokenTtlS)}`);let b=P.length===0?{jwksBaseUrl:R.jwksBaseUrl,issuers:p,tokenTtlS:w}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:d,ledgerSigning:y,lane:S,pooler:_,machine:b}}E();import{createHash as Ln,randomUUID as kt}from"crypto";E();import{request as _n}from"http";var vn="/pooler/v1/inference",F=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},Sn=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(n=>n.role==="system"||n.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},kn=e=>{let t=e.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let n=e.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)}},vt=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r).toString("utf8"))),e.on("error",n)}),Rn=async e=>{let t="pooler_error",n=`the pooler refused the request (HTTP ${e.status})`;try{let r=JSON.parse(await vt(e.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"&&(t=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new F(e.status,t,n,e.retryAfterSeconds)};async function En(e,t,n,r,o){let s=new URL(`${e.baseUrl.replace(/\/+$/,"")}${vn}`),i=JSON.stringify({region:e.region,model:r,request_id:n,streaming:o,payload:t,affinity:{systemPrompt:Sn(t),firstMessage:kn(t)}});return new Promise((a,d)=>{let c=_n({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},f=>{let y=Number(f.headers["retry-after"]??"");a({status:f.statusCode??0,retryAfterSeconds:Number.isFinite(y)?y:void 0,body:f})});c.on("error",f=>d(new F(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`))),c.end(i)})}var _t=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let n;try{n=JSON.parse(t)}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*Cn(e){let t="";for await(let r of e.body)for(t+=String(r);;){let o=t.indexOf(`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.
|
|
1
|
+
import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.35";var y=4141,R=g,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
|
|
2
2
|
`)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
3
|
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ie(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
4
4
|
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Mn,c as Ln,d as Ce,e as kt,f as ee,g as $n,h as Fn,i as Dn,j as Nn,k as qn,l as Un,m as Bn,n as jn,r as Hn,t as Gn,u as Jn,v as Wn,w as Vn,x as zn}from"./chunk-3JWYIKHM.js";import{a as Yt}from"./chunk-6M5JK4YC.js";import{s as Ae}from"./chunk-CY4RJOTS.js";import{a as Pn,e as st,f as Cn,i as q,j as Y}from"./chunk-6K7NOPD5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as _s}from"crypto";import{WebSocketServer as ws}from"ws";var vs=256,St=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>vs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},bs="local",it=n=>n.slice(0,120),Rt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof q){this.ws.close(Ln,it(e.message));return}if(e instanceof Y){this.ws.close(kt,it(e.message));return}if(e instanceof ee){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(Ce,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=$n(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new ee(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=jn(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Gn(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:Hn);return}this.transcript.push(...Jn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new ee("setup may only be sent once, as the first client message");let t=qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new ee("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",kt);if(i.model!==t.model)throw new ee(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new ee("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new ee(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,kt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Nn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Fn]=Dn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new ee("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new ee("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ce);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Vn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new ee("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new ee("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ce);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new ee(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new ee("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new ee("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=_s();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Un(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Bn(e.timeLeftMs)),this.ws.close(Ce,it(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new ee(`upstream error: ${JSON.stringify(l)}`,Ce);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=Wn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new ee("upstream produced no response.completed event",Ce);let{messages:o,assistantItems:a}=zn(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Me=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function xs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new Me(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new Me(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new Me(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Kn(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ws({noServer:!0}),s=new St;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Mn&&(a.on("error",()=>{}),(async()=>{let d=xs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Me(401,"invalid local proxy api key");c={clients:e.clients,scope:bs}}r.handleUpgrade(o,a,u,p=>{new Rt(p,c,s)})})().catch(d=>{let c=502;(d instanceof Me||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",y=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
|
|
1
|
+
import{a as Mn,c as Ln,d as Ce,e as kt,f as ee,g as $n,h as Fn,i as Dn,j as Nn,k as qn,l as Un,m as Bn,n as jn,r as Hn,t as Gn,u as Jn,v as Wn,w as Vn,x as zn}from"./chunk-3JWYIKHM.js";import{a as Yt}from"./chunk-6M5JK4YC.js";import{s as Ae}from"./chunk-ITPXS7D4.js";import{a as Pn,e as st,f as Cn,i as q,j as Y}from"./chunk-6K7NOPD5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as _s}from"crypto";import{WebSocketServer as ws}from"ws";var vs=256,St=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>vs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},bs="local",it=n=>n.slice(0,120),Rt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof q){this.ws.close(Ln,it(e.message));return}if(e instanceof Y){this.ws.close(kt,it(e.message));return}if(e instanceof ee){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(Ce,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=$n(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new ee(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=jn(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Gn(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:Hn);return}this.transcript.push(...Jn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new ee("setup may only be sent once, as the first client message");let t=qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new ee("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",kt);if(i.model!==t.model)throw new ee(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new ee("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new ee(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,kt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Nn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Fn]=Dn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new ee("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new ee("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ce);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Vn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new ee("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new ee("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ce);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new ee(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new ee("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new ee("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=_s();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Un(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Bn(e.timeLeftMs)),this.ws.close(Ce,it(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new ee(`upstream error: ${JSON.stringify(l)}`,Ce);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=Wn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new ee("upstream produced no response.completed event",Ce);let{messages:o,assistantItems:a}=zn(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Me=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function xs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new Me(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new Me(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new Me(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Kn(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ws({noServer:!0}),s=new St;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Mn&&(a.on("error",()=>{}),(async()=>{let d=xs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Me(401,"invalid local proxy api key");c={clients:e.clients,scope:bs}}r.handleUpgrade(o,a,u,p=>{new Rt(p,c,s)})})().catch(d=>{let c=502;(d instanceof Me||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",y=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
4
|
${y}\r
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as W}from"./chunk-CAR4AEQJ.js";import{f as Z,g as R,h as ee,i as ne}from"./chunk-
|
|
1
|
+
import{a as W}from"./chunk-CAR4AEQJ.js";import{f as Z,g as R,h as ee,i as ne}from"./chunk-LOPBORFM.js";import{c as B,f as H,g as j,p as G}from"./chunk-6M5JK4YC.js";import{a as oe,b as U}from"./chunk-GQTWIDJ6.js";import{a as F}from"./chunk-EV4DZCHN.js";import{b as V,c as q,d as K,g as J,j as D,k as X,l as N,m as Y,p as b,q as Q,r as z}from"./chunk-6K7NOPD5.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as C,createClientToken as ce,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Se,DEFAULT_WHEN_LIVE_TIMEOUT_MS as le,isWakingPhase as Pe,SessionFailedError as Ee}from"@urun-sh/core";A();import{SessionFailedError as me}from"@urun-sh/core";var M=2;function ge(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function we(e){let i=e?.type;return i==="response.completed"||i==="error"}function ie(e){return async function(a,d){let p=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=M;l++){let{app:w,entry:u,identity:h}=l===1?p:await e.sessionFor(a.model);d?.({sessionId:e.sessionIdOf?.(u)??null,identity:h});let s=!1,c=!1;try{let f=await e.createStream(u,a);for await(let g of f){if(we(g)&&(s=!0),ge(g)){if(l>1)continue}else c=!0;yield g}}catch(f){if(f instanceof me&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,u,f)}catch{}throw f}if(l<M&&!c){await e.evict(w,u);continue}throw f}if(s)return;if(l<M&&!c){await e.evict(w,u);continue}return}})()}}import{randomUUID as de}from"crypto";A();var ye="audio";var re=new WeakMap;function ae(e,i,a){let d=e.doc(ye),p=[],r=0,l=0;return{sessionId:i,appendInputAudio(w){let u=Buffer.from(w,"base64");if(u.byteLength===0||(p.push(u),r+=u.byteLength,r<4800))return;let h=Buffer.concat(p,r).toString("base64");if(p=[],r=0,a===void 0){let s=(re.get(e)??0)+1;re.set(e,s),d.set({frames:{[String(s%32)]:{s,pcm16:h}}})}else{let s=++l;d.set({frames:{[`${a}:${s%32}`]:{s,pcm16:h,c:a}}})}},onOutputAudio(){return()=>{}}}}var Oe=0,Ae=4,ve=4;function Je(e,i){let a=(l,w)=>{let u=(e[l]??"").trim();if(!u)return w;let h=Number.parseInt(u,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},d=(e.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let p=d?Number.parseInt(d,10):Oe;if(!Number.isInteger(p)||p<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=a("URUN_DECISION_POOL_MAX",Math.max(p,Ae));return{min:p,max:r,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",ve),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function Xe(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return R;let a=Number.parseInt(i,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function x(e,i,a,d){let p=e[a];if(typeof p!="function")throw new Error(`app "${i}" has no function "${a}" (set URUN_FUNCTION)`);let r=d?p(void 0,d):p();if(typeof r.end!="function")throw new Error(`app "${i}" function "${a}" returned a session without end()`);return r}function ue(e,i,a,d){let{baseUrl:p,orgId:r,auth:l}=e,w=i.fnName??e.fnName,u=e.sessionStartOptions?.(a),h=d||u||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...u,...d}:void 0,s=y=>({session:y,responses:new F(y),gone:oe(y,a)});if(l.lane==="jwt"){let y=C(i.appSlug,{baseUrl:p,orgId:r,jwt:l.jwt});return s(x(y,i.appSlug,w,h))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:k}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??de(),n=C(i.appSlug,{baseUrl:p,orgId:r,getAccessToken:async()=>(await ce(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(n,i.appSlug,w,h))}let{apiKey:c,gatewayUrl:f}=l,g=(typeof e.subject=="function"?e.subject():e.subject)??de(),S=C(i.appSlug,{baseUrl:p,orgId:r,getAccessToken:async()=>(await ce(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:g,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(S,i.appSlug,w,h))}function be(e){let i=e.session.id;if(typeof i!="string"||i.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return i}function fe(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,a=e.status.error?.code;return i===410||i===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Ie=new Set(["error","paused"]);function Ye(e){let{auth:i,catalog:a}=e,d=null,p=(l,w)=>{let u=ue(e,l,w);return e.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&e.onSessionOpen(w,u.session.id),u.gone.onGone(()=>{d?.evict(w,u)}),u},r=new z({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:p,closeSession:async l=>{if(l.gone.dispose(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:i.lane==="api-key"?()=>Y({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(a?()=>W(a):null),listPrices:a?()=>K(a):null,shared:i.lane==="api-key"?()=>q({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return V(l)}:null,sessionKey:be});return d=r,e.defaultApp!==null&&r.seed(e.defaultApp,p({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Qe(e,i){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",p=new Map,r=new Map,l=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
|
|
2
2
|
`)},u=(s,c)=>{let f=p.get(c);if(f)return f;let g=new Z({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:d,openSlot:async S=>{let y=ue(e,s,c,{concurrencyKey:S.concurrencyKey});return y.gone.onGone(()=>g.markSessionDead(y)),await L(y.session),w(`slot attached pool=${c} slot=${S.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async S=>{S.gone.dispose(),await S.session.end()},onDetach:(S,y)=>w(`slot detached pool=${c} slot=${S.concurrencyKey} reason=${y}`),terminalOpenFailure:S=>S instanceof Ee&&fe(S)});return r.set(c,{target:s,env:a}),p.set(c,g),g},h=async(s,c)=>{let f=r.get(c);if(f)try{let g=await i.poolTuningFor(s);u(s,c).retune({min:g?.min??f.env.min,max:g?.max??f.env.max,inFlightCap:g?.in_flight_cap??f.env.inFlightCap,idleGraceMs:g?.idle_grace_s!==void 0?g.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:g?.warm_wait_s!==void 0?g.warm_wait_s*1e3:void 0})}catch(g){w(`pool tuning refresh failed pool=${c} reason=${g instanceof Error?g.message:String(g)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await u(s,b(s)).boot()},async sessionFor(s){let c=await i.resolveTargetFor(s),f=b(c),g=u(c,f);await h(c,f);let S=await g.acquire({timeoutMs:g.requestWaitMs}),y=l.get(S.entry)??[];return y.push(S),l.set(S.entry,y),{app:f,entry:S.entry,identity:Q(c)}},async warmFor(s){let c=await i.resolveTargetFor(s);await u(c,b(c)).boot()},end(s){let c=l.get(s)?.shift();c&&(l.get(s)?.length===0&&l.delete(s),c.release())},evict(s){for(let c of p.values())c.evict(s)},markSessionDead(s){for(let c of p.values())c.markSessionDead(s)},reap(){for(let[s,{target:c}]of r)h(c,s).then(()=>{let f=p.get(s);f&&f.reap()})},async pingReady(s){for(let c of p.values())if(await c.pingReady(s))return!0;return!1},stats(){return[...p.entries()].map(([s,c])=>({poolKey:s,...c.stats()}))},async drain(s){await Promise.all([...p.values()].map(c=>c.drain({timeoutMs:s})))},async close(){await Promise.all([...p.values()].map(s=>s.close()))}}}function _e(e){return Pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le:Se:le}async function L(e,i){let a=e.whenLive;if(typeof a!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await a.call(e,{timeout:_e(e.phase),signal:i})}async function pe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function ze(e,i=j,a,d,p=R,r){let l=new WeakMap,w=new WeakMap,u=new WeakMap,h=new WeakMap,s=new WeakMap,c=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},f="lane",g=n=>{let o=N(n);if(!r||!o||o.app!==f)return null;let t=r.entryFor(o.key);if(!t)throw new D(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},S=async n=>g(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=l.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let m=await B(n.session,await i());return Object.assign(m,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=h.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:m=>t.appendInputAudio(m),onOutputAudio:m=>t.onOutputAudio(m),sessionId:c(n)}})(),h.set(n,o),o.catch(()=>{h.get(n)===o&&h.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(l.get(n)===void 0||E!==void 0&&E.waiting===0)&&await pe(n.session),_(t)}let m=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?m:new Promise((E,O)=>{let v=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),l.delete(n),h.delete(n),pe(n.session).catch(()=>{})),O(_(t))};t.addEventListener("abort",v,{once:!0});let $=()=>t.removeEventListener("abort",v);m.then(T=>{$(),E(T)},T=>{$(),O(T)})})};return{createResponse:ie({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return d?d.sessionFor(n):e.sessionFor(n)}:d?n=>d.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>c(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):d?d.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{fe(t)&&(r&&r.owns(o)?r.evict(o):d?d.markSessionDead(o):e.evict(n,o),a?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=ee(U(await n.responses.responses.create(o),n.gone),p);if(!d&&!r)return t;let m=n;return(async function*(){try{yield*t}catch(E){throw ne(E)&&(r&&r.owns(m)?r.evict(m):d&&(E instanceof D?d.markSessionDead(m):d.evict(m))),E}finally{r&&r.owns(m)?r.release(m):d?.end(m)}})()}catch(t){throw r&&r.owns(n)?r.release(n):d&&d.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let m=g(n);if(m)return ae(m.entry.session,m.laneId,t);let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await S(n);yield*J(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=H(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=u.get(o);return t||(t=G(o.session),u.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),m=c(t.entry);if(m===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return X(f,m)}}return(await e.handleFor(n)).handle},releaseSessionHandle:n=>{let o=N(n);if(!r||o?.app!==f)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let m=await S(n);await L(m.session);let P=t!==void 0&&g(n)?new F({...m.session,consumerId:t}):m.responses;return U(await P.responses.create(o),m.gone)},onSessionEnd:async(n,o)=>{let t=g(n);if(t)return t.entry.gone.onGone(O=>o({timeLeftMs:null,reason:O.message}));let{entry:m}=await e.sessionForHandle(n),P=m.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(O=>{if(E||!Ie.has(O.name))return;E=!0;let v=P.endsAt??null;o({timeLeftMs:v?Math.max(0,v.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}export{Je as a,Xe as b,Ye as c,Qe as d,ze as e};
|
package/dist/hosted/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-
|
|
2
|
+
import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-5VMB5HKE.js";import"../chunk-UO6N5FH7.js";import"../chunk-CAR4AEQJ.js";import"../chunk-LOPBORFM.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-PAYCMH5F.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-GQTWIDJ6.js";import{s as m,t as p}from"../chunk-ITPXS7D4.js";import"../chunk-EV4DZCHN.js";import"../chunk-ETX6IX25.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
|
|
3
3
|
`);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
|
|
4
4
|
`),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
|
|
5
5
|
`),o.exit(1)});
|
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-5VMB5HKE.js";import"../chunk-UO6N5FH7.js";import"../chunk-CAR4AEQJ.js";import"../chunk-LOPBORFM.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-PAYCMH5F.js";import"../chunk-GQTWIDJ6.js";import"../chunk-ITPXS7D4.js";import"../chunk-EV4DZCHN.js";import"../chunk-ETX6IX25.js";import"../chunk-7KRHHEKZ.js";import"../chunk-6K7NOPD5.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};
|