@urun-sh/openai 0.6.33 → 0.6.34

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.
Files changed (39) hide show
  1. package/dist/chunk-2L7UL6BM.js +17 -0
  2. package/dist/chunk-6K7NOPD5.js +6 -0
  3. package/dist/chunk-7KRHHEKZ.js +1 -0
  4. package/dist/{chunk-GR3UAW6P.js → chunk-AVMTHHBR.js} +1 -1
  5. package/dist/{chunk-NL3UBLXV.js → chunk-CY4RJOTS.js} +2 -2
  6. package/dist/chunk-ETX6IX25.js +1 -0
  7. package/dist/{chunk-GL7EWL3V.js → chunk-EV4DZCHN.js} +1 -1
  8. package/dist/{chunk-L6HTHDVV.js → chunk-GQTWIDJ6.js} +1 -1
  9. package/dist/chunk-LDBKLCCU.js +2 -0
  10. package/dist/{composite-CwfOOT0b.d.cts → composite-DGytPb8F.d.cts} +10 -8
  11. package/dist/gemini-live.cjs +2 -2
  12. package/dist/gemini-live.d.cts +0 -26
  13. package/dist/gemini-live.d.ts +0 -5
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +44 -44
  16. package/dist/hosted/bin.js +1 -1
  17. package/dist/hosted/index.cjs +38 -38
  18. package/dist/hosted/index.d.cts +44 -1
  19. package/dist/hosted/index.d.ts +9 -1
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/pi-extension/index.cjs +7 -7
  24. package/dist/pi-extension/index.js +1 -1
  25. package/dist/pi-extension/standalone.cjs +40 -40
  26. package/dist/pooler/bin.cjs +24 -24
  27. package/dist/pooler/bin.js +23 -23
  28. package/dist/proxy/cli.cjs +37 -37
  29. package/dist/proxy/cli.js +1 -1
  30. package/dist/proxy/index.cjs +13 -13
  31. package/dist/proxy/index.d.cts +2 -2
  32. package/dist/proxy/index.d.ts +2 -2
  33. package/dist/proxy/index.js +1 -1
  34. package/package.json +2 -2
  35. package/dist/chunk-7D2HMQFC.js +0 -2
  36. package/dist/chunk-NN6TQQUG.js +0 -1
  37. package/dist/chunk-OOCRI7ZM.js +0 -6
  38. package/dist/chunk-PBKCUSTI.js +0 -17
  39. /package/dist/{composite-D9VDruCV.d.ts → composite-D4oZXeX4.d.ts} +0 -0
