@urun-sh/openai 0.6.40 → 0.6.42

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.
@@ -1,4 +1,4 @@
1
- import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-PT5N7AY7.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-G5VRFFBE.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-BWYY4IPR.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}
1
+ import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-QNJKRB7Q.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-IFYB6QUQ.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-XKCWX72M.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
 
@@ -1,2 +1,2 @@
1
- import{a as Q}from"./chunk-CAR4AEQJ.js";import{f as re,g as U,h as ae,i as ce}from"./chunk-G5VRFFBE.js";import{c as J,f as M,g as X,p as z}from"./chunk-Z3QCHKJB.js";import{a as de,b as C}from"./chunk-L4QBHSVY.js";import{a as D}from"./chunk-4NMMWAKD.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as x,l as N,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-HPUX2H65.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as j,createClientToken as fe,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as me,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";A();import{SessionFailedError as he}from"@urun-sh/core";var V=2;function Se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function Pe(e){let s=e?.type;return s==="response.completed"||s==="error"}function le(e){return async function(a,p){let m=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=V;l++){let{app:w,entry:g,identity:S}=l===1?m:await e.sessionFor(a.model);p?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let i=!1,d=!1;try{let u=await e.createStream(g,a);for await(let f of u){if(Pe(f)&&(i=!0),Se(f)){if(l>1)continue}else d=!0;yield f}}catch(u){if(u instanceof he&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(l<V&&!d){await e.evict(w,g);continue}throw u}if(i)return;if(l<V&&!d){await e.evict(w,g);continue}return}})()}}import{randomUUID as ge}from"crypto";A();import{encodeStreamEnvelope as Ee}from"@urun-sh/core";var ve="audio";function pe(e){let s=e.streamEndpoint(ve);return{sessionId:e.id,appendInputAudio(a){let p=Buffer.from(a,"base64");p.byteLength!==0&&s.send(Ee(new Uint8Array(p)))},onOutputAudio(){return()=>{}}}}A();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function ue(e){let s=e.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(e,s){let a=(l,w)=>{let g=(e[l]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},p=(e.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let m=p?Number.parseInt(p,10):_e;if(!Number.isInteger(m)||m<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(m,ke));return{min:m,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,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 W(e,s,a,p){let m=e[a];if(typeof m!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?m(void 0,p):m();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function we(e,s,a,p){let{baseUrl:m,orgId:c,auth:l}=e,w=s.fnName??e.fnName,g=e.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new D(y),gone:de(y,a)});if(l.lane==="jwt"){let y=j(s.appSlug,{baseUrl:m,orgId:c,jwt:l.jwt});return i(W(y,s.appSlug,w,S))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:F}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??ge(),L=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:d,gatewayUrl:u}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ge(),h=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(d,{baseUrl:u,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:f,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function ye(e){let s=e.session.id;if(typeof s!="string"||s.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 s}function q(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(e){let{auth:s,catalog:a}=e,p=null,m=(l,w)=>{let g=we(e,l,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:m,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:s.lane==="api-key"?()=>oe({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:e.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:s.lane==="api-key"?()=>Z({apiUrl:e.apiUrl,apiKey:s.apiKey}):s.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return Y(l)}:null,sessionKey:ye});return p=c,e.defaultApp!==null&&c.seed(e.defaultApp,m({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),c}function cn(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",m=new Map,c=new Map,l=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
1
+ import{a as Q}from"./chunk-CAR4AEQJ.js";import{f as re,g as U,h as ae,i as ce}from"./chunk-IFYB6QUQ.js";import{c as J,f as M,g as X,p as z}from"./chunk-Z3QCHKJB.js";import{a as de,b as C}from"./chunk-L4QBHSVY.js";import{a as D}from"./chunk-4NMMWAKD.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as x,l as N,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-HPUX2H65.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as j,createClientToken as fe,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as me,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";A();import{SessionFailedError as he}from"@urun-sh/core";var V=2;function Se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function Pe(e){let s=e?.type;return s==="response.completed"||s==="error"}function le(e){return async function(a,p){let m=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=V;l++){let{app:w,entry:g,identity:S}=l===1?m:await e.sessionFor(a.model);p?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let i=!1,d=!1;try{let u=await e.createStream(g,a);for await(let f of u){if(Pe(f)&&(i=!0),Se(f)){if(l>1)continue}else d=!0;yield f}}catch(u){if(u instanceof he&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(l<V&&!d){await e.evict(w,g);continue}throw u}if(i)return;if(l<V&&!d){await e.evict(w,g);continue}return}})()}}import{randomUUID as ge}from"crypto";A();import{encodeStreamEnvelope as Ee}from"@urun-sh/core";var ve="audio";function pe(e){let s=e.streamEndpoint(ve);return{sessionId:e.id,appendInputAudio(a){let p=Buffer.from(a,"base64");p.byteLength!==0&&s.send(Ee(new Uint8Array(p)))},onOutputAudio(){return()=>{}}}}A();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function ue(e){let s=e.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(e,s){let a=(l,w)=>{let g=(e[l]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},p=(e.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let m=p?Number.parseInt(p,10):_e;if(!Number.isInteger(m)||m<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(m,ke));return{min:m,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,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 W(e,s,a,p){let m=e[a];if(typeof m!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?m(void 0,p):m();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function we(e,s,a,p){let{baseUrl:m,orgId:c,auth:l}=e,w=s.fnName??e.fnName,g=e.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new D(y),gone:de(y,a)});if(l.lane==="jwt"){let y=j(s.appSlug,{baseUrl:m,orgId:c,jwt:l.jwt});return i(W(y,s.appSlug,w,S))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:F}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??ge(),L=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:d,gatewayUrl:u}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ge(),h=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(d,{baseUrl:u,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:f,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function ye(e){let s=e.session.id;if(typeof s!="string"||s.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 s}function q(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(e){let{auth:s,catalog:a}=e,p=null,m=(l,w)=>{let g=we(e,l,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:m,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:s.lane==="api-key"?()=>oe({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:e.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:s.lane==="api-key"?()=>Z({apiUrl:e.apiUrl,apiKey:s.apiKey}):s.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return Y(l)}:null,sessionKey:ye});return p=c,e.defaultApp!==null&&c.seed(e.defaultApp,m({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),c}function cn(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",m=new Map,c=new Map,l=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
2
2
  `)},g=(i,d)=>{let u=m.get(d);if(u)return u;let f=new re({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:p,openSlot:async h=>{let y=we(e,i,d,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>f.markSessionDead(y)),await T(y.session),w(`slot attached pool=${d} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${d} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof B&&q(h)});return c.set(d,{target:i,env:a}),m.set(d,f),f},S=async(i,d)=>{let u=c.get(d);if(u)try{let f=await s.poolTuningFor(i);g(i,d).retune({min:f?.min??u.env.min,max:f?.max??u.env.max,inFlightCap:f?.in_flight_cap??u.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){w(`pool tuning refresh failed pool=${d} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let i={appSlug:e.defaultApp};await g(i,b(i)).boot()},async sessionFor(i){let d=await s.resolveTargetFor(i),u=b(d),f=g(d,u);await S(d,u);let h=await f.acquire({timeoutMs:f.requestWaitMs}),y=l.get(h.entry)??[];return y.push(h),l.set(h.entry,y),{app:u,entry:h.entry,identity:se(d)}},async warmFor(i){let d=await s.resolveTargetFor(i);await g(d,b(d)).boot()},end(i){let d=l.get(i)?.shift();d&&(l.get(i)?.length===0&&l.delete(i),d.release())},evict(i){for(let d of m.values())d.evict(i)},markSessionDead(i){for(let d of m.values())d.markSessionDead(i)},reap(){for(let[i,{target:d}]of c)S(d,i).then(()=>{let u=m.get(i);u&&u.reap()})},async pingReady(i){for(let d of m.values())if(await d.pingReady(i))return!0;return!1},stats(){return[...m.entries()].map(([i,d])=>({poolKey:i,...d.stats()}))},async drain(i){await Promise.all([...m.values()].map(d=>d.drain({timeoutMs:i})))},async close(){await Promise.all([...m.values()].map(i=>i.close()))}}}function Re(e){return Le(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?me:Ie:me}async function T(e,s){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:Re(e.phase),signal:s})}async function G(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 k(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function dn(e,s=X,a,p,m=U,c){let l=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,i=new WeakMap,d=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",f=n=>{let o=N(n);if(!c||!o||o.app!==u)return null;let t=c.entryFor(o.key);if(!t)throw new _(`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}},h=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=l.get(n);if(!o){let t={waiting:0,gone:new AbortController};i.set(n,t),o=(async()=>{if(await T(n.session,t.gone.signal),t.gone.signal.aborted)throw k(t.gone.signal);i.get(n)===t&&i.delete(n);let r=await J(n.session,await s());return Object.assign(r,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{i.get(n)===t&&i.delete(n)},()=>{i.get(n)===t&&i.delete(n)})}return o},F=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:r=>t.appendInputAudio(r),onOutputAudio:r=>t.onOutputAudio(r),sessionId:d(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=i.get(n);throw(l.get(n)===void 0||E!==void 0&&E.waiting===0)&&await G(n.session),k(t)}let r=o(n),P=i.get(n);return P!==void 0&&P.waiting++,t===void 0?r:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&i.get(n)===P&&(P.gone.abort(),i.delete(n),l.delete(n),S.delete(n),G(n.session).catch(()=>{})),v(k(t))};t.addEventListener("abort",O,{once:!0});let K=()=>t.removeEventListener("abort",O);r.then(R=>{K(),E(R)},R=>{K(),v(R)})})},L=async(n,o,t)=>{try{return await t}catch(r){throw(r instanceof _||r instanceof B&&q(r))&&(e.evict(n,o),r instanceof B&&a?.(n,r.kind==="never-live"?"never-live":"create-failed")),r}};return{createResponse:le({sessionFor:c?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return p?p.sessionFor(n):e.sessionFor(n)}:p?n=>p.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>d(n),evict:(n,o)=>{c&&c.owns(o)?c.evict(o):p?p.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{q(t)&&(c&&c.owns(o)?c.evict(o):p?p.markSessionDead(o):e.evict(n,o),a?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await T(n.session);let t=ae(C(await n.responses.responses.create(o),n.gone),m);if(!p&&!c)return t;let r=n;return(async function*(){try{yield*t}catch(E){throw ce(E)&&(c&&c.owns(r)?c.evict(r):p&&(E instanceof _?p.markSessionDead(r):p.evict(r))),E}finally{c&&c.owns(r)?c.release(r):p?.end(r)}})()}catch(t){throw c&&c.owns(n)?c.release(n):p&&p.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{app:t,entry:r}=await e.sessionFor(n);return await L(t,r,I(r,y,o))},openAudioOn:async(n,o,t)=>{let r=f(n);if(r){let v=r.entry.session;return pe(v)}let{app:P,entry:E}=await e.sessionForHandle(n);return await L(P,E,I(E,F,o))},openTurnsOn:async function*(n,o){if(o?.aborted)throw k(o);let t=await h(n);yield*ne(t.session,o)},openVideoOn:async n=>{let o=f(n);if(o)return ue(o.entry.session);let{entry:t}=await e.sessionForHandle(n),r=w.get(t);return r||(r=M(t.session),w.set(t,r)),r},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=M(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=z(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(c){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o),r=d(t.entry);if(r===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(u,r)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:t,entry:r}=await e.dedicatedSessionFor(n);return x(t,ye(r))},releaseSessionHandle:n=>{let o=N(n);if(!o)return;if(o.app.startsWith(te)){(async()=>{let r=null;try{r=(await e.sessionForHandle(n)).entry}catch{return}await G(r.session).catch(()=>{}),await e.evict(o.app,r)})();return}if(!c||o.app!==u)return;let t=c.entryFor(o.key);t&&c.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 r=await h(n);await T(r.session);let P=t!==void 0&&f(n)?new D({...r.session,consumerId:t},{sessionTag:t}):r.responses;return C(await P.responses.create(o),r.gone)},onSessionEnd:async(n,o)=>{let t=f(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:r}=await e.sessionForHandle(n),P=r.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(v=>{if(E||!Fe.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{sn as a,rn as b,an as c,cn as d,dn as e};
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-HPUX2H65.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.40";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)}
1
+ import{h as m}from"./chunk-HPUX2H65.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.42";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}