@urun-sh/openai 0.6.32 → 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.
- package/dist/chunk-2L7UL6BM.js +17 -0
- package/dist/chunk-6K7NOPD5.js +6 -0
- package/dist/chunk-7KRHHEKZ.js +1 -0
- package/dist/{chunk-7OH7UJ2H.js → chunk-AVMTHHBR.js} +4 -4
- package/dist/{chunk-M3YMNU5P.js → chunk-CY4RJOTS.js} +2 -2
- package/dist/chunk-ETX6IX25.js +1 -0
- package/dist/{chunk-GL7EWL3V.js → chunk-EV4DZCHN.js} +1 -1
- package/dist/{chunk-L6HTHDVV.js → chunk-GQTWIDJ6.js} +1 -1
- package/dist/chunk-LDBKLCCU.js +2 -0
- package/dist/{composite-DMawda97.d.ts → composite-D4oZXeX4.d.ts} +2 -0
- package/dist/{composite-DtBebn0Y.d.cts → composite-DGytPb8F.d.cts} +13 -8
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +0 -26
- package/dist/gemini-live.d.ts +0 -5
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +46 -46
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +40 -40
- package/dist/hosted/index.d.cts +57 -13
- package/dist/hosted/index.d.ts +15 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +40 -40
- package/dist/pooler/bin.cjs +24 -24
- package/dist/pooler/bin.js +23 -23
- package/dist/proxy/cli.cjs +37 -37
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +20 -20
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-5473ZAQ4.js +0 -17
- package/dist/chunk-KTMDSM7F.js +0 -2
- package/dist/chunk-NN6TQQUG.js +0 -1
- package/dist/chunk-OOCRI7ZM.js +0 -6
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
|
-
import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-
|
|
2
|
+
import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-DGytPb8F.cjs';
|
|
3
|
+
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-DGytPb8F.cjs';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CO8W_hmJ.cjs';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.cjs';
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
|
-
import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-
|
|
2
|
+
import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-D4oZXeX4.js';
|
|
3
|
+
export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-D4oZXeX4.js';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-Ddd65sXR.js';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.js';
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-
|
|
1
|
+
import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-AVMTHHBR.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-CY4RJOTS.js";import{i as r,j as i}from"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.34",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.6.
|
|
73
|
+
"@urun-sh/core": "^0.6.34"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"@prometheus-io/client": "^0.16.1",
|
package/dist/chunk-5473ZAQ4.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{a as ot,c as ye,d as st,e as we}from"./chunk-KTMDSM7F.js";import{A as Ze,B as et,C as tt,D as nt,b as De,d as $e,e as q,j as He,k as Me,m as Ge,n as We,o as Ke,p as je,q as Be,r as Ve,t as ze,u as Q,v as Ye,w as Je,x as qe,y as Xe,z as Qe}from"./chunk-7OH7UJ2H.js";import{a as xe}from"./chunk-3JWYIKHM.js";import{a as it,b as at,c as lt}from"./chunk-PAYCMH5F.js";import{a as rt}from"./chunk-L6HTHDVV.js";import{l as Fe,m as X}from"./chunk-M3YMNU5P.js";import{a as Oe}from"./chunk-GL7EWL3V.js";import{b as Ne,d as he}from"./chunk-NN6TQQUG.js";import{d as Ie,i as J,m as Ue,n as me}from"./chunk-OOCRI7ZM.js";import{c as S}from"./chunk-YSFSRI3D.js";S();import{Counter as D,Gauge as Z,Histogram as ee,Registry as xt,collectDefaultMetrics as Dt}from"@prometheus-io/client";import{createServer as $t}from"http";var _r=9464,ct="/metrics",te="(other)",Ht="(none)",Mt=64,Ft=128,Gt=["/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",ze,Je,Ie],Wt=new Set(Gt);function Kt(e){return Wt.has(e)?e:te}function jt(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===""?Ht: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 xt;modelLabel=new ne(Mt);orgLabel=new ne(Ft);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 D({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 D({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 D({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 D({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 qe)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"},Xe()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Qe()/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 D({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 D({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 D({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&&Dt({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=Kt(t.path),o=t.status!==null&&!(t.status>=400&&t.status<500),r=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(t.model,o),s=this.orgLabel.of(t.org,o);this.modelLabel.overflowCount+this.orgLabel.overflowCount-r>0&&(this.modelLabel.overflowCount>r?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=t.stream===!0?"true":"false";this.requests.inc({lane:n,method:t.method===""?te:t.method,status_class:jt(t.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},t.duration_ms/1e3),t.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},t.ttft_ms/1e3),t.stream_error&&this.streamErrors.inc({lane:n,model:i}),t.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function dt(e){return $t((t,n)=>{(async()=>{let o=(t.url??"/").split("?")[0];if(t.method!=="GET"||o!==ct){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${t.method} ${o} \u2014 this port serves only GET ${ct}
|
|
2
|
-
`);return}let r=await e.scrape();n.writeHead(200,{"content-type":e.contentType}),n.end(r)})().catch(o=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(o instanceof Error?o.message:o)}
|
|
3
|
-
`);return}n.end()})})}S();import{createHash as pt}from"crypto";import{createServer as Bt}from"http";var kr=9465,Vt="x-urun-key-id",zt="x-urun-key-fingerprint",Yt="urun-ratelimit-bucket:",Jt="urun-ratelimit-tier:",ut="anonymous",qt=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Xt(e){return pt("sha256").update(`${Yt}${e}`).digest("hex")}function Qt(e){return pt("sha256").update(`${Jt}${e}`).digest("hex")}function Zt(e){let t=/^Bearer[ \t]+(\S.*)$/i.exec((e??"").trim());if(!t)return null;let n=t[1].trim();return qt.test(n)?n:null}function ft(){return Bt((e,t)=>{let n=Zt(e.headers.authorization);t.setHeader(Vt,n===null?ut:Xt(n)),t.setHeader(zt,n===null?ut:Qt(n)),t.writeHead(200),t.end()})}S();import{createClientToken as en,ClientTokenError as tn}from"@urun-sh/core";var I=class extends Error{constructor(n,o=401){super(n);this.status=o;this.name="ProxyAuthError"}status},H=class extends Error{detail;constructor(t,n){super(t),this.name="ControlPlaneUnavailableError",this.detail=n}};function V(e){let t=(e??"").trim();if(t==="")throw new I("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 I("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var nn=60,rn=6e4,on=4096;function sn(e){return e===401||e===403}var oe=class{constructor(t){this.opts=t;this.mint=t.mint??en,this.now=t.now??Date.now}opts;cache=new Map;mint;now;async resolve(t){if(t==="")throw new I("empty Authorization bearer token");let n=this.cache.get(t);if(n&&this.now()-n.at<rn)return{apiKey:t,orgId:n.orgId};let o;try{o=(await this.mint(t,{baseUrl:this.opts.gatewayUrl,expiresIn:nn})).orgId}catch(r){throw r instanceof tn&&sn(r.status)?(this.cache.delete(t),new I("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new H("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${r instanceof Error?r.message:String(r)}`)}if(!o)throw new H("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=on){let r=this.cache.keys().next();r.done||this.cache.delete(r.value)}return this.cache.set(t,{orgId:o,at:this.now()}),{apiKey:t,orgId:o}}clear(){this.cache.clear()}};S();var an=8080,be="serve",Or="0.0.0.0";function ln(e,t,n){let o=(e[t]??"").trim();if(!o)throw new Error(`${t} is not set \u2014 ${n}`);return o}function Ir(e=process.env){let t=(e.PORT??"").trim(),n=t===""?an: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 o=Fe(X(ln(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")),r=(e.URUN_API_URL??"").trim(),i=r?X(r,"URUN_API_URL"):`${o.replace(/\/+$/,"")}/v1`,s=(e.URUN_CATALOG_URL??"").trim(),a=(e.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!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 u=s?{catalogUrl:X(s,"URUN_CATALOG_URL"),anonKey:a}:null,l=(e.URUN_LEDGER_SIGNING_KEY??"").trim(),p=(e.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!p)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let h=l?{keyId:p,key:l}:void 0,d={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"],R=m.filter((E,c)=>Object.values(d)[c]==="");if(R.length!==0&&R.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${R.join(", ")}, which would half-configure the lane plane`);let v=R.length===0?d:void 0,P={baseUrl:(e.URUN_POOLER_URL??"").trim(),token:(e.URUN_POOLER_TOKEN??"").trim(),region:(e.URUN_POOLER_REGION??"").trim()},f=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=f.filter((E,c)=>Object.values(P)[c]==="");if(g.length!==0&&g.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let y=g.length===0?P:void 0;return{port:n,baseUrl:o,apiUrl:i,catalog:u,ledgerSigning:h,lane:v,pooler:y}}S();import{createHash as yn,randomUUID as yt}from"crypto";S();import{request as cn}from"http";var dn="/pooler/v1/inference",M=class extends Error{constructor(n,o,r,i){super(r);this.status=n;this.code=o;this.retryAfterSeconds=i;this.name="PoolerTransportError"}status;code;retryAfterSeconds},un=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)},pn=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(o=>{if(o===null||typeof o!="object"||!("role"in o))return!0;let r=o.role;return r!=="system"&&r!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let o=n.content;return typeof o=="string"?o:JSON.stringify(o)}return JSON.stringify(n)}},ht=e=>new Promise((t,n)=>{let o=[];e.on("data",r=>o.push(r)),e.on("end",()=>t(Buffer.concat(o).toString("utf8"))),e.on("error",n)}),fn=async e=>{let t="pooler_error",n=`the pooler refused the request (HTTP ${e.status})`;try{let o=JSON.parse(await ht(e.body));if(o!==null&&typeof o=="object"&&"error"in o){let r=o.error;r!==null&&typeof r=="object"&&"code"in r&&typeof r.code=="string"&&(t=r.code),r!==null&&typeof r=="object"&&"message"in r&&typeof r.message=="string"&&(n=r.message)}}catch{}return new M(e.status,t,n,e.retryAfterSeconds)};async function gn(e,t,n,o,r){let i=new URL(`${e.baseUrl.replace(/\/+$/,"")}${dn}`),s=JSON.stringify({region:e.region,model:o,request_id:n,streaming:r,payload:t,affinity:{systemPrompt:un(t),firstMessage:pn(t)}});return new Promise((a,u)=>{let l=cn({hostname:i.hostname,port:i.port===""?void 0:Number(i.port),path:`${i.pathname}${i.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:r?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(s))}},p=>{let h=Number(p.headers["retry-after"]??"");a({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:p})});l.on("error",p=>u(new M(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),l.end(s)})}var gt=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 o=n;if(o.t===void 0&&o.error!==null&&typeof o.error=="object"){let r=o.error.code;return{t:"error",code:typeof r=="string"?r:null,body:o}}return o};async function*hn(e){let t="";for await(let o of e.body)for(t+=String(o);;){let r=t.indexOf(`
|
|
4
|
-
|
|
5
|
-
`);if(r===-1)break;let i=t.slice(0,r);t=t.slice(r+2);let s=gt(i);s!==null&&(yield s)}let n=gt(t);n!==null&&(yield n)}async function mt(e,t,n,o){let r=Ne(t,n,o),i=r.model??"";if(i==="")throw new M(400,"missing_model","the pooler submit requires a model");let s=await gn(e,r,n,i,t.stream===!0);if(s.status>=400)throw await fn(s);let a=t.stream===!0?he(n,hn(s)):await mn(s,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function mn(e,t){let n=await ht(e.body),o=null;try{let i=JSON.parse(n);i!==null&&typeof i=="object"&&(o=i)}catch{o=null}if(o===null)throw new M(502,"pooler_bad_body","the pooler answered a non-object body");let r=o;return he(t,(async function*(){yield r})())}var wn=512;function _e(e){return`urun-inference-proxy-${yn("sha256").update(e).digest("hex").slice(0,32)}`}var se=class{constructor(t){this.opts=t}opts;tenants=new Map;label(t,n){let o=Object.assign(Object.create(t),{tenant:n.orgId}),r=this.opts.pooler;return r===void 0?o:Object.assign(Object.create(o),{createResponse:(i,s)=>{let a=`px_${yt()}`;return mt(r,i,a,a)}})}build(t){if(this.opts.build){let i=this.opts.build(t);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,t),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:t.orgId,defaultApp:null,fnName:be,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{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:ot(process.env,process.env.HOSTNAME)??void 0},o=ye(n),r=n.decisionPool?st(n,o):null;return r&&this.ensureDecisionReaper(),{router:o,clients:this.label(we(o,void 0,void 0,r??void 0,void 0,this.opts.lanes),t),decision:r??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>=wn;){let r=this.tenants.entries().next();if(r.done)break;let[i,s]=r.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let o=this.build(t);return this.tenants.set(t.apiKey,o),o.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 o=>{let r=[o.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];o.decision&&r.push(o.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(r)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},wt=512,bn=1024,ie=class extends Error{constructor(){super(`conversation capacity reached (${wt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function _n(e){return{sessionStartOptions:t=>{if(t.startsWith(me))return;let n=e.get(t);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(t,n)=>{t.startsWith(me)||e.set(t,n)}}}function vn(e,t,n,o){let r=ye({baseUrl:e.baseUrl,orgId:t.orgId,defaultApp:null,fnName:be,sharedOnlyListing:!0,apiUrl:e.apiUrl,auth:{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",..._n(o)});return{clients:we(r,void 0,void 0,void 0,void 0,e.lanes),release:async()=>{await r.closeAll()}}}var ae=class{constructor(t){this.opts=t}opts;byCaller=new Map;byHandle=new Map;build(t,n){let o={id:n,subject:`${_e(t.apiKey)}:live:${n}`},r=new Map,i=this.opts.build?this.opts.build(t,o):vn(this.opts,t,o,r);return{id:n,backhaul:i,attachments:0,nativeRefs:r}}attachEntry(t,n){let o=this.byCaller.get(t.apiKey);o===void 0&&(o=new Map,this.byCaller.set(t.apiKey,o));let r=o.get(n);if(r!==void 0)return o.delete(n),o.set(n,r),r.attachments+=1,r;this.evictOverflow();let i=this.build(t,n);return i.attachments=1,o.set(n,i),i}get conversationCount(){let t=0;for(let n of this.byCaller.values())t+=n.size;return t}evictOverflow(){for(;this.conversationCount>=wt;){let t=this.byCaller.keys().next();if(t.done)throw new ie;let n=t.value,o=this.byCaller.get(n),r=!1;for(let[i,s]of o)if(!(s.attachments>0)){o.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),r=!0;break}if(!r)throw o.size===0&&this.byCaller.delete(n),new ie;o.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(t,n){for(let[o,r]of this.byHandle)r.apiKey===t&&r.conversationId===n&&this.byHandle.delete(o)}connectionFor(t){let n=null,o=!1,r=()=>(n===null&&(n=this.attachEntry(t,yt())),n),i={createResponse:(s,a)=>r().backhaul.clients.createResponse(s,a),catalogIdentity:s=>r().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=r().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(s)},listModels:()=>r().backhaul.clients.listModels(),sessionHandle:s=>r().backhaul.clients.sessionHandle(s),releaseSessionHandle:s=>r().backhaul.clients.releaseSessionHandle?.(s),createResponseOn:(s,a,u)=>r().backhaul.clients.createResponseOn(s,a,u),onSessionEnd:(s,a)=>r().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=r().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=r().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(s)},i.openVideoOut=async s=>{let a=r().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(s)},i.supportsAudio=async s=>{let a=r().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(s)},i.supportsSpeech=async s=>{let a=r().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(s)},i.speechVoices=async s=>{let a=r().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(s)},i.speechSessionHandle=async s=>{let a=r().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(s)},i.openAudioOn=async(s,a,u)=>{let l=r().backhaul.clients.openAudioOn;if(l===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 l(s,a,u)},i.openTurnsOn=(s,a)=>{let u=r().backhaul.clients.openTurnsOn;if(u===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 u(s,a)},i.evictSpeechSession=async s=>{let a=r().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(s)},i.supportsTranscription=async s=>{let a=r().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(s)},i.transcriptStreamFor=async s=>{let a=r().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(s)},i.listSpeechToTextModels=async()=>{let s=r().backhaul.clients.listSpeechToTextModels;if(s===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 s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=bn;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:t.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==t.apiKey)throw new J("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=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(o)return;o=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let t=[];for(let o of this.byCaller.values())for(let r of o.values())t.push(r.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(t.map(async o=>{try{await o}catch(r){n.push(String(r instanceof Error?r.message:r))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};S();var Sn="/inference-ledger",En=1e4,le=class extends Error{ledgerFailureReason;constructor(t,n="duplicate"){super(t),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Ee=class extends Error{constructor(n,o){super(o);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},A=class extends Error{ledgerFailureReason="surface";constructor(t){super(t),this.name="LedgerSurfaceError"}},Re=class extends I{ledgerFailureReason="auth";constructor(t){super(t),this.name="LedgerAuthError"}},ke=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(t){super(t),this.name="LedgerSignatureError"}},Rn=[["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",ve],["output_minutes",ve],["cost_nano_usd",ve],["price_version",e=>e===null||typeof e=="string"]];function kn(e){for(let[t,n]of Rn){if(!(t in e))return`${t} (absent)`;if(!n(e[t]))return`${t} (${JSON.stringify(e[t])})`}return null}function Ln(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 o=t.existing;return o===null||typeof o!="object"||Array.isArray(o)?{status:"unavailable"}:kn(o)!==null?{status:"unavailable"}:{status:"found",row:o}}function ve(e){return e===null?!0:typeof e=="number"?Number.isFinite(e):typeof e!="string"?!1:/[^\s]/.test(e)&&Number.isFinite(Number(e))}function Se(e,t){return e===null?t===null:t===null?!1:Number(t)===e}function Cn(e,t){return e===null?t===null:t===null?!1:Number(e.toFixed(9))===Number(t)}function bt(e,t){if(typeof t!="string")return!1;let n=Date.parse(e),o=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(o)&&n===o}function Pn(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&&bt(e.started_at,n.started_at)&&bt(e.completed_at,n.completed_at)&&Se(e.prompt_tokens,n.prompt_tokens)&&Se(e.completion_tokens,n.completion_tokens)&&Se(e.output_units,n.output_units)&&Cn(e.output_minutes,n.output_minutes)}function An(e){let t=o=>String(o??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 Tn(e,t){let n=new TextEncoder,o=await crypto.subtle.importKey("raw",n.encode(t.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",o,n.encode(An(e)));return{signature:Array.from(new Uint8Array(r),s=>s.toString(16).padStart(2,"0")).join(""),key_id:t.keyId}}function Nn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new A(`${t} answered a "recorded" that is not an object: ${JSON.stringify(e)}`);let n=e,o=n.inference_id;if(typeof o!="string"||o==="")throw new A(`${t} answered a row with no inference_id: ${JSON.stringify(e)}`);if(!("cost_nano_usd"in n))throw new A(`${t} answered a row with no cost_nano_usd field: ${JSON.stringify(e)}`);let r=n.cost_nano_usd;if(r!=null&&!(typeof r=="number"&&Number.isInteger(r)&&r>=0))throw new A(`${t} answered cost_nano_usd ${JSON.stringify(r)}, which is neither a non-negative integer nor null`);let i=l=>{if(!(l in n))throw new A(`${t} answered a row with no ${l} field: ${JSON.stringify(e)}`);let p=n[l];if(p===null)return null;if(typeof p!="string")throw new A(`${t} answered a non-string ${l}: ${JSON.stringify(p)}`);if(!/[^\s]/.test(p))throw new A(`${t} answered a BLANK ${l} (${JSON.stringify(p)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return p},s=i("price_version"),a=i("unpriced_reason"),u=r!=null;if(u&&(s===null||a!==null))throw new A(`${t} answered a PRICED row (cost_nano_usd ${String(r)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new A(`${t} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, 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:o,cost_nano_usd:r===void 0?null:r,price_version:s,unpriced_reason:a}}var ce=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async write(t,n){let o=`${this.opts.apiUrl.replace(/\/+$/,"")}${Sn}`,r;try{r=this.opts.signing?JSON.stringify({...n,...await Tn(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new A(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await this.fetchImpl(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:r,signal:AbortSignal.timeout(En)})}catch(l){throw new A(`the uRun ledger surface at ${o} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(i.status===409){let l=await i.text().catch(()=>""),p=Ln(l);throw p.status==="found"&&Pn(n,p.row)?new Ee(p.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.`):p.status==="not_in_this_org"?new le(`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 le(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${p.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). ${l.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new Re("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(!i.ok){let l=await i.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),p;try{let h=JSON.parse(l);if(h!==null&&typeof h=="object"&&"error"in h){let d=h.error;d!==null&&typeof d=="object"&&"code"in d&&(p=d.code)}}catch{}throw p==="ledger_signature_invalid"?new ke(`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: `+l.slice(0,400)):new A(`the uRun ledger surface at ${o} answered HTTP ${i.status}: ${l.slice(0,400)}`)}let s;try{s=await i.json()}catch(l){throw new A(`the uRun ledger surface at ${o} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=s?.recorded;if(a===void 0)throw new A(`the uRun ledger surface at ${o} answered a body with no "recorded" field`);let u=Nn(a,`the uRun ledger surface at ${o}`);if(u.inference_id!==n.inference_id)throw new A(`the uRun ledger surface at ${o} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};S();import{createServer as ir}from"http";S();import{createWebsocketDocConnector as Dn}from"@urun-sh/core/internal";import $n from"ws";S();import*as F from"yjs";import{SessionDocumentImpl as On}from"@urun-sh/core/internal";var In=3e4;function Un(e){return(t,n,o)=>{let r=e(t);F.applyUpdate(n,F.encodeStateAsUpdate(r));let i=a=>F.applyUpdate(r,a),s=a=>F.applyUpdate(n,a);return n.on("update",i),r.on("update",s),{awareness:o,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",i),r.off("update",s)}}}}async function*xn(e,t){let n=[],o=!1,r=null,i="",s=u=>{if(!("responses"in u)||typeof u.responses!="object"||u.responses===null)return null;let l=u.responses;if(!(t in l))return null;let p=l[t];if(p===null||typeof p!="object"||!("error"in p))return{body:p,error:null};let h=p.error;return h===null?{body:p,error:null}:{body:p,error:h}},a=u=>{let l={};for(let[h,d]of Object.entries(u)){let m=d;l[h]=typeof m?.toJSON=="function"?m.toJSON():d}if("tokens"in l&&typeof l.tokens=="object"&&l.tokens!==null){let h=l.tokens[t];typeof h=="string"&&h.length>i.length&&(n.push({t:"delta",delta:h.slice(i.length)}),i=h)}let p=s(l);if(p!==null){p.error!==null?n.push({t:"error",body:p.error}):n.push({t:"response",body:p.body}),o=!0,r?.(),r=null;return}if("progress"in l&&typeof l.progress=="object"&&l.progress!==null){let h=l.progress[t];if(typeof h=="object"&&h!==null&&"state"in h&&h.state==="error"){let m="error"in h&&typeof h.error=="string"?h.error:"lane request failed";n.push({t:"error",body:{message:m}}),o=!0,r?.(),r=null;return}}r?.(),r=null};if(a(e.get()??{}),!o){let u=e.on("change",a);try{for(;!o;){if(n.length>0){yield n.shift();continue}await new Promise(l=>{r=l})}}finally{u()}}for(;n.length>0;)yield n.shift()}function Le(e){let{laneId:t}=e,n=e.connector??(e.roomDoc?Un(e.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let o=new Map,r=!1,i=u=>{if(r)throw new Error(`lane ${t} is destroyed \u2014 the doc host shut down or the lane was evicted`);let l=o.get(u);return l||(l=new On(u,t,n),o.set(u,l)),l},s=u=>{let l="llm-resp:";if(!u.startsWith(l))throw new Error(`lane session exposes no stream "${u}" \u2014 only the llm reply lanes (${l}<rid>)`);let p=u.slice(l.length);return{messages:()=>xn(i("llm"),p),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(u){return i(u)},stream:s,async end(){},async whenLive(u){let l=i("llm");if(l.synced===!0)return;let p=u?.timeout??e.whenLiveTimeoutMs??In;await new Promise((h,d)=>{let m=setTimeout(()=>{R(),d(new Error(`lane ${t} llm doc never synced within ${p}ms`))},p),R=l.onSynced(()=>{clearTimeout(m),u?.signal?.removeEventListener("abort",v),h()}),v=()=>{clearTimeout(m),R(),d(u?.signal?.reason instanceof Error?u.signal.reason:new Error("aborted"))};u?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){r=!0;for(let u of o.values())u.dispose();o.clear()}}}function Hn(e){let t=(e.gpuSpec??"").split(":")[0];if(typeof e.appId!="string"||e.appId==="")throw new $e(`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 _t(e){let t=e.now??Date.now,n=new Map,o=new Map,r=new Set,i=new Map,s=(d,m,R,v,P)=>{let f=R?Le({laneId:d,roomDoc:E=>e.roomDoc(d,E)}):Le({laneId:d,connector:Dn({serverUrl:`ws://${v}/doc`,sessionId:d,token:()=>at(d,e.tokenSecret,void 0,void 0,P),WebSocketPolyfill:$n})}),g=R?a(d):rt(f,`lane:${d}`,{armOnFirstSync:!0}),y={session:f,responses:new Oe(f),gone:g,goneWatch:g,laneId:d,pool:m,inFlight:0,laneSession:f,self:R,host:v??""};return n.set(d,y),g.onGone(()=>u(y)),y},a=d=>{let m=null,R=!1,v=new Set,P=g=>{if(!m){m=g;for(let y of[...v])y(g);v.clear()}},f=e.hostedSignal?.(d,g=>{if(g){R=!0;return}R&&P(new J(`the lane ${d} 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),()=>{}):(v.add(g),()=>v.delete(g))},dispose(){f?.(),v.clear()}}},u=d=>{l(d)&&(n.delete(d.laneId),o.delete(d.laneId),d.goneWatch?.dispose())},l=d=>{let m=d.laneId;return typeof m=="string"&&n.get(m)===d},p=(d,m)=>{throw e.metrics?.observeLane503Fast(m??""),i.set(d,t()),new q(d)},h=async(d,m)=>{let R=Hn(m);r.add(R);let v=t();try{let P=await e.laneWarmWaitMsFor?.(d,m)??e.laneColdWakeDefaultMs??0,f=await e.plane.pick({pool:R,model:d,holdMs:P});e.metrics?.observeLaneReady(d??"",f.length);let y=f.map(c=>({laneId:c.laneId,self:c.host===e.selfAddress,host:c.host})).sort((c,w)=>c.self!==w.self?c.self?-1:1:(o.get(c.laneId)??0)-(o.get(w.laneId)??0))[0];y||p(R,d);let E=n.get(y.laneId);return E?.goneWatch?.gone()&&(u(E),E=void 0),E&&(E.pool!==R||E.self!==y.self||E.host!==y.host)&&(u(E),E=void 0),E||(E=s(y.laneId,R,y.self,y.host,m.sharedOrgId??void 0)),E.inFlight+=1,o.set(y.laneId,(o.get(y.laneId)??0)+1),{app:R,entry:E,identity:{kind:"catalog",model_id:m.modelId??d??"",variant:m.variant??""}}}finally{e.metrics?.observeLanePick(d??"",t()-v)}};return{sessionFor(d,m){return h(d,m)},release(d){l(d)&&(d.inFlight=Math.max(0,d.inFlight-1),o.set(d.laneId,d.inFlight))},owns(d){return l(d)},entryFor(d){return n.get(d)??null},evict(d){l(d)&&(d.gone.dispose(),n.delete(d.laneId),o.set(d.laneId,0),d.laneSession.destroy())},async status(){let d=[...new Set([...r,...[...n.values()].map(v=>v.pool)])].sort(),m=await e.plane.status().catch(()=>[]),R=new Map(Mn(m));return Promise.all(d.map(async v=>{let P=R.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:P.lanes,lastDemandAt:P.lastDemandAt,local:[...n.values()].filter(f=>f.pool===v).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:i.get(v)??null}}))},async close(){for(let d of n.values())d.gone.dispose(),d.laneSession.destroy();n.clear(),o.clear(),await e.plane.close()},stats(){return[...n.values()].map(d=>({pool:d.pool,laneId:d.laneId,inFlight:d.inFlight}))}}}function Mn(e){return new Map(e.map(t=>[t.pool,{lanes:t.lanes,lastDemandAt:t.lastDemandAt}]))}S();import{request as Fn}from"http";var Gn="/pooler/v1/lanes/pick",Wn="/pooler/v1/lanes/status",Kn=1e4;function vt(e,t,n,o,r){return new Promise((i,s)=>{let a=new URL(n,e.baseUrl),u=o===void 0?void 0:Buffer.from(JSON.stringify(o)),l=Fn({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:t,headers:{authorization:`Bearer ${e.token}`,...u===void 0?{}:{"content-type":"application/json","content-length":String(u.byteLength)}},timeout:r},p=>{let h=[];p.on("data",d=>h.push(d)),p.on("end",()=>{let d=Buffer.concat(h).toString("utf8"),m=null;try{m=d===""?null:JSON.parse(d)}catch{m=null}i({status:p.statusCode??0,json:m})}),p.on("error",s)});l.on("timeout",()=>{l.destroy(new Error(`pooler lane surface timed out after ${r}ms (${t} ${n})`))}),l.on("error",s),l.end(u)})}function St(e,t,n){if(e===503)return new q(n);let o=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: ${o}`)}function Et(e){return{async pick({pool:t,model:n,holdMs:o=0}){let r=await vt(e,"POST",Gn,{pool:t,model:n,hold_ms:o},o+Kn);if(r.status!==200)throw St(r.status,r.json,t);return(r.json?.lanes??[]).filter(s=>typeof s.lane_id=="string"&&s.lane_id!==""&&typeof s.host=="string"&&s.host!=="").map(s=>({laneId:s.lane_id,host:s.host}))},async status(){let t=await vt(e,"GET",Wn,void 0,5e3);if(t.status!==200)throw St(t.status,t.json,"");let n=t.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}S();import{WebSocketServer as tr}from"ws";S();import*as kt from"yjs";import*as K from"y-protocols/sync";import*as x from"y-protocols/awareness";import*as C from"lib0/encoding";import*as j from"lib0/decoding";import*as Lt from"lib0/map";import Bn from"lodash.debounce";S();var Rt=()=>{};var Vn=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,zn=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Yn=0,Jn=1;var qn=process.env.GC!=="false"&&process.env.GC!=="0",Xn=process.env.YPERSISTENCE,de=null;if(typeof Xn=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var W=new Map,ue=0,Pe=1,Qn=(e,t,n)=>{let o=C.createEncoder();C.writeVarUint(o,ue),K.writeUpdate(o,e);let r=C.toUint8Array(o);n.conns.forEach((i,s)=>z(n,s,r))},Ce=class extends kt.Doc{constructor(t){super({gc:qn}),this.name=t,this.conns=new Map,this.awareness=new x.Awareness(this),this.awareness.setLocalState(null);let n=({added:o,updated:r,removed:i},s)=>{let a=o.concat(r,i);if(s!==null){let p=this.conns.get(s);p!==void 0&&(o.forEach(h=>{p.add(h)}),i.forEach(h=>{p.delete(h)}))}let u=C.createEncoder();C.writeVarUint(u,Pe),C.writeVarUint8Array(u,x.encodeAwarenessUpdate(this.awareness,a));let l=C.toUint8Array(u);this.conns.forEach((p,h)=>{z(this,h,l)})};this.awareness.on("update",n),this.on("update",Qn),!1}},Ae=(e,t=!0)=>Lt.setIfUndefined(W,e,()=>{let n=new Ce(e);return n.gc=t,de!==null&&de.bindState(e,n),W.set(e,n),n}),Zn=(e,t,n)=>{try{let o=C.createEncoder(),r=j.createDecoder(n);switch(j.readVarUint(r)){case ue:C.writeVarUint(o,ue),K.readSyncMessage(r,o,t,e),C.length(o)>1&&z(t,e,C.toUint8Array(o));break;case Pe:{x.applyAwarenessUpdate(t.awareness,j.readVarUint8Array(r),e);break}}}catch(o){console.error(o),t.emit("error",[o])}},G=(e,t)=>{if(e.conns.has(t)){let n=e.conns.get(t);e.conns.delete(t),x.removeAwarenessStates(e.awareness,Array.from(n),null),e.conns.size===0&&de!==null&&(de.writeState(e.name,e).then(()=>{e.destroy()}),W.delete(e.name))}t.close()},z=(e,t,n)=>{t.readyState!==Yn&&t.readyState!==Jn&&G(e,t);try{t.send(n,o=>{o!=null&&G(e,t)})}catch{G(e,t)}},er=3e4,Ct=(e,t,{docName:n=t.url.slice(1).split("?")[0],gc:o=!0}={})=>{e.binaryType="arraybuffer";let r=Ae(n,o);r.conns.set(e,new Set),e.on("message",a=>Zn(e,r,new Uint8Array(a)));let i=!0,s=setInterval(()=>{if(!i)r.conns.has(e)&&G(r,e),clearInterval(s);else if(r.conns.has(e)){i=!1;try{e.ping()}catch{G(r,e),clearInterval(s)}}},er);e.on("close",()=>{G(r,e),clearInterval(s)}),e.on("pong",()=>{i=!0});{let a=C.createEncoder();C.writeVarUint(a,ue),K.writeSyncStep1(a,r),z(r,e,C.toUint8Array(a));let u=r.awareness.getStates();if(u.size>0){let l=C.createEncoder();C.writeVarUint(l,Pe),C.writeVarUint8Array(l,x.encodeAwarenessUpdate(r.awareness,Array.from(u.keys()))),z(r,e,C.toUint8Array(l))}}};var Te="/doc/",At=30,nr=1e4,Pt="llm";function rr(e){if(!e.startsWith(Te))return null;let t=e.slice(Te.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 Y(e,t,n){let o=t===401?"Unauthorized":t===403?"Forbidden":t===404?"Not Found":"Internal Server Error",r=`${n}\r
|
|
7
|
-
`;e.end(`HTTP/1.1 ${t} ${o}\r
|
|
8
|
-
Connection: close\r
|
|
9
|
-
Content-Type: text/plain; charset=utf-8\r
|
|
10
|
-
Content-Length: ${Buffer.byteLength(r)}\r
|
|
11
|
-
\r
|
|
12
|
-
${r}`)}function Tt(e,t){let n=new tr({noServer:!0}),o=new Set,r=new Map,i=new Map,s=f=>r.get(`${f}/${Pt}`)??0,a=f=>i.get(f)??0,u=new Map,l=new Map,p=new Set,h=new Set,d=!1,m=(f,g,y)=>{let E=s(f)>0,c=a(f),w=c>0,_=`${f}/${g}`,b=r.get(_)??0;y>0?r.set(_,y):r.delete(_);let k=c+y-b;k>0?i.set(f,k):i.delete(f);let L=s(f)>0,O=k>0;if(E!==L){L?R(f):v(f);for(let $ of u.get(f)??[])$(L)}w&&!O&&queueMicrotask(()=>{let $=`${f}/`;for(let[U,B]of[...W.entries()])!U.startsWith($)||B.conns.size>0||(W.delete(U),B.destroy())})},R=f=>{if(!t.hostRegistry||l.has(f))return;let g=()=>{t.hostRegistry?.setHost(f,t.selfAddress).catch(()=>{})};g();let y=setInterval(g,nr);y.unref?.(),l.set(f,y)},v=f=>{let g=l.get(f);g&&(clearInterval(g),l.delete(f)),t.hostRegistry&&t.hostRegistry.delHost(f,t.selfAddress).catch(()=>{})},P=(f,g,y)=>{let E;try{E=new URL(f.url??"/","http://localhost")}catch{Y(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>h.delete(g));let c=rr(E.pathname);if(!c){if(E.pathname.startsWith(Te)){Y(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(g);return}p.add(g);let w=!1;(async()=>{let _=E.searchParams.get("token")??"",b=null;try{b=_===""?null:await t.verifyToken(_,c.laneId,c.docName)}catch{b=null}if(b===null){Y(g,401,"invalid or missing lane doc token");return}let k=b;if(k.tenant!==void 0&&t.laneTenantOf){let L=null;try{L=await t.laneTenantOf(c.laneId)}catch{L=null}if(L==null||L==="")t.onLaneTenantMissing?.();else if(k.tenant!==L){Y(g,403,"lane doc token org does not match the lane record");return}}d||g.destroyed||(w=!0,n.handleUpgrade(f,g,y,L=>{p.delete(g),o.add(L),L.on("close",()=>o.delete(L));let O=k.scope===it||k.scope===void 0&&typeof k.app=="string"&&typeof k.fn=="string"&&k.aud==="sfu";if(O){let U=`${c.laneId}/${c.docName}`,B=(r.get(U)??0)+1;m(c.laneId,c.docName,B),B>1&&c.docName===Pt&&t.hostRegistry?.setHost(c.laneId,t.selfAddress).catch(()=>{})}L.on("close",()=>{if(!O)return;let U=`${c.laneId}/${c.docName}`;m(c.laneId,c.docName,Math.max(0,(r.get(U)??1)-1))}),Ct(L,f,{docName:`${c.laneId}/${c.docName}`,gc:!0})}))})().catch(()=>{!w&&!g.destroyed&&Y(g,500,"lane doc upgrade failed")}).finally(()=>p.delete(g))};return e.on("upgrade",P),{async close(){d=!0,e.off("upgrade",P);for(let g of[...l.keys()])v(g);await new Promise(g=>{if(o.size===0&&p.size===0){g();return}let y=o.size+p.size,E=()=>{y-=1,y<=0&&g()};for(let c of o)c.once("close",E);for(let c of p)c.once("close",E);for(let c of o)c.close(1001,"lane doc host shutting down");for(let c of p)c.destroy()}),r.clear(),i.clear(),u.clear()},roomDoc(f,g){return Ae(`${f}/${g}`,!0)},isHosted(f){return s(f)>0},onHostedChange(f,g){let y=u.get(f);return y||(y=new Set,u.set(f,y)),y.add(g),g(s(f)>0),()=>{y.delete(g)}}}}S();var or="urun:catalog:v1";function Nt(e){let t=e.refreshMs??5e3,n=e.now??Date.now,o=null,r=0,i=null,s=async()=>{let u=await e.redis.hgetall(or),l=[];for(let p of Object.values(u))try{l.push(JSON.parse(p))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
13
|
-
`)}return o=l,r=n(),l},a=()=>o===null||n()-r>=t;return{rows(){return a()?(i||(i=s().finally(()=>{i=null})),i):Promise.resolve(o)},close(){o=null,i=null}}}import ar from"ioredis";S();var pe="/inference-usage",Ot=25e3;var sr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function It(e){if(!(e instanceof Error))return`a ${typeof e}`;let t=sr.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 fe=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async lookup(t,n){let o=`${this.opts.apiUrl.replace(/\/+$/,"")}${pe}`,r;try{r=await this.fetchImpl(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Ot)})}catch(s){throw new Q(`the uRun usage surface (POST ${pe}) could not be reached within ${Ot}ms: ${It(s)}`)}if(r.status===401||r.status===403)throw await r.text().catch(()=>{}),new I("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!r.ok){let s=await r.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new Q(`the uRun usage surface (POST ${pe}) answered HTTP ${r.status} (${a})`)}let i;try{i=await r.json()}catch(s){throw new Q(`the uRun usage surface (POST ${pe}) answered HTTP ${r.status} with a body that is not JSON: ${It(s)}`)}return Ye(i,this.opts.onRejectedRow)}};var lr=5e3,cr=1e3,dr=1500,ur=3e3,pr="/api/client-tokens";function ge(e,t,n){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}function Ut(e,t,n,o){ge(e,t,{error:{message:n,type:o}})}async function fr(e,t=fetch){let n=`${e.replace(/\/+$/,"")}${pr}`;try{let o=await t(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(ur)});return o.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:o.status>=500?{ready:!1,detail:`${n} answered HTTP ${o.status}`}:{ready:!0,detail:`${n} answered HTTP ${o.status}`}}catch(o){return{ready:!1,detail:`${n} unreachable: ${o instanceof Error?o.message:String(o)}`}}}function es(e){let t=e.resolver??new oe({gatewayUrl:e.baseUrl}),n=new re(e.defaultMetrics===void 0?{}:{defaultMetrics:e.defaultMetrics}),o=null,r=(()=>{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 c=new ar(e.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),w=Nt({redis:c});return{registry:_t({selfAddress:e.lane.selfAddress,tokenSecret:e.lane.tokenSecret,plane:Et({baseUrl:e.pooler.baseUrl,token:e.pooler.token}),hostedSignal:(b,k)=>o?.onHostedChange(b,k)??(()=>()=>{}),roomDoc:(b,k)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(b,k)},metrics:n,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(b,k)=>w.rows().then(L=>{let O=Ue(L,k);return O?.warm_wait_s!==void 0?O.warm_wait_s*1e3:void 0})}),catalog:w,redis:c}})(),i=e.registry??new se({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:r?null:e.catalog,catalogRows:r?()=>r.catalog.rows():void 0,lanes:r?.registry,pooler:e.pooler}),s=e.probeControlPlane??(()=>fr(e.baseUrl)),a=async()=>{let c=null;for(let b of i.decisionPools()){c=b;break}if(!c)return null;let w=c.stats();if(w.some(b=>b.draining))return{ok:!1,detail:"decision pool draining"};if(w.every(b=>b.attached===0&&b.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let _=await c.pingReady(dr);return{ok:_,detail:_?"a decision slot answered its session ping":"no decision slot answered its session ping"}},u=e.usageClient??new fe({apiUrl:e.apiUrl}),l=e.ledgerClient??new ce({apiUrl:e.apiUrl,...e.ledgerSigning?{signing:e.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),h=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&h&&(async()=>{try{await i.decisionWarmerFor({orgId:p,apiKey:h})?.warmFor(tt)}catch(c){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(c instanceof Error?c.message:c)}
|
|
14
|
-
`)}})();let d=async c=>t.resolve(V(c.headers.authorization)),m=c=>c instanceof I?{status:c.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:c instanceof H?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:c.detail}:null,R=nt({clients:async c=>i.clientsFor(await d(c)),usage:{authorize:c=>V(c.headers.authorization),lookup:(c,w)=>u.lookup(c,w)},statusOf:m,...e.requestLog?{requestLog:e.requestLog}:{},observe:c=>n.observe(c),ledger:{write:(c,w)=>l.write(V(c.headers.authorization),w),observe:c=>n.observeLedger(c),...e.ledgerLog?{report:e.ledgerLog}:{}}}),v=null,P=null,f=ir((c,w)=>{let _=new URL(c.url??"/","http://localhost");(async()=>{if(c.method==="GET"&&_.pathname==="/healthz"){ge(w,200,{ok:!0});return}if(c.method==="GET"&&_.pathname==="/readyz"){let L=Date.now();if((!v||L-v.at>=lr)&&(v={at:L,...await s()}),!P||L-P.at>=cr){let U=await a();P=U===null?{at:L,ok:!0,detail:null}:{at:L,ok:U.ok,detail:U.detail}}let O=(v?.ready??!1)&&P.ok,$=P.detail===null?v?.detail??"control plane not yet probed":`${v?.detail??"control plane not yet probed"}; ${P.detail}`;ge(w,O?200:503,{ok:O,control_plane:$});return}if(c.method==="GET"&&_.pathname==="/lanez"){ge(w,200,{pools:r?await r.registry.status():null});return}let b=_.pathname==="/v1"||_.pathname.startsWith("/v1/"),k=_.pathname.startsWith("/partners/");if(!b&&!k){Ut(w,404,`no route for ${c.method} ${_.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}R(c,w)})().catch(b=>{if(!w.headersSent){Ut(w,500,String(b instanceof Error?b.message:b),"proxy_error");return}w.end()})}),g=e.conversations??new ae({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:r?null:e.catalog,catalogRows:r?()=>r.catalog.rows():void 0,lanes:r?.registry}),y=[De(f,{authenticate:async c=>{let w=await t.resolve(c),_=g.connectionFor(w);return{clients:_.clients,scope:_e(w.apiKey),onBindResumeHandle:_.bindResumeHandle,clientsForResume:_.clientsForResume,release:_.release}}}),Me(f,{clients:async c=>i.clientsFor(await d(c)),statusOf:m}).close,We(f,{resolver:{resolve:async(c,w)=>{let _=await t.resolve(V(c.headers.authorization)),b=g.connectionFor(_),k;try{k=await Ve(Ke(b.clients,e.realtimeCompanions),je(c),w,Be(c))}catch(O){throw b.release().catch(()=>{}),O}let L=k.release;return{...k,release:async()=>{await L?.(),await b.release()}}}}})];if(e.lane&&r){let c=e.lane,w=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Tt(f,{verifyToken:(b,k)=>lt(b,k,c.tokenSecret,void 0,w),selfAddress:c.selfAddress,laneTenantOf:b=>r.redis.get(`lane_tenant:${b}`),onLaneTenantMissing:()=>n.observeLaneDocTenantMissing(),previousTokenSecret:w,hostRegistry:{setHost:(b,k)=>r.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:${b}`,k,String(At)),delHost:b=>r.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${b}`,c.selfAddress)}});let _=r;y.push(async()=>{await o.close(),await _.registry.close(),_.redis.quit().catch(()=>{})})}f.on("upgrade",(c,w)=>{let _=new URL(c.url??"/","http://localhost");_.pathname===xe||_.pathname===He||_.pathname===Ge||o!==null&&_.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 ${_.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),w.destroy())});let E=async()=>{for(let c of y)await c();await g.detachAll()};return{server:f,metricsServer:dt(n),metrics:n,edgeIdentityServer:ft(),registry:i,closeAll:()=>i.closeAll(),closeWebSockets:E}}async function ts(e,t,n){n&&await n();let o=new Promise(r=>e.close(()=>r()));e.closeAllConnections(),await o,await Ze()||et(),await t()}export{_r as a,ct as b,te as c,Ht as d,Mt as e,Ft as f,Kt as g,jt as h,ne as i,re as j,dt as k,kr as l,Vt as m,zt as n,Yt as o,Jt as p,ut as q,Xt as r,Qt as s,Zt as t,ft as u,I as v,H as w,V as x,rn as y,on as z,oe as A,an as B,be as C,Or as D,Ir as E,wn as F,_e as G,se as H,wt as I,bn as J,ie as K,ae as L,Sn as M,En as N,le as O,A as P,Nn as Q,ce as R,lr as S,ur as T,es as U,ts as V};
|
package/dist/chunk-KTMDSM7F.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as H}from"./chunk-CAR4AEQJ.js";import{f as X,g as D,h as Y,i as Q}from"./chunk-7OH7UJ2H.js";import{c as C,f as x,g as $,p as B}from"./chunk-6M5JK4YC.js";import{a as z,b as N}from"./chunk-L6HTHDVV.js";import{a as k}from"./chunk-GL7EWL3V.js";import{b as W,c as G,f as V,i as T,j,k as F,l as q,o as I,p as K,q as J}from"./chunk-OOCRI7ZM.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as se,createClientToken as we,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as ye,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ie,isWakingPhase as he,SessionFailedError as Se}from"@urun-sh/core";v();import{SessionFailedError as pe}from"@urun-sh/core";var M=2;function ue(n){let r=n?.type;return r==="response.created"||r==="response.in_progress"}function fe(n){let r=n?.type;return r==="response.completed"||r==="error"}function ne(n){return async function(a,d){let p=await n.sessionFor(a.model);return(async function*(){for(let l=1;l<=M;l++){let{app:w,entry:u,identity:y}=l===1?p:await n.sessionFor(a.model);d?.({sessionId:n.sessionIdOf?.(u)??null,identity:y});let s=!1,c=!1;try{let f=await n.createStream(u,a);for await(let g of f){if(fe(g)&&(s=!0),ue(g)){if(l>1)continue}else c=!0;yield g}}catch(f){if(f instanceof pe&&(f.kind==="never-live"||f.kind==="create-failed")){try{n.onAdmissionVerdict?.(w,u,f)}catch{}throw f}if(l<M&&!c){await n.evict(w,u);continue}throw f}if(s)return;if(l<M&&!c){await n.evict(w,u);continue}return}})()}}import{randomUUID as Pe}from"crypto";v();var me="audio";var oe=new WeakMap;function te(n,r,a){let d=n.doc(me),p=[],i=0,l=0;return{sessionId:r,appendInputAudio(w){let u=Buffer.from(w,"base64");if(u.byteLength===0||(p.push(u),i+=u.byteLength,i<4800))return;let y=Buffer.concat(p,i).toString("base64");if(p=[],i=0,a===void 0){let s=(oe.get(n)??0)+1;oe.set(n,s),d.set({frames:{[String(s%32)]:{s,pcm16:y}}})}else{let s=++l;d.set({frames:{[`${a}:${s%32}`]:{s,pcm16:y,c:a}}})}},onOutputAudio(){return()=>{}}}}var Ee=0,Oe=4,ve=4;function Ke(n,r){let a=(l,w)=>{let u=(n[l]??"").trim();if(!u)return w;let y=Number.parseInt(u,10);if(!Number.isInteger(y)||y<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(n[l])})`);return y},d=(n.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let p=d?Number.parseInt(d,10):Ee;if(!Number.isInteger(p)||p<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(n.URUN_DECISION_POOL_MIN)})`);let i=a("URUN_DECISION_POOL_MAX",Math.max(p,Oe));return{min:p,max:i,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",ve),replicaId:(n.URUN_REPLICA_ID??"").trim()||r||"proxy"}}function Je(n){let r=(n.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!r)return D;let a=Number.parseInt(r,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(n.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function re(n,r,a,d){let p=n[a];if(typeof p!="function")throw new Error(`app "${r}" has no function "${a}" (set URUN_FUNCTION)`);let i=d?p(void 0,d):p();if(typeof i.end!="function")throw new Error(`app "${r}" function "${a}" returned a session without end()`);return i}function ce(n,r,a,d){let{baseUrl:p,orgId:i,auth:l}=n,w=r.fnName??n.fnName,u=n.sessionStartOptions?.(a),y=d||u||r.sharedApp?{...r.sharedApp?{sharedApp:!0}:{},...u,...d}:void 0,s=S=>({session:S,responses:new k(S),gone:z(S,a)});if(l.lane==="jwt"){let S=se(r.appSlug,{baseUrl:p,orgId:i,jwt:l.jwt});return s(re(S,r.appSlug,w,y))}let{apiKey:c,gatewayUrl:f}=l,g=(typeof n.subject=="function"?n.subject():n.subject)??Pe(),h=se(r.appSlug,{baseUrl:p,orgId:i,getAccessToken:async()=>(await we(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${r.appSlug}/${w}`],subject:g,...r.sharedApp?{sharedApp:!0}:{}})).token});return s(re(h,r.appSlug,w,y))}function Ae(n){let r=n.session.id;if(typeof r!="string"||r.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 r}function le(n){if(n.kind==="never-live")return!0;if(n.kind!=="create-failed")return!1;let r=n.status.error?.httpStatus,a=n.status.error?.code;return r===410||r===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Ie=new Set(["error","paused"]);function Xe(n){let{auth:r,catalog:a}=n,d=null,p=(l,w)=>{let u=ce(n,l,w);return n.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&n.onSessionOpen(w,u.session.id),u.gone.onGone(()=>{d?.evict(w,u)}),u},i=new J({sharedOnlyListing:n.sharedOnlyListing===!0,defaultApp:n.defaultApp,fnName:n.fnName,openSession:p,closeSession:async l=>{if(l.gone.dispose(),n.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:r.lane==="api-key"?()=>q({apiUrl:n.apiUrl,apiKey:r.apiKey}):null,listCatalog:n.catalogRows??(a?()=>H(a):null),listPrices:a?()=>G(a):null,shared:r.lane==="api-key"?()=>W({apiUrl:n.apiUrl,apiKey:r.apiKey}):null,sessionKey:Ae});return d=i,n.defaultApp!==null&&i.seed(n.defaultApp,p({appSlug:n.defaultApp},I({appSlug:n.defaultApp}))),i}function Ye(n,r){let a=n.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",p=new Map,i=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 X({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:d,openSlot:async h=>{let S=ce(n,s,c,{concurrencyKey:h.concurrencyKey});return S.gone.onGone(()=>g.markSessionDead(S)),await b(S.session),w(`slot attached pool=${c} slot=${h.concurrencyKey} session=${S.session.id??"(no id)"}`),S},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,S)=>w(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${S}`),terminalOpenFailure:h=>h instanceof Se&&le(h)});return i.set(c,{target:s,env:a}),p.set(c,g),g},y=async(s,c)=>{let f=i.get(c);if(f)try{let g=await r.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(n.defaultApp===null)return;let s={appSlug:n.defaultApp};await u(s,I(s)).boot()},async sessionFor(s){let c=await r.resolveTargetFor(s),f=I(c),g=u(c,f);await y(c,f);let h=await g.acquire({timeoutMs:g.requestWaitMs}),S=l.get(h.entry)??[];return S.push(h),l.set(h.entry,S),{app:f,entry:h.entry,identity:K(c)}},async warmFor(s){let c=await r.resolveTargetFor(s);await u(c,I(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 i)y(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(n){return he(n?.name)?n?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ie:ye:ie}async function b(n,r){let a=n.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(n,{timeout:_e(n.phase),signal:r})}async function ae(n){if(typeof n.cancel=="function")try{await n.cancel();return}catch{}if(typeof n.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");n.detach()}function _(n){return n.reason instanceof Error?n.reason:new Error("the client socket closed")}function Qe(n,r=$,a,d,p=D,i){let l=new WeakMap,w=new WeakMap,u=new WeakMap,y=new WeakMap,s=new WeakMap,c=e=>{let o=e.session.id;return typeof o=="string"&&o.length>0?o:null},f="lane",g=e=>{let o=F(e);if(!i||!o||o.app!==f)return null;let t=i.entryFor(o.key);if(!t)throw new T(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},h=async e=>g(e)?.entry??(await n.sessionForHandle(e)).entry,S=e=>{let o=l.get(e);if(!o){let t={waiting:0,gone:new AbortController};s.set(e,t),o=(async()=>{if(await b(e.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(e)===t&&s.delete(e);let m=await C(e.session,await r());return Object.assign(m,{sessionId:e.session.id})})(),l.set(e,o),o.catch(()=>{l.get(e)===o&&l.delete(e)}),o.then(()=>{s.get(e)===t&&s.delete(e)},()=>{s.get(e)===t&&s.delete(e)})}return o},de=e=>{let o=y.get(e);return o||(o=(async()=>{let t=await S(e);return{appendInputAudio:m=>t.appendInputAudio(m),onOutputAudio:m=>t.onOutputAudio(m),sessionId:c(e)}})(),y.set(e,o),o.catch(()=>{y.get(e)===o&&y.delete(e)})),o},R=async(e,o,t)=>{if(t?.aborted){let E=s.get(e);throw(l.get(e)===void 0||E!==void 0&&E.waiting===0)&&await ae(e.session),_(t)}let m=o(e),P=s.get(e);return P!==void 0&&P.waiting++,t===void 0?m:new Promise((E,O)=>{let A=()=>{P!==void 0&&--P.waiting===0&&s.get(e)===P&&(P.gone.abort(),s.delete(e),l.delete(e),y.delete(e),ae(e.session).catch(()=>{})),O(_(t))};t.addEventListener("abort",A,{once:!0});let U=()=>t.removeEventListener("abort",A);m.then(L=>{U(),E(L)},L=>{U(),O(L)})})};return{createResponse:ne({sessionFor:i?async e=>{let o=await n.resolveTargetFor(e);if(o.sharedApp){let t=await i.sessionFor(e,o);return{app:t.app,entry:t.entry,identity:t.identity}}return d?d.sessionFor(e):n.sessionFor(e)}:d?e=>d.sessionFor(e):e=>n.sessionFor(e),sessionIdOf:e=>c(e),evict:(e,o)=>{i&&i.owns(o)?i.evict(o):d?d.evict(o):n.evict(e,o)},onAdmissionVerdict:(e,o,t)=>{le(t)&&(i&&i.owns(o)?i.evict(o):d?d.markSessionDead(o):n.evict(e,o),a?.(e,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(e,o)=>{try{await b(e.session);let t=Y(N(await e.responses.responses.create(o),e.gone),p);if(!d&&!i)return t;let m=e;return(async function*(){try{yield*t}catch(E){throw Q(E)&&(i&&i.owns(m)?i.evict(m):d&&(E instanceof T?d.markSessionDead(m):d.evict(m))),E}finally{i&&i.owns(m)?i.release(m):d?.end(m)}})()}catch(t){throw i&&i.owns(e)?i.release(e):d&&d.end(e),t}}}),listModels:()=>n.modelList(),openRouterModels:()=>n.openRouterModels(),supportsImages:(e,o)=>n.supportsImages(e,o),listImageModels:()=>n.imageModelList(),catalogIdentity:e=>n.catalogIdentityFor(e),servingAppSlug:async e=>await n.servingAppSlugFor(e),supportsAudio:e=>n.supportsAudio(e),supportsSpeech:e=>n.supportsSpeech(e),speechVoices:e=>n.speechVoices(e),supportsTranscription:e=>n.supportsTranscription(e),transcriptStreamFor:e=>n.transcriptStreamFor(e),listSpeechToTextModels:()=>n.speechToTextModelList(),openAudio:async(e,o)=>{let{entry:t}=await n.sessionFor(e);return await R(t,S,o)},openAudioOn:async(e,o,t)=>{let m=g(e);if(m)return te(m.entry.session,m.laneId,t);let{entry:P}=await n.sessionForHandle(e);return await R(P,de,o)},openTurnsOn:async function*(e,o){if(o?.aborted)throw _(o);let t=await h(e);yield*V(t.session,o)},openVideo:async e=>{let{entry:o}=await n.sessionFor(e),t=w.get(o);return t||(t=x(o.session),w.set(o,t)),t},openVideoOut:async e=>{let{entry:o}=await n.sessionFor(e),t=u.get(o);return t||(t=B(o.session),u.set(o,t)),t},sessionHandle:async e=>{if(i){let o=await n.resolveTargetFor(e);if(o.sharedApp){let t=await i.sessionFor(e,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 j(f,m)}}return(await n.handleFor(e)).handle},releaseSessionHandle:e=>{let o=F(e);if(!i||o?.app!==f)return;let t=i.entryFor(o.key);t&&i.release(t)},speechSessionHandle:async e=>(await n.speechHandleFor(e)).handle,evictSpeechSession:async e=>{let{app:o,entry:t}=await n.sessionForHandle(e);await n.evict(o,t)},createResponseOn:async(e,o,t)=>{let m=await h(e);await b(m.session);let P=t!==void 0&&g(e)?new k({...m.session,consumerId:t}):m.responses;return N(await P.responses.create(o),m.gone)},onSessionEnd:async(e,o)=>{let t=g(e);if(t)return t.entry.gone.onGone(O=>o({timeLeftMs:null,reason:O.message}));let{entry:m}=await n.sessionForHandle(e),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 A=P.endsAt??null;o({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}export{Ke as a,Je as b,Xe as c,Ye as d,Qe as e};
|
package/dist/chunk-NN6TQQUG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as i}from"./chunk-YSFSRI3D.js";i();function m(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 y(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 _(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 k="llm-resp";async function*w(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 _(r);return}}}async function*g(e,t){let o=`${k}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*w(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var f=class e{constructor(t,o=e.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let t=this.session.doc("llm");if(t.synced===!0||typeof t.onSynced!="function")return;let o;await new Promise((s,r)=>{let a=t.onSynced(()=>{clearTimeout(o),s()});o=setTimeout(()=>{a(),r(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}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=y(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=m(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}async writeGated(t,o){try{await this.ensureDocSynced()}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{m as a,y as b,_ as c,w as d,g as e,f};
|
package/dist/chunk-OOCRI7ZM.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
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,r,o,i,l,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let a=new Date(Date.UTC(t,r-1,o,i,l,d));return a.getUTCFullYear()===t&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===i&&a.getUTCMinutes()===l&&a.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:r,regions:o,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(r))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let l=r.map((d,a)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(d)}`);let s=d;for(let c of["model_id","variant","app_slug","function"])if(typeof s[c]!="string"||s[c].length===0)throw new p(`catalog shared endpoints[${a}] (${JSON.stringify(s)}) has no valid "${c}"`);if(s.app_id!==void 0&&s.app_id!==null&&(typeof s.app_id!="string"||s.app_id===""))throw new p(`catalog shared endpoints[${a}] (${s.model_id}:${s.variant}) carries a malformed "app_id": ${JSON.stringify(s.app_id)}`);let u=(c,g)=>{if(s[c]!==void 0&&s[c]!==null&&!g)throw new p(`catalog shared endpoints[${a}] (${s.model_id}:${s.variant}) carries a malformed "${c}": ${JSON.stringify(s[c])}`)};u("ready",typeof s.ready=="boolean"),u("ready_runtimes",typeof s.ready_runtimes=="number"&&Number.isInteger(s.ready_runtimes)&&s.ready_runtimes>=0),u("ready_since",ve(s.ready_since));for(let c of["model_id","variant"]){let g=s[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${a}] 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 s.output_free=="boolean"),s});if(o!=null&&(!Array.isArray(o)||!o.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);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 a of Object.keys(d))if(a!=="zdr"&&a!=="hipaa")throw new p(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return l.length===0?null:{shared_org_id:t,endpoints:l,...o!=null?{regions:o}:{},...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 D(n,e,t){let r=(e??"").trim();if(r==="")return null;let o=r,i=t,l=r.lastIndexOf(":");l>0&&(o=r.slice(0,l),i=r.slice(l+1));let d=n.endpoints.filter(s=>s.model_id===o);if(d.length===0)return null;if(i!==void 0){let s=d.find(u=>u.variant===i);return s?{shared_org_id:n.shared_org_id,endpoint:s}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let a=d.filter(s=>s.compat_default===!0);if(a.length!==1)throw new p(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${d.map(s=>s.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:a[0]}}async function We(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${r.status}`);return Re(await r.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 r=typeof n=="string"?Date.parse(n):NaN;if(!Number.isFinite(r))throw new _(`${e}: ${t} is not a parseable timestamp (${JSON.stringify(n)})`);return r}function Te(n,e,t){return n===null?null:X(n,e,t)}function $e(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((o,i)=>i.effective_at>o.effective_at?i:o,n[0]),r=n.find(o=>o.effective_at===t.effective_at&&o.usd!==t.usd);return r?{reason:`two ${e} rates are effective at the same instant (${t.usd} and ${r.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 K(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 r=n[t],o=`model_prices[${t}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new _(`${o} is not an object: ${JSON.stringify(r)}`);let i=r;for(let s of Q.split(","))if(!Object.hasOwn(i,s))throw new _(`${o} has no "${s}" column: ${JSON.stringify(i)}`);let l=$e(i.unit,o);if(l===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${o} has no model_id (${JSON.stringify(i)})`);let a=i.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new _(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:d,variant:a,side:l,usd:Se(i.price_usd,o),effective_at:X(i.effective_at,o,"effective_at"),expires_at:Te(i.expires_at,o,"expires_at")})}return e}function Z(n,e=Date.now(),t){let r=new Map,o=new Map;for(let a of n){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let s=r.get(a.model_id);s||(s=new Map,r.set(a.model_id,s),o.set(a.model_id,new Map));let u=a.variant??"",c=s.get(u);c||(c={input:[],output:[]},s.set(u,c),o.get(a.model_id).set(u,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let i=[],l=[];for(let[a,s]of r){let u=s.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(K(a,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 o.get(a)){let v=s.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){l.push({model_id:a,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){l.push({model_id:a,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:a,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(a,s)=>a.model_id.localeCompare(s.model_id)||(a.variant===null?1:0)-(s.variant===null?1:0)||(a.variant??"").localeCompare(s.variant??"");return{prices:i.sort(d),refusals:l.sort(d)}}function A(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===e);if(r)return r.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===null);return o?o.pricing:null}var E={prices:[],refusals:[]};async function et(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,r=await e(`${n.catalogUrl}/model_prices?select=${Q}&unit=in.(${t})`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`},signal:AbortSignal.timeout(be)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Pe(await r.json())}w();var st="/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=[],r=[];for(let o of n){let i=Object.hasOwn(te,o)?te[o]:null;if(i===null){r.push(o);continue}t.some(d=>d.region===o)||t.push({country_code:i,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.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("/"),r=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let i=r[o];if(Object.hasOwn(ne,i))return ne[i];let l=r[o+1];if(i==="llama"&&l!==void 0&&Object.hasOwn(re,l))return re[l];if(i==="phi"&&l!==void 0&&/^\d/.test(l))return"Phi"}return null}var Me=["context_length","max_model_len"];function Oe(n){let e=Me.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(Oe),t=e[0];return t==null?null:e.every(r=>r===t)?t:null}function Ie(n){let e=n.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function J(n){if(n.length===0)return null;let e=n.map(Ie),t=e[0];return t==null?null:e.every(r=>r===t)?t:null}function B(n,e){let t=e.filter(o=>o.serve_app_slug===n);return new Set(t.map(o=>o.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 M(t);let r=e.filter(i=>h(i.model_id)===n);if(r.length>0)return M(r);let o=B(n,e);return o.length>0?M(o):null}function M(n){let e=n[0];return n.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(n){let e=n[0],t=r=>n.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]: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 T=class extends Error{name="ModelCreatedError"};function $(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 T(`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 r=t[0];if(!t.every(u=>u===r))throw new T(`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 o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new T(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(o[1]),l=Number(o[2]),d=Number(o[3]),a=Date.UTC(i,l-1,d),s=new Date(a);if(s.getUTCFullYear()!==i||s.getUTCMonth()!==l-1||s.getUTCDate()!==d)throw new T(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/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 r=Ne(n,e);if(!r)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:o,matches:i}=r,l=N(i),d=$(i),a=A(o.model_id,o.variant,t),s=se(o,i),u=J(i);return b({id:n,object:"model",created:d,owned_by:"urun",...l!==null?{context_length:l}:{},...a!==null?{pricing:a}:{},...s.published.length>0?{voices:[...s.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),r=t[0];if(Array.isArray(r)&&r.length>0&&r.every(i=>typeof i=="string")&&t.every(i=>Array.isArray(i)&&i.length===r.length&&i.every((l,d)=>l===r[d])))return{published:[...r],defect:null};let o=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:o}:{published:[],defect:o}}function z(n){let e=n.length>0?M(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="",r="",o=""]=e,i=t+r,l=t.length-6+(o===""?0:Number(o));return(l<=0?`0.${"0".repeat(-l)}${i}`:`${i.slice(0,l)}.${i.slice(l).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,r){if(e.length===0)return null;let o=M(e);if(!o)return null;let{row:i,matches:l}=o;if(!i.task||xe[i.task]!==!0)return null;let d=N(l),a=A(i.model_id,i.variant,t),s=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:$(l),quantization:Ce(i.variant),...s!==null?{tokenizer:s}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...a?{pricing:ie(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:ie(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function ae(n,e,t,r){let o=r??(s=>console.warn(s.trimEnd())),i=n?S(n):[];if(i.length>0){let s=i.filter(u=>u.ready===void 0);if(s.length===i.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(s.length>0){let u=s.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let l={datacenters:Ae(n?.regions,o),compliance:n?.compliance??null},d=[],a=new Set;for(let s of i){let u=`${s.model_id}:${s.variant}`;if(a.has(u))continue;a.add(u);let c=De(s,e.filter(g=>g.model_id===s.model_id&&g.variant===s.variant),t,l);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 r=!1,o=l=>{r||(r=!0,e.removeEventListener("abort",i),t(l))},i=()=>o("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>o("pulled"),()=>o("pulled"))})}function dt(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*r(){let o=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ue(e);let i=o.next();if(e!==void 0&&await Ue(i,e)==="aborted")throw i.catch(()=>{}),ue(e);let l=await i;if(l.done)return;yield je(l.value)}}finally{let i=o.return?.();i&&i.catch(()=>{})}}return r()}var wt="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 Je(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 _t(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.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]],r=!1;for(let[o,i]of t){let l=n[o];if(l==null)continue;let d=typeof l=="number"?l:typeof l=="string"?Number.parseInt(l,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(l)})
|
|
3
|
-
`),r=!0;break}e[o]=d}return r||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(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),t||(t=n.find(r=>r.serve_app_slug===e.appSlug||h(`${r.model_id}-${r.variant}`)===e.appSlug||h(r.model_id)===e.appSlug)),t?Be(t.engine_args?.pool):null}function H(n,e,t,r,o){if(!o)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=r.filter(l=>l.model_id===e&&l.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(o=>(o.task??void 0)==="image"))return[];let t=e.map(o=>o.engine_args?.expects_image),r=t[0];if(typeof r!="boolean"||!t.every(o=>o===r))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[r===!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 r=e.filter(i=>h(i.model_id)===n);return new Set(r.map(i=>i.variant)).size===1?r:[]}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(r=>r===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(o=>(o.task??void 0)===e),r=e===void 0?void 0:Ge[e];return r!==void 0?t?r:null:t&&n.every(o=>o.engine_args?.realtime===!0)?"decision":null}function we(n,e){let t=V(n,e);return t.length>0?t:B(n,e)}function O(n,e){return we(n.appSlug,e)}function Ve(n){let e=n.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(r=>r===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,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{o.refreshing=void 0}})()),o.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(o){if(o instanceof _)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
4
|
-
`),E}let r=Z(t,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
|
|
5
|
-
`);return r}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let r of e.endpoints)r.output_free===!0&&t.add(K(r.model_id,r.variant));return t}warn(e){(this.opts.warn??(r=>console.warn(r.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 o of this.servable(await this.deployedApps()))t.add(o);for(let o of this.pool.keys())o.startsWith(ye)||o.startsWith(fe)||t.add(o);let r=[...t].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let t=await this.availableIds(),r=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: ${r}`:`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: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let r=D(t,e);if(r)return r;let o=e.lastIndexOf(":"),i=o>0?e.slice(0,o):e,l=o>0?e.slice(o+1):void 0,d=h(i),a=t.endpoints.filter(c=>h(c.model_id)===d&&(l===void 0||c.variant===l)),s=new Set(a.map(c=>c.model_id)),u=[...s][0];return u===void 0||s.size!==1?null:D(t,u,l)}async resolveTarget(e){let t=(e??"").trim(),r=this.opts.defaultApp;if(!t||t==="urun")return r===null?this.noDefaultApp(t):{appSlug:r};let o=h(t);if(o===r)return{appSlug:r};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(o))return{appSlug:o};if(this.opts.listApps){let l=await this.deployedApps(),d=this.servable(l);if(d.includes(o))return{appSlug:o};let a=d.filter(u=>u.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let s=l.find(u=>u.app_slug===o||u.app_slug.startsWith(`${o}-`));if(s)throw new P(`model "${t}" maps to app "${s.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(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||o===h(a.model_id)||o===h(`${a.model_id}-${a.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 r===null?this.noDefaultApp(t):{appSlug:r}}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 r=this.pool.get(t);return r||(r=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,r),r.catch(()=>this.pool.delete(t))),{app:t,entry:await r,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 r=t(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:t,entry:r}=await this.sessionFor(e);return{app:t,handle:ce(t,this.keyOf(r))}}async speechHandleFor(e){let{app:t,entry:r}=await this.speechSessionFor(e);return{app:t,handle:ce(t,this.keyOf(r))}}async sessionForHandle(e){let t=Je(e);if(!t)throw new I(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=t,i=this.pool.get(r),l=i?await i.then(d=>d,()=>null):null;if(l===null)throw new I(`the session behind this handle (app "${r}") 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(l)!==o)throw new I(`the session behind this handle (app "${r}") 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:r,entry:l}}async evict(e,t){let r=this.pool.get(e);!r||await r.then(i=>i,()=>null)!==t||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(s=>({ok:!0,rows:s}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=r.rows,l=r.ok?o:E;r.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 a=(t?S(t):[]).map(s=>{let u=i.filter(W=>W.model_id===s.model_id&&W.variant===s.variant),c=N(u),g=$(u),f=J(u),v=A(s.model_id,s.variant,l),m=z(u);return b({id:`${s.model_id}:${s.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?a:[...e.map(s=>L(s,i,l)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[t,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ae(e,t,r,o=>this.warn(o))}async supportsImages(e,t){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let i=H(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return ge(`${r.modelId}:${r.variant}`,i).includes(t)}return pe(V(r.appSlug,o)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),r=await this.catalogRows();return t.sharedApp?R(r.filter(o=>o.model_id===t.modelId&&o.variant===t.variant))!==null:R(O(t,r))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),r=await this.catalogRows();return t.sharedApp?R(r.filter(o=>o.model_id===t.modelId&&o.variant===t.variant))==="tts":R(O(t,r))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),r=await this.catalogRows();return t.sharedApp?R(r.filter(o=>o.model_id===t.modelId&&o.variant===t.variant))==="stt":R(O(t,r))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),r=await this.catalogRows(),o=t.sharedApp?r.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):O(t,r);return Ve(o)}async speechVoices(e){let t=await this.resolveTarget(e),r=await this.catalogRows(),o=t.sharedApp?r.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):O(t,r);return z(o)}async imageModelList(){let e=await this.catalogRows(),t=E,r=[];for(let i of await this.availableIds()){let l=pe(V(i,e));l.length!==0&&r.push(b({...L(i,e,t),image_modes:l}))}let o=await this.sharedBlock();if(o)for(let i of S(o)){let l=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=ge(`${i.model_id}:${i.variant}`,l);if(d.length===0)continue;let a=b({id:`${i.model_id}:${i.variant}`,object:"model",created:$(l),owned_by:"urun",image_modes:d});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,r=[];for(let i of await this.availableIds())R(we(i,e))==="stt"&&r.push(L(i,e,t));let o=await this.sharedBlock();if(o)for(let i of S(o)){let l=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(l)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:$(l),owned_by:"urun"});r.push(d)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){t.push(String(o instanceof Error?o.message:o))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,We as b,et as c,st as d,T as e,dt as f,wt as g,P as h,I as i,ce as j,Je as k,_t as l,ze as m,fe as n,q as o,he as p,me as q};
|