@@ -0,0 +1,17 @@
1
+ import{a as lt,c as _e,d as ct,e as ve}from"./chunk-LDBKLCCU.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-AVMTHHBR.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-CY4RJOTS.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
+ `);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
+ `);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
+
5
+ `);if(o===-1)break;let s=t.slice(0,o);t=t.slice(o+2);let i=_t(s);i!==null&&(yield i)}let n=_t(t);n!==null&&(yield n)}async function St(e,t,n,r){let o=xe(t,n,r),s=o.model??"";if(s==="")throw new F(400,"missing_model","the pooler submit requires a model");let i=await En(e,o,n,s,t.stream===!0);if(i.status>=400)throw await Rn(i);let a=t.stream===!0?we(n,Cn(i)):await An(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function An(e,t){let n=await vt(e.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new F(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return we(t,(async function*(){yield o})())}var Nn=512;function Re(e){return`urun-inference-proxy-${Ln("sha256").update(e).digest("hex").slice(0,32)}`}var ae=class{constructor(t){this.opts=t}opts;tenants=new Map;label(t,n){let r=Object.assign(Object.create(t),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${kt()}`;return St(o,s,a,a)}})}build(t){if(this.opts.build){let s=this.opts.build(t);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,t),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:t.orgId,defaultApp:null,fnName:ke,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:t.credential==="machine"?{lane:"machine",machineToken:t.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:t.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:lt(process.env,process.env.HOSTNAME)??void 0},r=_e(n),o=n.decisionPool?ct(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ve(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),t),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let t=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);t.unref(),this.decisionReaper=t}decisionReaper=null;clientsFor(t){let n=this.tenants.get(t.apiKey);if(n)return this.tenants.delete(t.apiKey),this.tenants.set(t.apiKey,n),n.clients;for(;this.tenants.size>=Nn;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(t);return this.tenants.set(t.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let t of this.tenants.values())t.decision&&(yield t.decision)}decisionWarmerFor(t){return this.clientsFor(t),this.tenants.get(t.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let t=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(t.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Rt=512,Tn=1024,le=class extends Error{constructor(){super(`conversation capacity reached (${Rt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Pn(e){return{sessionStartOptions:t=>{if(t.startsWith(be))return;let n=e.get(t);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(t,n)=>{t.startsWith(be)||e.set(t,n)}}}function On(e,t,n,r){let o=_e({baseUrl:e.baseUrl,orgId:t.orgId,defaultApp:null,fnName:ke,sharedOnlyListing:!0,apiUrl:e.apiUrl,auth:t.credential==="machine"?{lane:"machine",machineToken:t.apiKey,gatewayUrl:e.baseUrl}:{lane:"api-key",apiKey:t.apiKey,gatewayUrl:e.baseUrl},catalog:e.catalogRows?null:e.catalog,catalogRows:e.catalogRows,lanes:e.lanes,subject:n.subject,release:"detach",...Pn(r)});return{clients:ve(o,void 0,void 0,void 0,void 0,e.lanes),release:async()=>{await o.closeAll()}}}var ce=class{constructor(t){this.opts=t}opts;byCaller=new Map;byHandle=new Map;build(t,n){let r={id:n,subject:`${Re(t.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(t,r):On(this.opts,t,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(t,n){let r=this.byCaller.get(t.apiKey);r===void 0&&(r=new Map,this.byCaller.set(t.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(t,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let t=0;for(let n of this.byCaller.values())t+=n.size;return t}evictOverflow(){for(;this.conversationCount>=Rt;){let t=this.byCaller.keys().next();if(t.done)throw new le;let n=t.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new le;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(t,n){for(let[r,o]of this.byHandle)o.apiKey===t&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(t){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(t,kt())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,d)=>o().backhaul.clients.createResponseOn(i,a,d),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let d=o().backhaul.clients.openAudio;if(d===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return d(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async(i,a,d)=>{let c=o().backhaul.clients.openAudioOn;if(c===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return c(i,a,d)},s.openTurnsOn=(i,a)=>{let d=o().backhaul.clients.openTurnsOn;if(d===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return d(i,a)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},s.supportsTranscription=async i=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(i)},s.transcriptStreamFor=async i=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Tn;){let d=this.byHandle.keys().next();if(d.done)break;this.byHandle.delete(d.value)}this.byHandle.set(i,{apiKey:t.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),d=a===void 0?void 0:this.byCaller.get(a.apiKey),c=a===void 0||d===void 0?void 0:d.get(a.conversationId);if(a===void 0||c===void 0||a.apiKey!==t.apiKey)throw new Y("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let t=[];for(let r of this.byCaller.values())for(let o of r.values())t.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(t.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};E();var Un="/inference-ledger",In=1e4,de=class extends Error{ledgerFailureReason;constructor(t,n="duplicate"){super(t),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Ae=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},T=class extends Error{ledgerFailureReason="surface";constructor(t){super(t),this.name="LedgerSurfaceError"}},Le=class extends N{ledgerFailureReason="auth";constructor(t){super(t),this.name="LedgerAuthError"}},Ne=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(t){super(t),this.name="LedgerSignatureError"}},xn=[["inference_id",e=>typeof e=="string"&&/[^\s]/.test(e)],["model_id",e=>typeof e=="string"&&/[^\s]/.test(e)],["variant",e=>e===null||typeof e=="string"],["task",e=>typeof e=="string"&&/[^\s]/.test(e)],["http_status",e=>typeof e=="number"&&Number.isInteger(e)],["started_at",e=>typeof e=="string"&&!Number.isNaN(Date.parse(e))],["completed_at",e=>typeof e=="string"&&!Number.isNaN(Date.parse(e))],["prompt_tokens",e=>e===null||typeof e=="number"&&Number.isInteger(e)],["completion_tokens",e=>e===null||typeof e=="number"&&Number.isInteger(e)],["output_units",Ee],["output_minutes",Ee],["cost_nano_usd",Ee],["price_version",e=>e===null||typeof e=="string"]];function $n(e){for(let[t,n]of xn){if(!(t in e))return`${t} (absent)`;if(!n(e[t]))return`${t} (${JSON.stringify(e[t])})`}return null}function Dn(e){let t;try{t=JSON.parse(e)}catch{return{status:"unavailable"}}if(t===null||typeof t!="object"||Array.isArray(t))return{status:"unavailable"};let n=t.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=t.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:$n(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ee(e){return e===null?!0:typeof e=="number"?Number.isFinite(e):typeof e!="string"?!1:/[^\s]/.test(e)&&Number.isFinite(Number(e))}function Ce(e,t){return e===null?t===null:t===null?!1:Number(t)===e}function Mn(e,t){return e===null?t===null:t===null?!1:Number(e.toFixed(9))===Number(t)}function Et(e,t){if(typeof t!="string")return!1;let n=Date.parse(e),r=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Hn(e,t){let n=t;return n.inference_id===e.inference_id&&n.model_id===e.model_id&&(n.variant??null)===e.variant&&n.task===e.task&&n.http_status===e.http_status&&Et(e.started_at,n.started_at)&&Et(e.completed_at,n.completed_at)&&Ce(e.prompt_tokens,n.prompt_tokens)&&Ce(e.completion_tokens,n.completion_tokens)&&Ce(e.output_units,n.output_units)&&Mn(e.output_minutes,n.output_minutes)}function Fn(e){let t=r=>String(r??null),n="session_seconds"in e?e.session_seconds:null;return["urun-ledger-write-v2",e.inference_id,e.model_id,t(e.variant),e.identity_kind,e.task,t(e.prompt_tokens),t(e.completion_tokens),t(e.output_units),t(e.output_minutes),t(e.output_seconds),t(n),e.started_at,e.completed_at].join(`
6
+ `)}async function Gn(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(t.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Fn(e)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:t.keyId}}function jn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new T(`${t} answered a "recorded" that is not an object: ${JSON.stringify(e)}`);let n=e,r=n.inference_id;if(typeof r!="string"||r==="")throw new T(`${t} answered a row with no inference_id: ${JSON.stringify(e)}`);if(!("cost_nano_usd"in n))throw new T(`${t} answered a row with no cost_nano_usd field: ${JSON.stringify(e)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new T(`${t} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=c=>{if(!(c in n))throw new T(`${t} answered a row with no ${c} field: ${JSON.stringify(e)}`);let f=n[c];if(f===null)return null;if(typeof f!="string")throw new T(`${t} answered a non-string ${c}: ${JSON.stringify(f)}`);if(!/[^\s]/.test(f))throw new T(`${t} answered a BLANK ${c} (${JSON.stringify(f)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return f},i=s("price_version"),a=s("unpriced_reason"),d=o!=null;if(d&&(i===null||a!==null))throw new T(`${t} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!d&&(i!==null||a===null))throw new T(`${t} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var ue=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async write(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Un}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Gn(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new T(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:o,signal:AbortSignal.timeout(In)})}catch(c){throw new T(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(s.status===409){let c=await s.text().catch(()=>""),f=Dn(c);throw f.status==="found"&&Hn(n,f.row)?new Ae(f.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):f.status==="not_in_this_org"?new de(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new de(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${f.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${c.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Le("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let c=await s.text().catch(y=>`<body unreadable: ${y instanceof Error?y.message:String(y)}>`),f;try{let y=JSON.parse(c);if(y!==null&&typeof y=="object"&&"error"in y){let l=y.error;l!==null&&typeof l=="object"&&"code"in l&&(f=l.code)}}catch{}throw f==="ledger_signature_invalid"?new Ne(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+c.slice(0,400)):new T(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${c.slice(0,400)}`)}let i;try{i=await s.json()}catch(c){throw new T(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let a=i?.recorded;if(a===void 0)throw new T(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let d=jn(a,`the uRun ledger surface at ${r}`);if(d.inference_id!==n.inference_id)throw new T(`the uRun ledger surface at ${r} answered for inference_id ${d.inference_id} when asked about ${n.inference_id}`);return d}};E();import{createServer as yr}from"http";E();import{createWebsocketDocConnector as Vn}from"@urun-sh/core/internal";import zn from"ws";E();import*as G from"yjs";import{SessionDocumentImpl as Wn}from"@urun-sh/core/internal";var Kn=3e4;function Bn(e){return(t,n,r)=>{let o=e(t);G.applyUpdate(n,G.encodeStateAsUpdate(o));let s=a=>G.applyUpdate(o,a),i=a=>G.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}async function*Jn(e,t){let n=[],r=!1,o=null,s="",i=0,a=c=>{if(!("responses"in c)||typeof c.responses!="object"||c.responses===null)return null;let f=c.responses;if(!(t in f))return null;let y=f[t];if(y===null||typeof y!="object"||!("error"in y))return{body:y,error:null};let l=y.error;return l===null?{body:y,error:null}:{body:y,error:l}},d=c=>{let f={};for(let[l,m]of Object.entries(c)){let k=m;f[l]=typeof k?.toJSON=="function"?k.toJSON():m}if("tokens"in f&&typeof f.tokens=="object"&&f.tokens!==null){let l=f.tokens[t];if(typeof l=="string"&&l.length>s.length)n.push({t:"delta",delta:l.slice(s.length)}),s=l;else if(l!==null&&typeof l=="object"){let m=l,k=Object.keys(m).map(S=>Number(S)).filter(S=>Number.isFinite(S)&&S>i).sort((S,C)=>S-C);for(let S of k){let C=m[String(S)];typeof C=="string"&&C.length>0&&(n.push({t:"delta",delta:C}),i=S)}}}let y=a(f);if(y!==null){y.error!==null?n.push({t:"error",body:y.error}):n.push({t:"response",body:y.body}),r=!0,o?.(),o=null;return}if("progress"in f&&typeof f.progress=="object"&&f.progress!==null){let l=f.progress[t];if(typeof l=="object"&&l!==null&&"state"in l&&l.state==="error"){let k="error"in l&&typeof l.error=="string"?l.error:"lane request failed";n.push({t:"error",body:{message:k}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(d(e.get()??{}),!r){let c=e.on("change",d);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(f=>{o=f})}}finally{c()}}for(;n.length>0;)yield n.shift()}function Te(e){let{laneId:t}=e,n=e.connector??(e.roomDoc?Bn(e.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${t} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new Wn(d,t,n),r.set(d,c)),c},i=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);let f=d.slice(c.length);return{messages:()=>Jn(s("llm"),f),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:t,sessionId:t,consumerId:e.consumerId??`lane-${t}`,doc(d){return s(d)},stream:i,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??e.whenLiveTimeoutMs??Kn;await new Promise((y,l)=>{let m=setTimeout(()=>{k(),l(new Error(`lane ${t} llm doc never synced within ${f}ms`))},f),k=c.onSynced(()=>{clearTimeout(m),d?.signal?.removeEventListener("abort",S),y()}),S=()=>{clearTimeout(m),k(),l(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",S,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear()}}}function Yn(e){let t=(e.gpuSpec??"").split(":")[0];if(typeof e.appId!="string"||e.appId==="")throw new Ge(`the shared lane target (app slug "${e.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${t}.${e.appId}.${e.fnName??""}`}function Ct(e){let t=e.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(l,m,k,S,C)=>{let u=k?Te({laneId:l,roomDoc:R=>e.roomDoc(l,R)}):Te({laneId:l,connector:Vn({serverUrl:`ws://${S}/doc`,sessionId:l,token:()=>ut(l,e.tokenSecret,void 0,void 0,C),WebSocketPolyfill:zn})}),g=k?a(l):at(u,`lane:${l}`,{armOnFirstSync:!0}),_={session:u,responses:new $e(u),gone:g,goneWatch:g,laneId:l,pool:m,inFlight:0,laneSession:u,self:k,host:S??""};return n.set(l,_),g.onGone(()=>d(_)),_},a=l=>{let m=null,k=!1,S=new Set,C=g=>{if(!m){m=g;for(let _ of[...S])_(g);S.clear()}},u=e.hostedSignal?.(l,g=>{if(g){k=!0;return}k&&C(new Y(`the lane ${l} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>m,onGone(g){return m?(g(m),()=>{}):(S.add(g),()=>S.delete(g))},dispose(){u?.(),S.clear()}}},d=l=>{c(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose())},c=l=>{let m=l.laneId;return typeof m=="string"&&n.get(m)===l},f=(l,m)=>{throw e.metrics?.observeLane503Fast(m??""),s.set(l,t()),new q(l)},y=async(l,m)=>{let k=Yn(m);o.add(k);let S=t();try{let C=await e.laneWarmWaitMsFor?.(l,m)??e.laneColdWakeDefaultMs??0,u=await e.plane.pick({pool:k,model:l,holdMs:C});e.metrics?.observeLaneReady(l??"",u.length);let _=u.map(v=>({laneId:v.laneId,self:v.host===e.selfAddress,host:v.host})).sort((v,P)=>v.self!==P.self?v.self?-1:1:(r.get(v.laneId)??0)-(r.get(P.laneId)??0))[0];_||f(k,l);let R=n.get(_.laneId);return R?.goneWatch?.gone()&&(d(R),R=void 0),R&&(R.pool!==k||R.self!==_.self||R.host!==_.host)&&(d(R),R=void 0),R||(R=i(_.laneId,k,_.self,_.host,m.sharedOrgId??void 0)),R.inFlight+=1,r.set(_.laneId,(r.get(_.laneId)??0)+1),{app:k,entry:R,identity:{kind:"catalog",model_id:m.modelId??l??"",variant:m.variant??""}}}finally{e.metrics?.observeLanePick(l??"",t()-S)}};return{sessionFor(l,m){return y(l,m)},release(l){c(l)&&(l.inFlight=Math.max(0,l.inFlight-1),r.set(l.laneId,l.inFlight))},owns(l){return c(l)},entryFor(l){return n.get(l)??null},evict(l){c(l)&&(l.gone.dispose(),n.delete(l.laneId),r.set(l.laneId,0),l.laneSession.destroy())},async status(){let l=[...new Set([...o,...[...n.values()].map(S=>S.pool)])].sort(),m=await e.plane.status().catch(()=>[]),k=new Map(qn(m));return Promise.all(l.map(async S=>{let C=k.get(S)??{pool:S,lanes:[],lastDemandAt:null};return{pool:S,lanes:C.lanes,lastDemandAt:C.lastDemandAt,local:[...n.values()].filter(u=>u.pool===S).map(u=>({laneId:u.laneId,inFlight:u.inFlight,self:u.self,host:u.host})),lastRefusalAt:s.get(S)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await e.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function qn(e){return new Map(e.map(t=>[t.pool,{lanes:t.lanes,lastDemandAt:t.lastDemandAt}]))}E();import{request as Xn}from"http";var Qn="/pooler/v1/lanes/pick",Zn="/pooler/v1/lanes/status",er=1e4;function At(e,t,n,r,o){return new Promise((s,i)=>{let a=new URL(n,e.baseUrl),d=r===void 0?void 0:Buffer.from(JSON.stringify(r)),c=Xn({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:t,headers:{authorization:`Bearer ${e.token}`,...d===void 0?{}:{"content-type":"application/json","content-length":String(d.byteLength)}},timeout:o},f=>{let y=[];f.on("data",l=>y.push(l)),f.on("end",()=>{let l=Buffer.concat(y).toString("utf8"),m=null;try{m=l===""?null:JSON.parse(l)}catch{m=null}s({status:f.statusCode??0,json:m})}),f.on("error",i)});c.on("timeout",()=>{c.destroy(new Error(`pooler lane surface timed out after ${o}ms (${t} ${n})`))}),c.on("error",i),c.end(d)})}function Lt(e,t,n){if(e===503)return new q(n);let r=t!==null&&typeof t=="object"&&typeof t.error=="object"?JSON.stringify(t.error):`status ${e}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Nt(e){return{async pick({pool:t,model:n,holdMs:r=0}){let o=await At(e,"POST",Qn,{pool:t,model:n,hold_ms:r},r+er);if(o.status!==200)throw Lt(o.status,o.json,t);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let t=await At(e,"GET",Zn,void 0,5e3);if(t.status!==200)throw Lt(t.status,t.json,"");let n=t.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}E();import{WebSocketServer as fr}from"ws";E();import*as Pt from"yjs";import*as K from"y-protocols/sync";import*as D from"y-protocols/awareness";import*as L from"lib0/encoding";import*as B from"lib0/decoding";import*as Ot from"lib0/map";import nr from"lodash.debounce";E();var Tt=()=>{};var rr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,or=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,sr=0,ir=1;var ar=process.env.GC!=="false"&&process.env.GC!=="0",lr=process.env.YPERSISTENCE,fe=null;if(typeof lr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var W=new Map,pe=0,Oe=1,cr=(e,t,n)=>{let r=L.createEncoder();L.writeVarUint(r,pe),K.writeUpdate(r,e);let o=L.toUint8Array(r);n.conns.forEach((s,i)=>V(n,i,o))},Pe=class extends Pt.Doc{constructor(t){super({gc:ar}),this.name=t,this.conns=new Map,this.awareness=new D.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let f=this.conns.get(i);f!==void 0&&(r.forEach(y=>{f.add(y)}),s.forEach(y=>{f.delete(y)}))}let d=L.createEncoder();L.writeVarUint(d,Oe),L.writeVarUint8Array(d,D.encodeAwarenessUpdate(this.awareness,a));let c=L.toUint8Array(d);this.conns.forEach((f,y)=>{V(this,y,c)})};this.awareness.on("update",n),this.on("update",cr),!1}},Ue=(e,t=!0)=>Ot.setIfUndefined(W,e,()=>{let n=new Pe(e);return n.gc=t,fe!==null&&fe.bindState(e,n),W.set(e,n),n}),dr=(e,t,n)=>{try{let r=L.createEncoder(),o=B.createDecoder(n);switch(B.readVarUint(o)){case pe:L.writeVarUint(r,pe),K.readSyncMessage(o,r,t,e),L.length(r)>1&&V(t,e,L.toUint8Array(r));break;case Oe:{D.applyAwarenessUpdate(t.awareness,B.readVarUint8Array(o),e);break}}}catch(r){console.error(r),t.emit("error",[r])}},j=(e,t)=>{if(e.conns.has(t)){let n=e.conns.get(t);e.conns.delete(t),D.removeAwarenessStates(e.awareness,Array.from(n),null),e.conns.size===0&&fe!==null&&(fe.writeState(e.name,e).then(()=>{e.destroy()}),W.delete(e.name))}t.close()},V=(e,t,n)=>{t.readyState!==sr&&t.readyState!==ir&&j(e,t);try{t.send(n,r=>{r!=null&&j(e,t)})}catch{j(e,t)}},ur=3e4,Ut=(e,t,{docName:n=t.url.slice(1).split("?")[0],gc:r=!0}={})=>{e.binaryType="arraybuffer";let o=Ue(n,r);o.conns.set(e,new Set),e.on("message",a=>dr(e,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(e)&&j(o,e),clearInterval(i);else if(o.conns.has(e)){s=!1;try{e.ping()}catch{j(o,e),clearInterval(i)}}},ur);e.on("close",()=>{j(o,e),clearInterval(i)}),e.on("pong",()=>{s=!0});{let a=L.createEncoder();L.writeVarUint(a,pe),K.writeSyncStep1(a,o),V(o,e,L.toUint8Array(a));let d=o.awareness.getStates();if(d.size>0){let c=L.createEncoder();L.writeVarUint(c,Oe),L.writeVarUint8Array(c,D.encodeAwarenessUpdate(o.awareness,Array.from(d.keys()))),V(o,e,L.toUint8Array(c))}}};var Ie="/doc/",xt=30,pr=1e4,It="llm";function gr(e){if(!e.startsWith(Ie))return null;let t=e.slice(Ie.length),n=t.indexOf("/");return n<=0||n===t.length-1||t.includes("/",n+1)?null:{laneId:t.slice(0,n),docName:t.slice(n+1)}}function z(e,t,n){let r=t===401?"Unauthorized":t===403?"Forbidden":t===404?"Not Found":"Internal Server Error",o=`${n}\r
7
+ `;e.end(`HTTP/1.1 ${t} ${r}\r
8
+ Connection: close\r
9
+ Content-Type: text/plain; charset=utf-8\r
10
+ Content-Length: ${Buffer.byteLength(o)}\r
11
+ \r
12
+ ${o}`)}function $t(e,t){let n=new fr({noServer:!0}),r=new Set,o=new Map,s=new Map,i=u=>o.get(`${u}/${It}`)??0,a=u=>s.get(u)??0,d=new Map,c=new Map,f=new Set,y=new Set,l=!1,m=(u,g,_)=>{let R=i(u)>0,v=a(u),P=v>0,p=`${u}/${g}`,w=o.get(p)??0;_>0?o.set(p,_):o.delete(p);let b=v+_-w;b>0?s.set(u,b):s.delete(u);let h=i(u)>0,A=b>0;if(R!==h){h?k(u):S(u);for(let I of d.get(u)??[])I(h)}P&&!A&&queueMicrotask(()=>{let I=`${u}/`;for(let[x,M]of[...W.entries()])!x.startsWith(I)||M.conns.size>0||(W.delete(x),M.destroy())})},k=u=>{if(!t.hostRegistry||c.has(u))return;let g=()=>{t.hostRegistry?.setHost(u,t.selfAddress).catch(()=>{})};g();let _=setInterval(g,pr);_.unref?.(),c.set(u,_)},S=u=>{let g=c.get(u);g&&(clearInterval(g),c.delete(u)),t.hostRegistry&&t.hostRegistry.delHost(u,t.selfAddress).catch(()=>{})},C=(u,g,_)=>{let R;try{R=new URL(u.url??"/","http://localhost")}catch{z(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>y.delete(g));let v=gr(R.pathname);if(!v){if(R.pathname.startsWith(Ie)){z(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}y.add(g);return}f.add(g);let P=!1;(async()=>{let p=R.searchParams.get("token")??"",w=null;try{w=p===""?null:await t.verifyToken(p,v.laneId,v.docName)}catch{w=null}if(w===null){z(g,401,"invalid or missing lane doc token");return}let b=w;if(b.tenant!==void 0&&t.laneTenantOf){let h=null;try{h=await t.laneTenantOf(v.laneId)}catch{h=null}if(h==null||h==="")t.onLaneTenantMissing?.();else if(b.tenant!==h){z(g,403,"lane doc token org does not match the lane record");return}}l||g.destroyed||(P=!0,n.handleUpgrade(u,g,_,h=>{f.delete(g),r.add(h),h.on("close",()=>r.delete(h));let A=b.scope===dt||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(A){let x=`${v.laneId}/${v.docName}`,M=(o.get(x)??0)+1;m(v.laneId,v.docName,M),M>1&&v.docName===It&&t.hostRegistry?.setHost(v.laneId,t.selfAddress).catch(()=>{})}h.on("close",()=>{if(!A)return;let x=`${v.laneId}/${v.docName}`;m(v.laneId,v.docName,Math.max(0,(o.get(x)??1)-1))}),Ut(h,u,{docName:`${v.laneId}/${v.docName}`,gc:!0})}))})().catch(()=>{!P&&!g.destroyed&&z(g,500,"lane doc upgrade failed")}).finally(()=>f.delete(g))};return e.on("upgrade",C),{async close(){l=!0,e.off("upgrade",C);for(let g of[...c.keys()])S(g);await new Promise(g=>{if(r.size===0&&f.size===0){g();return}let _=r.size+f.size,R=()=>{_-=1,_<=0&&g()};for(let v of r)v.once("close",R);for(let v of f)v.once("close",R);for(let v of r)v.close(1001,"lane doc host shutting down");for(let v of f)v.destroy()}),o.clear(),s.clear(),d.clear()},roomDoc(u,g){return Ue(`${u}/${g}`,!0)},isHosted(u){return i(u)>0},onHostedChange(u,g){let _=d.get(u);return _||(_=new Set,d.set(u,_)),_.add(g),g(i(u)>0),()=>{_.delete(g)}}}}E();var hr="urun:catalog:v1";function Dt(e){let t=e.refreshMs??5e3,n=e.now??Date.now,r=null,o=0,s=null,i=async()=>{let d=await e.redis.hgetall(hr),c=[];for(let f of Object.values(d))try{c.push(JSON.parse(f))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
13
+ `)}return r=c,o=n(),c},a=()=>r===null||n()-o>=t;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}import wr from"ioredis";E();var ge="/inference-usage",Mt=25e3;var mr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ht(e){if(!(e instanceof Error))return`a ${typeof e}`;let t=mr.has(e.name)?e.name:"Error",n=e.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${t} (${n})`:t}var he=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async lookup(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ge}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Mt)})}catch(i){throw new Q(`the uRun usage surface (POST ${ge}) could not be reached within ${Mt}ms: ${Ht(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new N("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new Q(`the uRun usage surface (POST ${ge}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new Q(`the uRun usage surface (POST ${ge}) answered HTTP ${o.status} with a body that is not JSON: ${Ht(i)}`)}return Qe(s,this.opts.onRejectedRow)}};var br=5e3,_r=1e3,vr=1500,Sr=3e3,kr="/api/client-tokens";function me(e,t,n){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}function Ft(e,t,n,r){me(e,t,{error:{message:n,type:r}})}async function Rr(e,t=fetch){let n=`${e.replace(/\/+$/,"")}${kr}`;try{let r=await t(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Sr)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function fs(e){let t=e.resolver??new oe({gatewayUrl:e.baseUrl}),n=e.machine?new se({jwksBaseUrl:e.machine.jwksBaseUrl,issuers:e.machine.issuers}):null,r=new re(e.defaultMetrics===void 0?{}:{defaultMetrics:e.defaultMetrics}),o=null,s=(()=>{if(!e.lane)return null;if(!e.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let p=new wr(e.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),w=Dt({redis:p});return{registry:Ct({selfAddress:e.lane.selfAddress,tokenSecret:e.lane.tokenSecret,plane:Nt({baseUrl:e.pooler.baseUrl,token:e.pooler.token}),hostedSignal:(h,A)=>o?.onHostedChange(h,A)??(()=>()=>{}),roomDoc:(h,A)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(h,A)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(h,A)=>w.rows().then(I=>{let x=Me(I,A);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:w,redis:p}})(),i=e.registry??new ae({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:s?null:e.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:e.pooler}),a=e.probeControlPlane??(()=>Rr(e.baseUrl)),d=async()=>{let p=null;for(let h of i.decisionPools()){p=h;break}if(!p)return null;let w=p.stats();if(w.some(h=>h.draining))return{ok:!1,detail:"decision pool draining"};if(w.every(h=>h.attached===0&&h.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await p.pingReady(vr);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=e.usageClient??new he({apiUrl:e.apiUrl}),f=e.ledgerClient??new ue({apiUrl:e.apiUrl,...e.ledgerSigning?{signing:e.ledgerSigning}:{}}),y=process.env.URUN_SHARED_ORG_ID?.trim(),l=process.env.URUN_SHARED_ORG_API_KEY?.trim();y&&l&&(async()=>{try{await i.decisionWarmerFor({orgId:y,apiKey:l})?.warmFor(st)}catch(p){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(p instanceof Error?p.message:p)}
14
+ `)}})();let m=async p=>Se(ie(p.headers.authorization),t,n),k=async p=>{let w=await m(p);if(w.billingAudience==="platform"&&w.creditsAdmissionOk===!1){let b=w.creditsRefusalReason;throw new J(b==="spend_cap_reached"||b==="insufficient_credits"?b:void 0)}return w},S=p=>p instanceof N?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof J?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...p.code!==void 0?{code:p.code}:{}}:p instanceof $?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:p.detail}:null,C=it({clients:async p=>i.clientsFor(await k(p)),usage:{authorize:p=>ie(p.headers.authorization),lookup:(p,w)=>c.lookup(p,w)},statusOf:S,...e.requestLog?{requestLog:e.requestLog}:{},observe:p=>r.observe(p),ledger:{write:(p,w)=>f.write(ie(p.headers.authorization),w),observe:p=>r.observeLedger(p),...e.ledgerLog?{report:e.ledgerLog}:{}}}),u=null,g=null,_=yr((p,w)=>{let b=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&b.pathname==="/healthz"){me(w,200,{ok:!0});return}if(p.method==="GET"&&b.pathname==="/readyz"){let I=Date.now();if((!u||I-u.at>=br)&&(u={at:I,...await a()}),!g||I-g.at>=_r){let ye=await d();g=ye===null?{at:I,ok:!0,detail:null}:{at:I,ok:ye.ok,detail:ye.detail}}let x=(u?.ready??!1)&&g.ok,M=g.detail===null?u?.detail??"control plane not yet probed":`${u?.detail??"control plane not yet probed"}; ${g.detail}`;me(w,x?200:503,{ok:x,control_plane:M});return}if(p.method==="GET"&&b.pathname==="/lanez"){me(w,200,{pools:s?await s.registry.status():null});return}let h=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),A=b.pathname.startsWith("/partners/");if(!h&&!A){Ft(w,404,`no route for ${p.method} ${b.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}C(p,w)})().catch(h=>{if(!w.headersSent){Ft(w,500,String(h instanceof Error?h.message:h),"proxy_error");return}w.end()})}),R=e.conversations??new ce({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:s?null:e.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),v=[Fe(_,{authenticate:async p=>{let w=await Se(p,t,n),b=R.connectionFor(w);return{clients:b.clients,scope:Re(w.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),We(_,{clients:async p=>i.clientsFor(await k(p)),statusOf:S}).close,Je(_,{resolver:{resolve:async(p,w)=>{let b=await k(p),h=R.connectionFor(b),A;try{A=await qe(Ve(h.clients,e.realtimeCompanions),ze(p),w,Ye(p))}catch(x){throw h.release().catch(()=>{}),x}let I=A.release;return{...A,release:async()=>{await I?.(),await h.release()}}}}})];if(e.lane&&s){let p=e.lane,w=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=$t(_,{verifyToken:(h,A)=>ft(h,A,p.tokenSecret,void 0,w),selfAddress:p.selfAddress,laneTenantOf:h=>s.redis.get(`lane_tenant:${h}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:w,hostRegistry:{setHost:(h,A)=>s.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${h}`,A,String(xt)),delHost:h=>s.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${h}`,p.selfAddress)}});let b=s;v.push(async()=>{await o.close(),await b.registry.close(),b.redis.quit().catch(()=>{})})}_.on("upgrade",(p,w)=>{let b=new URL(p.url??"/","http://localhost");b.pathname===He||b.pathname===je||b.pathname===Be||o!==null&&b.pathname.startsWith("/doc/")||w.destroyed||(w.write(`HTTP/1.1 404 Not Found\r
15
+ Connection: close\r
16
+ \r
17
+ no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),w.destroy())});let P=async()=>{for(let p of v)await p();await R.detachAll()};return{server:_,metricsServer:gt(r),metrics:r,edgeIdentityServer:yt(),registry:i,closeAll:()=>i.closeAll(),closeWebSockets:P}}async function ps(e,t,n){n&&await n();let r=new Promise(o=>e.close(()=>o()));e.closeAllConnections(),await r,await rt()||ot(),await t()}export{Pr as a,pt as b,te as c,Kt as d,Bt as e,Jt as f,Yt as g,qt as h,ne as i,re as j,gt as k,$r as l,Qt as m,Zt as n,en as o,tn as p,ht as q,rn as r,on as s,sn as t,yt as u,N as v,$ as w,ie as x,hn as y,mn as z,oe as A,wn as B,ke as C,Kr as D,Br as E,Nn as F,Re as G,ae as H,Rt as I,Tn as J,le as K,ce as L,Un as M,In as N,de as O,T as P,jn as Q,ue as R,br as S,Sr as T,fs as U,ps as V};
@@ -0,0 +1,6 @@
1
+ import{c as w}from"./chunk-YSFSRI3D.js";w();w();var p=class extends Error{},_e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ve(n){if(typeof n!="string")return!1;let e=_e.exec(n);if(!e)return!1;let[,t,o,r,i,a,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let s=new Date(Date.UTC(t,o-1,r,i,a,d));return s.getUTCFullYear()===t&&s.getUTCMonth()===o-1&&s.getUTCDate()===r&&s.getUTCHours()===i&&s.getUTCMinutes()===a&&s.getUTCSeconds()===d}function Re(n){if(n===null||typeof n!="object")return null;let e=n.shared;if(e==null)return null;if(typeof e!="object")throw new p(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:t,endpoints:o,regions:r,compliance:i}=e;if(typeof t!="string"||t==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(o))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let a=o.map((d,s)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${s}] is not an object: ${JSON.stringify(d)}`);let l=d;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new p(`catalog shared endpoints[${s}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let u=(c,g)=>{if(l[c]!==void 0&&l[c]!==null&&!g)throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};u("ready",typeof l.ready=="boolean"),u("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),u("ready_since",ve(l.ready_since));for(let c of["model_id","variant"]){let g=l[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${s}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof l.output_free=="boolean"),l});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let s of Object.keys(d))if(s!=="zdr"&&s!=="hipaa")throw new p(`catalog "shared" block compliance carries "${s}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return a.length===0?null:{shared_org_id:t,endpoints:a,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(n){return[...n.endpoints].sort((e,t)=>e.model_id.localeCompare(t.model_id)||e.variant.localeCompare(t.variant))}function We(n){let e=n.filter(r=>typeof r.shared_org_id=="string"&&r.shared_org_id!=="");if(e.length===0)return null;let t=e[0].shared_org_id,o=e.map((r,i)=>{let a=d=>new p(`catalog rows[${i}] (${r.model_id}:${r.variant}) shared row is malformed: ${d}`);if(r.shared_org_id!==t)throw a(`shared_org_id ${JSON.stringify(r.shared_org_id)} disagrees with ${JSON.stringify(t)}`);for(let d of["model_id","variant"]){let s=r[d];if(typeof s!="string"||s===""||s.includes(":"))throw a(`"${d}" ${JSON.stringify(s)} is empty or contains ":"`)}if(typeof r.app_slug!="string"||r.app_slug==="")throw a("no app_slug");if(typeof r.function!="string"||r.function==="")throw a("no function");if(r.app_id!==void 0&&r.app_id!==null&&(typeof r.app_id!="string"||r.app_id===""))throw a(`malformed app_id ${JSON.stringify(r.app_id)}`);return{model_id:r.model_id,variant:r.variant,app_slug:r.app_slug,app_id:r.app_id??null,function:r.function,...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...r.warm!==void 0&&r.warm!==null?{warm:r.warm}:{},...r.compat_default===!0?{compat_default:!0}:{},...r.output_free===!0?{output_free:!0}:{},...r.ready!==void 0&&r.ready!==null?{ready:r.ready}:{},...r.ready_runtimes!==void 0&&r.ready_runtimes!==null?{ready_runtimes:r.ready_runtimes}:{},...r.ready_since?{ready_since:r.ready_since}:{}}});return{shared_org_id:t,endpoints:o}}function D(n,e,t){let o=(e??"").trim();if(o==="")return null;let r=o,i=t,a=o.lastIndexOf(":");a>0&&(r=o.slice(0,a),i=o.slice(a+1));let d=n.endpoints.filter(l=>l.model_id===r);if(d.length===0)return null;if(i!==void 0){let l=d.find(u=>u.variant===i);return l?{shared_org_id:n.shared_org_id,endpoint:l}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let s=d.filter(l=>l.compat_default===!0);if(s.length!==1)throw new p(`shared model "${r}" has ${s.length} compat_default rows (exactly one required) among variants ${d.map(l=>l.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:s[0]}}async function Ye(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${o.status}`);return Re(await o.json())}w();function h(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}w();var _=class extends Error{name="ModelPriceError"},j="per_million_input_tokens",U="per_million_output_tokens",Q="model_id,variant,unit,price_usd,effective_at,expires_at",Y={per_request:!0,per_minute:!0,per_output_unit:!0},be=5e3;function Se(n,e){let t=typeof n=="number"?n:typeof n=="string"&&n.trim()!==""?Number(n):NaN;if(!Number.isFinite(t)||t<0)throw new _(`${e}: price_usd is not a non-negative number (${JSON.stringify(n)})`);return t}function X(n,e,t){let o=typeof n=="string"?Date.parse(n):NaN;if(!Number.isFinite(o))throw new _(`${e}: ${t} is not a parseable timestamp (${JSON.stringify(n)})`);return o}function $e(n,e,t){return n===null?null:X(n,e,t)}function Te(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Y,n))return null;throw new _(`${e}: unit ${JSON.stringify(n)} is neither a per-token rate (${j} | ${U}) nor a known GPU-time unit (${Object.keys(Y).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function ke(n,e){let t=n.reduce((r,i)=>i.effective_at>r.effective_at?i:r,n[0]),o=n.find(r=>r.effective_at===t.effective_at&&r.usd!==t.usd);return o?{reason:`two ${e} rates are effective at the same instant (${t.usd} and ${o.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:t}}function J(n,e){return`${n}\0${e}`}function Pe(n){if(!Array.isArray(n))throw new _(`model_prices read is not an array: ${JSON.stringify(n)}`);let e=[];for(let t=0;t<n.length;t++){let o=n[t],r=`model_prices[${t}]`;if(o===null||typeof o!="object"||Array.isArray(o))throw new _(`${r} is not an object: ${JSON.stringify(o)}`);let i=o;for(let l of Q.split(","))if(!Object.hasOwn(i,l))throw new _(`${r} has no "${l}" column: ${JSON.stringify(i)}`);let a=Te(i.unit,r);if(a===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${r} has no model_id (${JSON.stringify(i)})`);let s=i.variant;if(!(s===null||typeof s=="string"&&s!==""))throw new _(`${r} has a non-string variant (${JSON.stringify(s)})`);e.push({model_id:d,variant:s,side:a,usd:Se(i.price_usd,r),effective_at:X(i.effective_at,r,"effective_at"),expires_at:$e(i.expires_at,r,"expires_at")})}return e}function Z(n,e=Date.now(),t){let o=new Map,r=new Map;for(let s of n){if(s.effective_at>e||s.expires_at!==null&&s.expires_at<=e)continue;let l=o.get(s.model_id);l||(l=new Map,o.set(s.model_id,l),r.set(s.model_id,new Map));let u=s.variant??"",c=l.get(u);c||(c={input:[],output:[]},l.set(u,c),r.get(s.model_id).set(u,s.variant)),c[s.side].push({effective_at:s.effective_at,usd:s.usd})}let i=[],a=[];for(let[s,l]of o){let u=l.get(""),c=(g,f,v)=>{let m=g&&g.length>0?g:u?.[f];if(!m||m.length===0)return null;let y=ke(m,f);return"reason"in y?y:y.rate.usd===0?f==="output"&&v!==null&&t?.has(J(s,v))?y.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[g,f]of r.get(s)){let v=l.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){a.push({model_id:s,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){a.push({model_id:s,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:s,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(s,l)=>s.model_id.localeCompare(l.model_id)||(s.variant===null?1:0)-(l.variant===null?1:0)||(s.variant??"").localeCompare(l.variant??"");return{prices:i.sort(d),refusals:a.sort(d)}}function A(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var E={prices:[],refusals:[]};async function tt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${Q}&unit=in.(${t})`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`},signal:AbortSignal.timeout(be)});if(!o.ok)throw new Error(`model_prices fetch failed: ${o.status}`);return Pe(await o.json())}w();var at="/partners/openrouter/models",xe={chat:!0,code:!0,agent:!0,vl:!0},ee={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ce(n){let e=n.toLowerCase();return Object.hasOwn(ee,e)?ee[e]:null}var te={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Ae(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(te,r)?te[r]:null;if(i===null){o.push(r);continue}t.some(d=>d.region===r)||t.push({country_code:i,region:r})}return o.length>0&&e(`urun openrouter doc: shared block region(s) ${o.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),t}var ne={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},re={2:"Llama2",3:"Llama3"};function Ee(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(ne,i))return ne[i];let a=o[r+1];if(i==="llama"&&a!==void 0&&Object.hasOwn(re,a))return re[a];if(i==="phi"&&a!==void 0&&/^\d/.test(a))return"Phi"}return null}var Oe=["context_length","max_model_len"];function Me(n){let e=Oe.map(t=>n.engine_args?.[t]).filter(t=>typeof t=="number"&&Number.isFinite(t)&&t>0);return e.length===0?null:e.every(t=>t===e[0])?e[0]:null}function N(n){let e=n.map(Me),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function Ie(n){let e=n.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function K(n){if(n.length===0)return null;let e=n.map(Ie),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function B(n,e){let t=e.filter(r=>r.serve_app_slug===n);return new Set(t.map(r=>r.model_id)).size===1?t:[]}function Ne(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return O(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return O(o);let r=B(n,e);return r.length>0?O(r):null}function O(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),a=Number(r[2]),d=Number(r[3]),s=Date.UTC(i,a-1,d),l=new Date(s);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==a-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return s/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function L(n,e,t){let o=Ne(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,a=N(i),d=T(i),s=A(r.model_id,r.variant,t),l=se(r,i),u=K(i);return b({id:n,object:"model",created:d,owned_by:"urun",...a!==null?{context_length:a}:{},...s!==null?{pricing:s}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var Fe=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function se(n,e){if((n.task??void 0)!=="tts")return{published:[],defect:null};let t=e.map(i=>i.engine_args?.voices),o=t[0];if(Array.isArray(o)&&o.length>0&&o.every(i=>typeof i=="string")&&t.every(i=>Array.isArray(i)&&i.length===o.length&&i.every((a,d)=>a===o[d])))return{published:[...o],defect:null};let r=t.some(i=>i!=null)?`the catalog's engine_args.voices for ${n.model_id}:${n.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return n.model_id==="qwen3-tts-customvoice"?{published:[...Fe],defect:r}:{published:[],defect:r}}function z(n){let e=n.length>0?O(n):null;return e===null?{published:[],defect:null}:se(e.row,e.matches)}function oe(n){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(n));if(!e)throw new Error(`unrenderable per-token price: ${String(n)}`);let[,t="",o="",r=""]=e,i=t+o,a=t.length-6+(r===""?0:Number(r));return(a<=0?`0.${"0".repeat(-a)}${i}`:`${i.slice(0,a)}.${i.slice(a).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function ie(n){return{input:[{type:"prompt",unit:"token",cost_usd:oe(n.input)}],output:[{type:"completion",unit:"token",cost_usd:oe(n.output)}]}}function De(n,e,t,o){if(e.length===0)return null;let r=O(e);if(!r)return null;let{row:i,matches:a}=r;if(!i.task||xe[i.task]!==!0)return null;let d=N(a),s=A(i.model_id,i.variant,t),l=Ee(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(a),quantization:Ce(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&s!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...s?{pricing:ie(s).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...s?{pricing:ie(s).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function ae(n,e,t,o){let r=o??(l=>console.warn(l.trimEnd())),i=n?S(n):[];if(i.length>0){let l=i.filter(u=>u.ready===void 0);if(l.length===i.length)r("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let u=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");r(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let a={datacenters:Ae(n?.regions,r),compliance:n?.compliance??null},d=[],s=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(s.has(u))continue;s.add(u);let c=De(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,a);c&&d.push(c)}return{data:d}}w();var le={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},k=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function de(n){let e=n.t;if(typeof e!="string"||!(e in le))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(le).join(", ")}`);let t={kind:e};return typeof n.delta=="string"&&(t.text=n.delta),typeof n.start_ms=="number"&&Number.isFinite(n.start_ms)&&(t.startMs=n.start_ms),t}function je(n){if(typeof n=="string"){let e;try{e=JSON.parse(n)}catch(t){throw new k(`the "stt" transcript lane delivered a string payload that is not valid JSON (${t instanceof Error?t.message:String(t)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new k(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return de(e)}if(n===null||typeof n!="object"||Array.isArray(n))throw new k(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(n)?"array":typeof n}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return de(n)}function ue(n){return n.reason instanceof Error?n.reason:new Error("the turn-lane consumer aborted")}async function Ue(n,e){return e.aborted?"aborted":await new Promise(t=>{let o=!1,r=a=>{o||(o=!0,e.removeEventListener("abort",i),t(a))},i=()=>r("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>r("pulled"),()=>r("pulled"))})}function ut(n,e){let t=n.stream("stt");if(typeof t.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*o(){let r=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ue(e);let i=r.next();if(e!==void 0&&await Ue(i,e)==="aborted")throw i.catch(()=>{}),ue(e);let a=await i;if(a.done)return;yield je(a.value)}}finally{let i=r.return?.();i&&i.catch(()=>{})}}return o()}var _t="https://api.urun.sh/v1",P=class extends Error{},I=class extends Error{},G="urs1.";function ce(n,e){return G+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function Ke(n){if(!n.startsWith(G))return null;try{let e=JSON.parse(Buffer.from(n.slice(G.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function vt(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function pe(n){if(n.length===0)return[];if(!n.every(t=>(t.task??void 0)==="image"))return[];let e=qe(n);return e===null?[]:[e]}function Be(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(n)}
2
+ `),null;let e={},t=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],o=!1;for(let[r,i]of t){let a=n[r];if(a==null)continue;let d=typeof a=="number"?a:typeof a=="string"?Number.parseInt(a,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(r)}=${JSON.stringify(a)})
3
+ `),o=!0;break}e[r]=d}return o||Object.keys(e).length===0?null:e}function ze(n,e){if(n.length===0)return null;let t;return e.modelId&&(t=n.find(o=>o.model_id===e.modelId&&(!e.variant||o.variant===e.variant))),t||(t=n.find(o=>o.serve_app_slug===e.appSlug||h(`${o.model_id}-${o.variant}`)===e.appSlug||h(o.model_id)===e.appSlug)),t?Be(t.engine_args?.pool):null}function H(n,e,t,o,r){if(!r)throw new p(`shared model "${n}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||t===void 0)throw new p(`shared model "${n}" resolved without a catalog id + variant to join on`);let i=o.filter(a=>a.model_id===e&&a.variant===t);if(i.length===0)throw new p(`shared model "${n}" names endpoint ${e}:${t} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function ge(n,e){if(!e.every(r=>(r.task??void 0)==="image"))return[];let t=e.map(r=>r.engine_args?.expects_image),o=t[0];if(typeof o!="boolean"||!t.every(r=>r===o))throw new p(`shared image model "${n}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(t)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[o===!1?"generation":"edit"]}var ye="shared:",fe="speech:";function q(n){return n.sharedApp?ye+n.appSlug:n.appSlug}function he(n){return typeof n.modelId=="string"&&typeof n.variant=="string"?{kind:"catalog",model_id:n.modelId,variant:n.variant}:{kind:"not-a-catalog-model",model:n.appSlug}}function V(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return t;let o=e.filter(i=>h(i.model_id)===n);return new Set(o.map(i=>i.variant)).size===1?o:[]}function He(n){let e=n.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function qe(n){let e=n.map(He),t=e[0];return t!=null&&e.every(o=>o===t)?t:null}var Ge={stt:"stt",tts:"tts"};function R(n){if(n.length===0)return null;let e=n[0].task??void 0,t=n.every(r=>(r.task??void 0)===e),o=e===void 0?void 0:Ge[e];return o!==void 0?t?o:null:t&&n.every(r=>r.engine_args?.realtime===!0)?"decision":null}function we(n,e){let t=V(n,e);return t.length>0?t:B(n,e)}function M(n,e){return we(n.appSlug,e)}function Ve(n){let e=n.map(o=>o.engine_args?.transcript_stream).filter(o=>o!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(o=>o===t))throw new p(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return t}var F=6e4,me=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??F):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??F):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??F):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??F;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
4
+ `),E}let o=Z(t,Date.now(),e);for(let r of o.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
5
+ `);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(ye)||r.startsWith(fe)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,a=r>0?e.slice(r+1):void 0,d=h(i),s=t.endpoints.filter(c=>h(c.model_id)===d&&(a===void 0||c.variant===a)),l=new Set(s.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,a)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let a=await this.deployedApps(),d=this.servable(a);if(d.includes(r))return{appSlug:r};let s=d.filter(u=>u.startsWith(`${r}-`));if(s.length===1)return{appSlug:s[0]};if(s.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${s.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=a.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(s=>t===s.model_id||t===`${s.model_id}:${s.variant}`||r===h(s.model_id)||r===h(`${s.model_id}-${s.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=he(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return ze(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,fe+q(t))}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:he(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async sessionForHandle(e){let t=Ke(e);if(!t)throw new I(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),a=i?await i.then(d=>d,()=>null):null;if(a===null)throw new I(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(a)!==r)throw new I(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:a}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,a=o.ok?r:E;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
6
+ `);let s=(t?S(t):[]).map(l=>{let u=i.filter(W=>W.model_id===l.model_id&&W.variant===l.variant),c=N(u),g=T(u),f=K(u),v=A(l.model_id,l.variant,a),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?s:[...e.map(l=>L(l,i,a)),...s]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ae(e,t,o,r=>this.warn(r))}async supportsImages(e,t){let o=await this.resolveTarget(e),r=await this.catalogRows();if(o.sharedApp){let i=H(String(e),o.modelId,o.variant,r,this.opts.listCatalog!==null);return ge(`${o.modelId}:${o.variant}`,i).includes(t)}return pe(V(o.appSlug,r)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))!==null:R(M(t,o))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="tts":R(M(t,o))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="stt":R(M(t,o))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return Ve(r)}async speechVoices(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds()){let a=pe(V(i,e));a.length!==0&&o.push(b({...L(i,e,t),image_modes:a}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=ge(`${i.model_id}:${i.variant}`,a);if(d.length===0)continue;let s=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun",image_modes:d});o.push(s)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(we(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(a)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,We as b,Ye as c,tt as d,at as e,$ as f,ut as g,_t as h,P as i,I as j,ce as k,Ke as l,vt as m,ze as n,fe as o,q as p,he as q,me as r};
@@ -0,0 +1 @@
1
+ import{c as r}from"./chunk-YSFSRI3D.js";r();async function d(e,t,o){if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((i,s)=>{let u=e.onSynced(()=>{clearTimeout(n),i()});n=setTimeout(()=>{u(),s(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${o} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}export{d as a};
@@ -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-NL3UBLXV.js";import{a as Pn,d as st,e as Cn,h as q,i as Y}from"./chunk-OOCRI7ZM.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-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
2
2
  Connection: close\r
3
3
  \r
4
4
  ${y}\r
@@ -1,6 +1,6 @@
1
- import{g as m}from"./chunk-OOCRI7ZM.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 f="0.6.33";var y=4141,R=f,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(p=>p==="-m"||p==="--model"||p.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),u=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...u]}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?g(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 u=(e.URUN_GATEWAY_URL??"").trim(),p=u?g(u):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:p}}}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 g(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-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.34";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}
5
5
  `)}catch(o){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
6
- `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function se(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}export{J as a,P as b,B as c,K as d,M as e,F as f,H as g,V as h,X as i,z as j,Q as k,N as l,g as m,Z as n,A as o,ee as p,te as q,ne as r,re as s,oe as t,ie as u,se as v};
6
+ `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function se(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}export{J as a,P as b,B as c,K as d,M as e,F as f,H as g,V as h,X as i,z as j,Q as k,N as l,f as m,Z as n,A as o,ee as p,te as q,ne as r,re as s,oe as t,ie as u,se as v};
@@ -0,0 +1 @@
1
+ import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var w="llm-resp";async function*v(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*l(e,t){let o=`${w}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*v(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var k=class{constructor(t,o=15e3){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),l(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),l(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,v as d,l as e,k as f};
@@ -1 +1 @@
1
- import{f as r}from"./chunk-NN6TQQUG.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(n){this.transport=new r(n)}responses={create:async n=>{let t=a(),i=await this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*i})(),{requestId:t})}}};export{o as a};
1
+ import{f as r}from"./chunk-ETX6IX25.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(n){this.transport=new r(n)}responses={create:async n=>{let t=a(),i=await this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*i})(),{requestId:t})}}};export{o as a};
@@ -1 +1 @@
1
- import{i as d}from"./chunk-OOCRI7ZM.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
1
+ import{j as d}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
@@ -0,0 +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-AVMTHHBR.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
+ `)},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};
@@ -1884,7 +1884,8 @@ interface LedgerRecorded {
1884
1884
  * Why the row carries no price, or null when it is priced. One of
1885
1885
  * `not_a_catalog_model` | `outcome_not_billable` | `http_status_not_success`
1886
1886
  * | `task_unit_undeclared` | `task_not_token_billed` | `token_counts_absent`
1887
- * | `output_minutes_absent` | `no_active_price` | `no_active_input_price` |
1887
+ * | `output_minutes_absent` | `output_units_absent` |
1888
+ * `session_seconds_absent` | `no_active_price` | `no_active_input_price` |
1888
1889
  * `no_active_output_price`.
1889
1890
  * It is a NORMAL answer, not an error: no PER-TOKEN rate has been seeded
1890
1891
  * yet, so this lane has nothing to price with. (Not "the price book is
@@ -1901,13 +1902,14 @@ interface LedgerRecorded {
1901
1902
  * TASK DECLARES (`public.task_billing_units`), never in the unit the data
1902
1903
  * happens to look like:
1903
1904
  *
1904
- * * `task_not_token_billed` — this lane's billable quantity is not tokens
1905
- * (an image lane's is {@link LedgerWrite.output_units}), so its token counts are not
1906
- * a price for it. A genuine `{0, 0}` receipt on such a lane would
1907
- * otherwise settle at `cost_nano_usd = 0` PERMANENTLY — the control
1908
- * plane's append-only rule allows a deliberate re-price and never a
1909
- * return to NULL — which is an invoice asserting the work was free when
1910
- * its billable quantity was never measured.
1905
+ * * `task_not_token_billed` — the task's declared billing unit has no
1906
+ * arithmetic rung in the writer (the CHECK vocabulary accepts units the
1907
+ * ladder does not price, e.g. `per_request`), so nothing is priced.
1908
+ * A genuine `{0, 0}` receipt on such a lane would otherwise settle at
1909
+ * `cost_nano_usd = 0` PERMANENTLY — the control plane's append-only
1910
+ * rule allows a deliberate re-price and never a return to NULL —
1911
+ * which is an invoice asserting the work was free when its billable
1912
+ * quantity was never measured.
1911
1913
  * * `task_unit_undeclared` — nobody has declared what this task bills in,
1912
1914
  * so nothing is priced. Adding a lane to {@link ledgerTaskOf} without a
1913
1915
  * matching declaration fails CLOSED and says which fix it wants.