@urun-sh/openai 0.6.39 → 0.6.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{chunk-USLITFIB.js → chunk-BWYY4IPR.js} +1 -1
  2. package/dist/chunk-G5VRFFBE.js +64 -0
  3. package/dist/chunk-G7CSAISC.js +1 -0
  4. package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
  5. package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
  6. package/dist/chunk-L6CT7ZVO.js +23 -0
  7. package/dist/chunk-PT5N7AY7.js +2 -0
  8. package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
  9. package/dist/chunk-Z3QCHKJB.js +1 -0
  10. package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
  11. package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +2 -2
  14. package/dist/gemini-live.d.ts +2 -2
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +48 -48
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +46 -46
  19. package/dist/hosted/index.d.cts +3 -3
  20. package/dist/hosted/index.d.ts +3 -3
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/pi-extension/index.js +1 -1
  27. package/dist/pi-extension/standalone.cjs +56 -56
  28. package/dist/pooler/bin.cjs +7 -7
  29. package/dist/pooler/bin.js +25 -25
  30. package/dist/proxy/cli.cjs +51 -51
  31. package/dist/proxy/cli.js +1 -1
  32. package/dist/proxy/index.cjs +26 -26
  33. package/dist/proxy/index.d.cts +35 -5
  34. package/dist/proxy/index.d.ts +11 -5
  35. package/dist/proxy/index.js +1 -1
  36. package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
  37. package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
  38. package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
  39. package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
  40. package/package.json +3 -3
  41. package/dist/chunk-4XOYE4A7.js +0 -23
  42. package/dist/chunk-6M5JK4YC.js +0 -1
  43. package/dist/chunk-7IWRLQOZ.js +0 -64
  44. package/dist/chunk-DO6EIHE5.js +0 -2
@@ -1,10 +1,10 @@
1
1
  import { IncomingMessage, Server } from 'node:http';
2
- import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-F94H40CD.cjs';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-F94H40CD.cjs';
4
- export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CO8W_hmJ.cjs';
2
+ import { P as ProxyClients, h as ProxyVideoLane, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-B-F2J0NK.cjs';
3
+ export { D as DialObserver, a as DialReport, g as ProxyIdentity, i as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-B-F2J0NK.cjs';
4
+ export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-Dox25ky9.cjs';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.cjs';
7
- import '../video-out-BsuLqlID.cjs';
7
+ import '../video-out-DnCKUUO2.cjs';
8
8
  import '../types-CHPtJx6d.cjs';
9
9
 
10
10
  /**
@@ -102,6 +102,17 @@ interface RealtimeBinding<S = unknown> {
102
102
  };
103
103
  /** `model` the binding names for this conversation (overrides session config default). */
104
104
  model?: string;
105
+ /**
106
+ * The NATIVE video frame lane (the §5 `rt-video-in` named-DATA path —
107
+ * enableSessionVideo on a pooled session, the lane stream relay's
108
+ * `rt-video-in` channel on a proxy-hosted lane), resolved on the SAME
109
+ * pooled session identity the voice binding rides. LAZY: the lane opens on
110
+ * the first `conversation.item.create` `input_image` frame, never at
111
+ * binding time. Optional at the seam: an absent opener means the embedder
112
+ * wired no video seam — the connection answers image frames with the LOUD
113
+ * error event, never a silent drop.
114
+ */
115
+ video?: () => Promise<ProxyVideoLane>;
105
116
  /**
106
117
  * The GA transcription-session intent (`?intent=transcription`): this
107
118
  * connection is a TRANSCRIPTION session — transcription events flow
@@ -498,6 +509,13 @@ declare class OpenAIRealtimeConnection<S = unknown> {
498
509
  /** Uncommitted input audio (base64 PCM16 chunks) held locally until commit. */
499
510
  private pendingAudioBytes;
500
511
  private pendingAudioTotalBytes;
512
+ /**
513
+ * The rt-video-in media lane (the binding's video seam), opened LAZILY on
514
+ * the first `input_image` frame (the Gemini Live pattern) and cached for
515
+ * every later one. A failed open clears the cache so a later frame can
516
+ * retry — a rejected cached promise would poison every later frame forever.
517
+ */
518
+ private videoLane;
501
519
  /** Committed audio of the frozen turn, dispatched at response.create. */
502
520
  private frozenAudio;
503
521
  private inFlight;
@@ -781,6 +799,18 @@ declare class OpenAIRealtimeConnection<S = unknown> {
781
799
  */
782
800
  private cancelResponse;
783
801
  private pushItem;
802
+ /**
803
+ * THE CAMERA-FRAME PATH (GA `input_image` on conversation.item.create): the
804
+ * data URI's image bytes ride the rt-video-in media lane (the SAME
805
+ * named-DATA frame path the Gemini Live lane's realtimeInput.video rides) —
806
+ * the runtime folds them into its rolling media window the way the REST
807
+ * path builds media. Frames are forwarded LIVE — no hold/commit machinery:
808
+ * video is ambient context, not a turn's audio, and the runtime's media
809
+ * window keeps the LATEST frame (latest-frame-wins; nothing queues). The
810
+ * lane opens LAZILY on the first frame; a failed open clears the cache so a
811
+ * later frame can retry — never a poisoned cached promise.
812
+ */
813
+ private forwardImageFrames;
784
814
  private itemToProtocol;
785
815
  private send;
786
816
  /**
@@ -874,7 +904,7 @@ declare function realtimeModelOf(req: IncomingMessage): string | undefined;
874
904
  * and the bridge opens — a refused upgrade admits nothing. On an stt row
875
905
  * the intent is recorded on the binding (a transcription session).
876
906
  */
877
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
907
+ declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
878
908
  /**
879
909
  * The LOCAL lane resolver: fixed pooled clients, optional fixed apiKey (the
880
910
  * same shared-secret rule the local Gemini Live lane applies — a mismatched
@@ -1,10 +1,10 @@
1
1
  import { IncomingMessage, Server } from 'node:http';
2
- import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-ClDE3ViI.js';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-ClDE3ViI.js';
4
- export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-Ddd65sXR.js';
2
+ import { P as ProxyClients, h as ProxyVideoLane, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-B--rGI5m.js';
3
+ export { D as DialObserver, a as DialReport, g as ProxyIdentity, i as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-B--rGI5m.js';
4
+ export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-BqpmZ-vh.js';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.js';
7
- import '../video-out-Cawtm7SF.js';
7
+ import '../video-out-REmiQMBJ.js';
8
8
  import '../types-CHPtJx6d.js';
9
9
 
10
10
  declare const OPENAI_REALTIME_PATH = "/v1/realtime";
@@ -34,6 +34,8 @@ interface RealtimeBinding<S = unknown> {
34
34
 
35
35
  model?: string;
36
36
 
37
+ video?: () => Promise<ProxyVideoLane>;
38
+
37
39
  intent?: 'transcription';
38
40
 
39
41
  resumed?: boolean;
@@ -125,6 +127,8 @@ declare class OpenAIRealtimeConnection<S = unknown> {
125
127
  private pendingAudioBytes;
126
128
  private pendingAudioTotalBytes;
127
129
 
130
+ private videoLane;
131
+
128
132
  private frozenAudio;
129
133
  private inFlight;
130
134
  private activeResponseId;
@@ -223,6 +227,8 @@ declare class OpenAIRealtimeConnection<S = unknown> {
223
227
 
224
228
  private cancelResponse;
225
229
  private pushItem;
230
+
231
+ private forwardImageFrames;
226
232
  private itemToProtocol;
227
233
  private send;
228
234
 
@@ -234,7 +240,7 @@ declare class OpenAIRealtimeConnection<S = unknown> {
234
240
 
235
241
  declare function realtimeModelOf(req: IncomingMessage): string | undefined;
236
242
 
237
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
243
+ declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
238
244
 
239
245
  declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
240
246
  resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<ProxyClients>>;
@@ -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-7IWRLQOZ.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-USLITFIB.js";import{i as r,j as i}from"../chunk-7AI75MPZ.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};
1
+ import{F as I,a as n,b as p,c as m,l,m as a,n as x,p as s,s as O,t as f}from"../chunk-G5VRFFBE.js";import{a as o,h as t}from"../chunk-QTHFMDZY.js";import"../chunk-Z3QCHKJB.js";import"../chunk-BWYY4IPR.js";import{i as r,j as i}from"../chunk-HPUX2H65.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};
@@ -1,4 +1,4 @@
1
- import { k as VideoOutRecord } from './video-out-Cawtm7SF.js';
1
+ import { k as VideoOutRecord } from './video-out-REmiQMBJ.js';
2
2
 
3
3
  declare const GEMINI_LIVE_PATH = "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
4
4
 
@@ -1,4 +1,4 @@
1
- import { k as VideoOutRecord } from './video-out-BsuLqlID.cjs';
1
+ import { k as VideoOutRecord } from './video-out-DnCKUUO2.cjs';
2
2
 
3
3
  /**
4
4
  * Gemini Live (BidiGenerateContent) ⇄ uRun Responses translation — PURE
@@ -35,9 +35,22 @@ declare class AudioBridge {
35
35
  private source;
36
36
  private sink;
37
37
  private outHandlers;
38
+ /**
39
+ * The §5 DATA emit seam for the audio lane (wired by {@link enableSessionAudio}
40
+ * off `session.stream('audio').emit`). `null` = the stream surface has no
41
+ * data-produce seam (legacy construction); appends then publish RTP only.
42
+ */
43
+ private dataEmit;
44
+ /** Serializes DATA emits so appends reach the wire in order, never unbounded. */
45
+ private dataEmitChain;
46
+ private dataEmitFailures;
38
47
  constructor(backend: AudioBackend, opts: {
39
48
  sampleRate: number;
40
49
  });
50
+ /**
51
+ * Wire the §5 DATA audio emit (see {@link enableSessionAudio}). Idempotent.
52
+ */
53
+ setDataEmit(emit: ((payload: Buffer) => Promise<void>) | null): void;
41
54
  startOutbound(): Promise<unknown>;
42
55
  /** OpenAI: input_audio_buffer.append (base64 PCM16) → publish frames. */
43
56
  appendInputAudio(base64Pcm16: string): void;
@@ -22,9 +22,16 @@ declare class AudioBridge {
22
22
  private source;
23
23
  private sink;
24
24
  private outHandlers;
25
+
26
+ private dataEmit;
27
+
28
+ private dataEmitChain;
29
+ private dataEmitFailures;
25
30
  constructor(backend: AudioBackend, opts: {
26
31
  sampleRate: number;
27
32
  });
33
+
34
+ setDataEmit(emit: ((payload: Buffer) => Promise<void>) | null): void;
28
35
  startOutbound(): Promise<unknown>;
29
36
 
30
37
  appendInputAudio(base64Pcm16: string): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.39",
3
+ "version": "0.6.40",
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.39"
73
+ "@urun-sh/core": "^0.6.40"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",
@@ -97,7 +97,7 @@
97
97
  "ajv-formats": "^3.0.1",
98
98
  "esbuild": "^0.28.1",
99
99
  "fengari": "^0.1.5",
100
- "happy-dom": "^20.9.0",
100
+ "happy-dom": "21.0.4",
101
101
  "opusscript": "^0.1.1",
102
102
  "reflect-metadata": "^0.2.2",
103
103
  "tsup": "^8.5.0",
@@ -1,23 +0,0 @@
1
- import{a as vt,c as Pe,d as _t,e as Te}from"./chunk-DO6EIHE5.js";import{A as gt,B as mt,C as yt,D as wt,b as Qe,d as Ze,e as W,j as et,k as tt,m as rt,n as ot,o as st,p as it,q as at,r as lt,t as ct,u as ne,v as dt,w as ut,x as ft,y as pt,z as ht}from"./chunk-7IWRLQOZ.js";import{a as Xe}from"./chunk-3JWYIKHM.js";import{a as bt}from"./chunk-5MH6NSR2.js";import{l as nt,m as te}from"./chunk-USLITFIB.js";import{a as St,c as Y,e as Ne}from"./chunk-KKCUIOL4.js";import{a as ze}from"./chunk-4NMMWAKD.js";import{b as Ve,d as Le}from"./chunk-GX243AIV.js";import{e as Ye,j as ee,n as qe,o as Ae,p as Ce}from"./chunk-7AI75MPZ.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as F,Gauge as re,Histogram as oe,Registry as ln,collectDefaultMetrics as cn}from"@prometheus-io/client";import{createServer as dn}from"http";var to=9464,kt="/metrics",se="(other)",un="(none)",fn=64,pn=128,hn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",ct,ut,Ye],gn=new Set(hn);function mn(t){return gn.has(t)?t:se}function yn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var ie=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?un:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,se):(this.admitted.add(e),e):se}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ae=class{registry=new ln;modelLabel=new ie(fn);orgLabel=new ie(pn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new re({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 F({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 oe({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 oe({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 F({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 F({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 F({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 ft)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new re({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"},pt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ht()/1e3)}}),this.labelCardinality=new re({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 F({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 re({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 oe({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 oe({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 F({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 F({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&cn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=mn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let g=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?se:e.method,status_class:yn(e.status),stream:g,model:i,org:s}),this.duration.observe({lane:n,stream:g,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Et(t){return dn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==kt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${kt}
2
- `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
- `);return}n.end()})})}L();import{createHash as Lt}from"crypto";import{createServer as wn}from"http";var io=9465,bn="x-urun-key-id",vn="x-urun-key-fingerprint",_n="urun-ratelimit-bucket:",Sn="urun-ratelimit-tier:",Rt="anonymous",kn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function En(t){return Lt("sha256").update(`${_n}${t}`).digest("hex")}function Rn(t){return Lt("sha256").update(`${Sn}${t}`).digest("hex")}function Ln(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return kn.test(n)?n:null}function At(){return wn((t,e)=>{let n=Ln(t.headers.authorization);e.setHeader(bn,n===null?Rt:En(n)),e.setHeader(vn,n===null?Rt:Rn(n)),e.writeHead(200),e.end()})}L();import{createClientToken as An,ClientTokenError as Cn}from"@urun-sh/core";import{createPublicKey as Pn,verify as Tn}from"crypto";var Ct="urun-session-gateway",Nn="machine",Un=3e5;function In(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var P=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},D=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function de(t){let e=(t??"").trim();if(e==="")throw new P("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new P("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var On=60,xn=6e4,$n=4096;function Dn(t){return t===401||t===403}var le=class{constructor(e){this.opts=e;this.mint=e.mint??An,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new P("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<xn)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:On});r=i.orgId,o={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Cn&&Dn(i.status)?(this.cache.delete(e),new P("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new D("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}: ${i instanceof Error?i.message:String(i)}`)}if(!r)throw new D("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>=$n){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function Pt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var ce=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<Un)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(s){throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${s instanceof Error?s.message:String(s)}`)}if(!o.ok)throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let i;try{let s=await o.json();if(!Array.isArray(s.keys))throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);i=s.keys}catch(s){throw s instanceof D?s:new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return i})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new P("malformed machine token");let i,s;try{i=Pt(n),s=Pt(r)}catch{throw new P("malformed machine token")}if(i.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(i.alg??null)})`);let a=typeof i.kid=="string"?i.kid:"",g=typeof s.iss=="string"?s.iss:"";if(g===""||!this.opts.issuers.includes(g))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(g)})`);if(s.aud!==Ct)throw new P(`machine token audience must be ${Ct} (got ${JSON.stringify(s.aud??null)})`);if(s.token_use!==Nn)throw new P(`bearer is a ${JSON.stringify(String(s.token_use??""))} token, not a machine token`);let d=typeof s.org_id=="string"?s.org_id:"";if(d==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");if((typeof s.exp=="number"?s.exp:0)<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let m=u=>u.kty==="RSA"&&u.n!==void 0&&u.e!==void 0,l=await this.jwksKeys(!1),p=a===""?void 0:l.find(u=>u.kid===a&&m(u));if(p===void 0&&(l=await this.jwksKeys(!0),p=a===""?void 0:l.find(u=>u.kid===a&&m(u))),p===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let R=Buffer.from(`${n}.${r}`,"ascii"),E=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),y=!1;try{let u=Pn({key:p,format:"jwk"});y=Tn("RSA-SHA256",R,u,E)}catch{y=!1}if(!y)throw new P("machine token signature failed verification");return{apiKey:e,orgId:d,credential:"machine"}}};function Ue(t,e,n){return n!==null&&In(t)?n.verify(t):e.resolve(t)}L();var Hn=8080,Ie="serve",go="0.0.0.0";function Mn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function mo(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Hn:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=nt(te(Mn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?te(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.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 g=s?{catalogUrl:te(s,"URUN_CATALOG_URL"),anonKey:a}:null,d=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),c=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!d!=!!c)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 m=d?{keyId:c,key:d}:void 0,l={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},p=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],R=p.filter((w,k)=>Object.values(l)[k]==="");if(R.length!==0&&R.length!==p.length)throw new Error(`${p.join(", ")} must be set together (or all left unset) \u2014 missing: ${R.join(", ")}, which would half-configure the lane plane`);let E=R.length===0?l:void 0,y={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},u=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],h=u.filter((w,k)=>Object.values(y)[k]==="");if(h.length!==0&&h.length!==u.length)throw new Error(`${u.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the pooler cutover`);let v=h.length===0?y:void 0,_={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},b=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],N=b.filter((w,k)=>Object.values(_)[k]==="");if(N.length!==0&&N.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${N.join(", ")}, which would half-configure the machine-identity rung`);let $=_.issuers.split(",").map(w=>w.trim()).filter(w=>w!=="");if($.length===0&&N.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let f=Number(_.tokenTtlS);if(N.length===0&&(!Number.isFinite(f)||f<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(_.tokenTtlS)}`);let S=N.length===0?{jwksBaseUrl:_.jwksBaseUrl,issuers:$,tokenTtlS:f}:void 0;return{port:n,baseUrl:r,apiUrl:i,catalog:g,ledgerSigning:m,lane:E,pooler:v,machine:S}}L();import{createHash as zn,randomUUID as It}from"crypto";L();import{request as Fn}from"http";var Wn="/pooler/v1/inference",G=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterSeconds=i;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Gn=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Kn=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Nt=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Bn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Nt(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new G(t.status,e,n,t.retryAfterSeconds)};async function jn(t,e,n,r,o){let i=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Wn}`),s=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Gn(e),firstMessage:Kn(e)}});return new Promise((a,g)=>{let d=Fn({hostname:i.hostname,port:i.port===""?void 0:Number(i.port),path:`${i.pathname}${i.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(s))}},c=>{let m=Number(c.headers["retry-after"]??"");a({status:c.statusCode??0,retryAfterSeconds:Number.isFinite(m)?m:void 0,body:c})});d.on("error",c=>g(new G(502,"pooler_unreachable",`the pooler channel failed: ${c.message}`))),d.end(s)})}var Tt=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Jn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
4
-
5
- `);if(o===-1)break;let i=e.slice(0,o);e=e.slice(o+2);let s=Tt(i);s!==null&&(yield s)}let n=Tt(e);n!==null&&(yield n)}async function Ut(t,e,n,r){let o=Ve(e,n,r),i=o.model??"";if(i==="")throw new G(400,"missing_model","the pooler submit requires a model");let s=await jn(t,o,n,i,e.stream===!0);if(s.status>=400)throw await Bn(s);let a=e.stream===!0?Le(n,Jn(s)):await Vn(s,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Vn(t,e){let n=await Nt(t.body),r=null;try{let i=JSON.parse(n);i!==null&&typeof i=="object"&&(r=i)}catch{r=null}if(r===null)throw new G(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Le(e,(async function*(){yield o})())}var Yn=512;function Oe(t){return`urun-inference-proxy-${zn("sha256").update(t).digest("hex").slice(0,32)}`}var ue=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),i=this.opts.pooler;if(i===void 0)return o;let s=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,g)=>{if(s!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,g)}catch(m){if(!(m instanceof W))throw m}let d=`px_${It()}`;return Ut(i,a,d,d)}})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e,i.router),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ie,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:vt(process.env,process.env.HOSTNAME)??void 0},r=Pe(n),o=n.decisionPool?_t(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Te(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Yn;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ot=512,qn=1024,fe=class extends Error{constructor(){super(`conversation capacity reached (${Ot} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Xn(t){return{sessionStartOptions:e=>{if(e.startsWith(Ae)||e.startsWith(Ce))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Ae)||e.startsWith(Ce)||t.set(e,n)}}}function Qn(t,e,n,r){let o=Pe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ie,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Xn(r)});return{clients:Te(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var pe=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Oe(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Qn(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Ot;){let e=this.byCaller.keys().next();if(e.done)throw new fe;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new fe;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,It())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),dedicatedSessionHandle:s=>{let a=o().backhaul.clients.dedicatedSessionHandle;return a===void 0?o().backhaul.clients.sessionHandle(s):a(s)},releaseSessionHandle:s=>o().backhaul.clients.releaseSessionHandle?.(s),createResponseOn:(s,a,g)=>o().backhaul.clients.createResponseOn(s,a,g),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let g=o().backhaul.clients.openAudio;if(g===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return g(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a,g)=>{let d=o().backhaul.clients.openAudioOn;if(d===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 d(s,a,g)},i.openTurnsOn=(s,a)=>{let g=o().backhaul.clients.openTurnsOn;if(g===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 g(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().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>=qn;){let g=this.byHandle.keys().next();if(g.done)break;this.byHandle.delete(g.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),g=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||g===void 0?void 0:g.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new ee("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=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var Zn="/inference-ledger",er=1e4,he=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},De=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},U=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},He=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Me=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},tr=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",xe],["output_minutes",xe],["cost_nano_usd",xe],["price_version",t=>t===null||typeof t=="string"]];function nr(t){for(let[e,n]of tr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function rr(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:nr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function xe(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function $e(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function or(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function xt(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function sr(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&xt(t.started_at,n.started_at)&&xt(t.completed_at,n.completed_at)&&$e(t.prompt_tokens,n.prompt_tokens)&&$e(t.completion_tokens,n.completion_tokens)&&$e(t.output_units,n.output_units)&&or(t.output_minutes,n.output_minutes)}function ir(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
6
- `)}async function ar(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(ir(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function lr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new U(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new U(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new U(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new U(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=d=>{if(!(d in n))throw new U(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let c=n[d];if(c===null)return null;if(typeof c!="string")throw new U(`${e} answered a non-string ${d}: ${JSON.stringify(c)}`);if(!/[^\s]/.test(c))throw new U(`${e} answered a BLANK ${d} (${JSON.stringify(c)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return c},s=i("price_version"),a=i("unpriced_reason"),g=o!=null;if(g&&(s===null||a!==null))throw new U(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!g&&(s!==null||a===null))throw new U(`${e} 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:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Zn}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ar(n,this.opts.signing)}):JSON.stringify(n)}catch(d){throw new U(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(er)})}catch(d){throw new U(`the uRun ledger surface at ${r} could not be reached: ${d instanceof Error?d.message:String(d)}`)}if(i.status===409){let d=await i.text().catch(()=>""),c=rr(d);throw c.status==="found"&&sr(n,c.row)?new De(c.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.`):c.status==="not_in_this_org"?new he(`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 he(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${c.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). ${d.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new He("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 d=await i.text().catch(m=>`<body unreadable: ${m instanceof Error?m.message:String(m)}>`),c;try{let m=JSON.parse(d);if(m!==null&&typeof m=="object"&&"error"in m){let l=m.error;l!==null&&typeof l=="object"&&"code"in l&&(c=l.code)}}catch{}throw c==="ledger_signature_invalid"?new Me(`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: `+d.slice(0,400)):new U(`the uRun ledger surface at ${r} answered HTTP ${i.status}: ${d.slice(0,400)}`)}let s;try{s=await i.json()}catch(d){throw new U(`the uRun ledger surface at ${r} answered a body that is not JSON: ${d instanceof Error?d.message:String(d)}`)}let a=s?.recorded;if(a===void 0)throw new U(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let g=lr(a,`the uRun ledger surface at ${r}`);if(g.inference_id!==n.inference_id)throw new U(`the uRun ledger surface at ${r} answered for inference_id ${g.inference_id} when asked about ${n.inference_id}`);return g}};L();import{createServer as Fr}from"http";L();import{createWebsocketDocConnector as mr}from"@urun-sh/core/internal";import yr from"ws";L();import*as K from"yjs";import{SessionDocumentImpl as cr}from"@urun-sh/core/internal";var dr=3e4;function ur(t){return(e,n,r)=>{let o=t(e);K.applyUpdate(n,K.encodeStateAsUpdate(o));let i=a=>K.applyUpdate(o,a),s=a=>K.applyUpdate(n,a);return n.on("update",i),o.on("update",s),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",i),o.off("update",s)}}}}function Fe(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?ur(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,i=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let m=r.get(c);return m||(m=new cr(c,e,n),r.set(c,m)),m},s=new Map,a=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let m=s.get(c);if(!m){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${c}"`);m=t.streamEndpoint(c),s.set(c,m)}return m},g=c=>{let m="llm-resp:";if(!c.startsWith(m))throw new Error(`lane session exposes no stream "${c}" \u2014 only the llm reply lanes (${m}<rid>)`);async function*l(){let p=a(c);try{yield*p.messages()}finally{s.delete(c),await p.close()}}return{messages:()=>l(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(c){return i(c)},stream:g,streamEndpoint:a,async end(){},async whenLive(c){let m=i("llm");if(m.synced===!0)return;let l=c?.timeout??t.whenLiveTimeoutMs??dr;await new Promise((p,R)=>{let E=setTimeout(()=>{y(),R(new Error(`lane ${e} llm doc never synced within ${l}ms`))},l),y=m.onSynced(()=>{clearTimeout(E),c?.signal?.removeEventListener("abort",u),p()}),u=()=>{clearTimeout(E),y(),R(c?.signal?.reason instanceof Error?c.signal.reason:new Error("aborted"))};c?.signal?.addEventListener("abort",u,{once:!0})})},destroy(){o=!0;for(let c of r.values())c.dispose();r.clear();for(let[c,m]of s)s.delete(c),m.close()}}}L();import me,{WebSocketServer as fr}from"ws";import{ENVELOPE_KIND as Ft,STREAM_END as pr,StreamFragmentReassembler as hr}from"@urun-sh/core";var $t="/stream/";function Dt(t){if(!t.startsWith($t))return null;let e=t.slice($t.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function be(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function ye(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>Ft.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var we=class{reassembler=new hr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===pr&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Ge=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let i=this.chan(e,n),s=[...i.peers].filter(a=>a!==r);if(s.length===0){let a=i.pending;(a.list.length>=Ht||a.bytes+o.byteLength>Mt)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Ht} frames / ${Mt} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of s)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let i=o.pending;if(i.list.length===0)return;let s=i.list.filter(a=>a.producer!==r);i.list=i.list.filter(a=>a.producer===r),i.bytes=i.list.reduce((a,g)=>a+g.envelope.byteLength,0);for(let{envelope:a}of s)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,i=this.channels.get(o);if(i){for(let s of[...i.peers])s===r&&i.peers.delete(s);i.peers.size===0&&i.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let i of o?.peers??[])i.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Ht=256,Mt=8*1024*1024,H=new Ge;function Wt(t,e){let n=new we,r={send(o){H.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{ye(o)}catch(i){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(i)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),H.detach(t,e,r)}};return H.attach(t,e,r),r}function gr(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function Gt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new me(r,be(e)),i=new we;return o.addEventListener("message",s=>{let a=new Uint8Array(s.data);try{ye(a)}catch(g){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(g)}`);return}i.push(i.feed(a))}),o.addEventListener("close",()=>{i.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{i.finish(new Error(`lane stream ${r} socket error`))}),{send(s){if(ye(s),o.readyState!==me.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(s,{binary:!0})},deliver(s){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>i.iterate(),async close(){i.finish();try{o.close(1e3)}catch{}}}}function We(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
7
- `;t.end(`HTTP/1.1 ${e} ${r}\r
8
- Connection: close\r
9
- Content-Type: text/plain; charset=utf-8\r
10
- Content-Length: ${Buffer.byteLength(o)}\r
11
- \r
12
- ${o}`)}function Kt(t,e){let n=e.heartbeatMs??3e4,r=new fr({noServer:!0,handleProtocols:(d,c)=>{let m=Dt(new URL(c.url??"/","http://localhost").pathname);if(!m)return!1;let l=be(m.name);return d.has(l)?l:!1}}),o=new Map,i=new Set,s=!1,a=(d,c,m,l)=>{let p={client:m,upstream:l,laneId:d,name:c};i.add(p);let R=E=>{if(i.delete(p)){console.warn(`[lane-stream] ${d}/${c}: host-affinity pump torn down (${E})`);for(let y of[m,l])try{(y.readyState===me.OPEN||y.readyState===me.CONNECTING)&&y.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let E=(y,u)=>{let h=!0;y.on("pong",()=>{h=!0});let v=setInterval(()=>{if(!h){console.warn(`[lane-stream] ${d}/${c}: pong timeout on ${u} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${u} dial never sends a close)`),clearInterval(v);try{y.terminate()}catch{}R(`${u} pong timeout`);return}h=!1;try{y.ping()}catch{}},n);v.unref?.();let _=()=>clearInterval(v);y.once("close",_),y.once("error",_)};E(m,"client"),E(l,"host")}m.on("message",E=>{try{l.send(E,{binary:!0})}catch(y){R(`upstream send failed: ${String(y)}`)}}),l.on("message",E=>{try{m.send(E,{binary:!0})}catch(y){R(`client send failed: ${String(y)}`)}}),m.on("close",()=>R("client socket closed")),m.on("error",()=>R("client socket error")),l.on("close",()=>R("host socket closed")),l.on("error",()=>R("host socket error"))},g=(d,c,m)=>{let l;try{l=new URL(d.url??"/","http://localhost")}catch{We(c,400,"malformed upgrade URL");return}c.on("error",()=>c.destroy());let p=Dt(l.pathname);p&&(s||c.destroyed||(async()=>{let R=l.searchParams.get("token")??"",E=null;try{E=R===""?null:await e.verifyToken(R,p.laneId,p.name)}catch{E=null}if(E===null){We(c,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let y=await e.hostOf(p.laneId).catch(()=>null);if(y&&y!==e.selfAddress)try{let u=await e.podToPodDial(p.laneId,p.name,y);r.handleUpgrade(d,c,m,h=>{a(p.laneId,p.name,h,u)});return}catch(u){console.warn(`[lane-stream] ${p.laneId}/${p.name}: host dial to ${y} failed (${String(u)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(d,c,m,y=>{let u=gr(y);if(o.set(y,u),H.attach(p.laneId,p.name,u),n>0){let v=!0;y.on("pong",()=>{v=!0});let _=setInterval(()=>{if(!v){console.warn(`[lane-stream] ${p.laneId}/${p.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(_),y.terminate();return}v=!1;try{y.ping()}catch{}},n);_.unref?.();let b=()=>clearInterval(_);y.once("close",b),y.once("error",b)}y.on("message",v=>{let _=new Uint8Array(v);try{ye(_)}catch(b){console.warn(`[lane-stream] ${p.laneId}/${p.name}: dropped malformed envelope: ${String(b)}`);return}H.deliver(p.laneId,p.name,u,_),_[1]===Ft.END&&H.detach(p.laneId,p.name,u)});let h=()=>{o.delete(y),H.detach(p.laneId,p.name,u)};y.on("close",h),y.on("error",h)})})().catch(()=>{c.destroyed||We(c,500,"lane stream upgrade failed")}))};return t.on("upgrade",g),{async close(){s=!0,t.off("upgrade",g),H.clear();for(let d of o.values())d.close(1001,"lane stream host shutting down");o.clear();for(let d of i)for(let c of[d.client,d.upstream])try{c.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}function wr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Ze(`the shared lane target (app slug "${t.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`${e}.${t.appId}.${t.fnName??""}`}function Bt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,i=new Map,s=(l,p,R,E,y)=>{let u=R?b=>Wt(l,b):b=>Gt(l,b,{hostUrl:`ws://${E}/stream/${l}`,token:()=>Y(l,t.tokenSecret,void 0,void 0,y)}),h=R?Fe({laneId:l,roomDoc:b=>t.roomDoc(l,b),streamEndpoint:u}):Fe({laneId:l,streamEndpoint:u,connector:mr({serverUrl:`ws://${E}/doc`,sessionId:l,token:()=>Y(l,t.tokenSecret,void 0,void 0,y),WebSocketPolyfill:yr})}),v=R?a(l):bt(h,`lane:${l}`,{armOnFirstSync:!0}),_={session:h,responses:new ze(h,{sessionTag:null}),gone:v,goneWatch:v,laneId:l,pool:p,inFlight:0,laneSession:h,self:R,host:E??""};return n.set(l,_),v.onGone(()=>g(_)),_},a=l=>{let p=null,R=!1,E=new Set,y=h=>{if(!p){p=h;for(let v of[...E])v(h);E.clear()}},u=t.hostedSignal?.(l,h=>{if(h){R=!0;return}R&&y(new ee(`the lane ${l} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>p,onGone(h){return p?(h(p),()=>{}):(E.add(h),()=>E.delete(h))},dispose(){u?.(),E.clear()}}},g=l=>{d(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose(),H.forgetLane(l.laneId))},d=l=>{let p=l.laneId;return typeof p=="string"&&n.get(p)===l},c=(l,p)=>{throw t.metrics?.observeLane503Fast(p??""),i.set(l,e()),new W(l)},m=async(l,p)=>{let R=wr(p);o.add(R);let E=e();try{let y=await t.laneWarmWaitMsFor?.(l,p)??t.laneColdWakeDefaultMs??0,u=await t.plane.pick({pool:R,model:l,holdMs:y});t.metrics?.observeLaneReady(l??"",u.length);let v=u.map(b=>({laneId:b.laneId,self:b.host===t.selfAddress,host:b.host})).sort((b,N)=>b.self!==N.self?b.self?-1:1:(r.get(b.laneId)??0)-(r.get(N.laneId)??0))[0];v||c(R,l);let _=n.get(v.laneId);return _?.goneWatch?.gone()&&(g(_),_=void 0),_&&(_.pool!==R||_.self!==v.self||_.host!==v.host)&&(g(_),_=void 0),_||(_=s(v.laneId,R,v.self,v.host,p.sharedOrgId??void 0)),_.inFlight+=1,r.set(v.laneId,(r.get(v.laneId)??0)+1),{app:R,entry:_,identity:{kind:"catalog",model_id:p.modelId??l??"",variant:p.variant??""}}}finally{t.metrics?.observeLanePick(l??"",e()-E)}};return{sessionFor(l,p){return m(l,p)},release(l){d(l)&&(l.inFlight=Math.max(0,l.inFlight-1),r.set(l.laneId,l.inFlight))},owns(l){return d(l)},entryFor(l){return n.get(l)??null},evict(l){d(l)&&(l.gone.dispose(),n.delete(l.laneId),r.set(l.laneId,0),l.laneSession.destroy())},async status(){let l=[...new Set([...o,...[...n.values()].map(E=>E.pool)])].sort(),p=await t.plane.status().catch(()=>[]),R=new Map(br(p));return Promise.all(l.map(async E=>{let y=R.get(E)??{pool:E,lanes:[],lastDemandAt:null};return{pool:E,lanes:y.lanes,lastDemandAt:y.lastDemandAt,local:[...n.values()].filter(u=>u.pool===E).map(u=>({laneId:u.laneId,inFlight:u.inFlight,self:u.self,host:u.host})),lastRefusalAt:i.get(E)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function br(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();import{request as vr}from"http";var _r="/pooler/v1/lanes/pick",Sr="/pooler/v1/lanes/status",kr=1e4;function jt(t,e,n,r,o){return new Promise((i,s)=>{let a=new URL(n,t.baseUrl),g=r===void 0?void 0:Buffer.from(JSON.stringify(r)),d=vr({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...g===void 0?{}:{"content-type":"application/json","content-length":String(g.byteLength)}},timeout:o},c=>{let m=[];c.on("data",l=>m.push(l)),c.on("end",()=>{let l=Buffer.concat(m).toString("utf8"),p=null;try{p=l===""?null:JSON.parse(l)}catch{p=null}i({status:c.statusCode??0,json:p})}),c.on("error",s)});d.on("timeout",()=>{d.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),d.on("error",s),d.end(g)})}function Jt(t,e,n){if(t===503)return new W(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Vt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await jt(t,"POST",_r,{pool:e,model:n,hold_ms:r},r+kr);if(o.status!==200)throw Jt(o.status,o.json,e);return(o.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 e=await jt(t,"GET",Sr,void 0,5e3);if(e.status!==200)throw Jt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import{WebSocketServer as xr}from"ws";L();import*as Yt from"yjs";import*as J from"y-protocols/sync";import*as M from"y-protocols/awareness";import*as C from"lib0/encoding";import*as V from"lib0/decoding";import*as qt from"lib0/map";import Rr from"lodash.debounce";L();var zt=()=>{};var Lr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Ar=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Cr=0,Pr=1;var Tr=process.env.GC!=="false"&&process.env.GC!=="0",Nr=process.env.YPERSISTENCE,ve=null;if(typeof Nr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var j=new Map,_e=0,Be=1,Ur=(t,e,n)=>{let r=C.createEncoder();C.writeVarUint(r,_e),J.writeUpdate(r,t);let o=C.toUint8Array(r);n.conns.forEach((i,s)=>X(n,s,o))},Ke=class extends Yt.Doc{constructor(e){super({gc:Tr}),this.name=e,this.conns=new Map,this.awareness=new M.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:i},s)=>{let a=r.concat(o,i);if(s!==null){let c=this.conns.get(s);c!==void 0&&(r.forEach(m=>{c.add(m)}),i.forEach(m=>{c.delete(m)}))}let g=C.createEncoder();C.writeVarUint(g,Be),C.writeVarUint8Array(g,M.encodeAwarenessUpdate(this.awareness,a));let d=C.toUint8Array(g);this.conns.forEach((c,m)=>{X(this,m,d)})};this.awareness.on("update",n),this.on("update",Ur),!1}},je=(t,e=!0)=>qt.setIfUndefined(j,t,()=>{let n=new Ke(t);return n.gc=e,ve!==null&&ve.bindState(t,n),j.set(t,n),n}),Ir=(t,e,n)=>{try{let r=C.createEncoder(),o=V.createDecoder(n);switch(V.readVarUint(o)){case _e:C.writeVarUint(r,_e),J.readSyncMessage(o,r,e,t),C.length(r)>1&&X(e,t,C.toUint8Array(r));break;case Be:{M.applyAwarenessUpdate(e.awareness,V.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},B=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),M.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&ve!==null&&(ve.writeState(t.name,t).then(()=>{t.destroy()}),j.delete(t.name))}e.close()},X=(t,e,n)=>{e.readyState!==Cr&&e.readyState!==Pr&&B(t,e);try{e.send(n,r=>{r!=null&&B(t,e)})}catch{B(t,e)}},Or=3e4,Xt=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=je(n,r);o.conns.set(t,new Set),t.on("message",a=>Ir(t,o,new Uint8Array(a)));let i=!0,s=setInterval(()=>{if(!i)o.conns.has(t)&&B(o,t),clearInterval(s);else if(o.conns.has(t)){i=!1;try{t.ping()}catch{B(o,t),clearInterval(s)}}},Or);t.on("close",()=>{B(o,t),clearInterval(s)}),t.on("pong",()=>{i=!0});{let a=C.createEncoder();C.writeVarUint(a,_e),J.writeSyncStep1(a,o),X(o,t,C.toUint8Array(a));let g=o.awareness.getStates();if(g.size>0){let d=C.createEncoder();C.writeVarUint(d,Be),C.writeVarUint8Array(d,M.encodeAwarenessUpdate(o.awareness,Array.from(g.keys()))),X(o,t,C.toUint8Array(d))}}};var Je="/doc/",Zt=30,$r=1e4,Qt="llm";function Dr(t){if(!t.startsWith(Je))return null;let e=t.slice(Je.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function Q(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
13
- `;t.end(`HTTP/1.1 ${e} ${r}\r
14
- Connection: close\r
15
- Content-Type: text/plain; charset=utf-8\r
16
- Content-Length: ${Buffer.byteLength(o)}\r
17
- \r
18
- ${o}`)}function en(t,e){let n=new xr({noServer:!0}),r=new Set,o=new Map,i=new Map,s=u=>o.get(`${u}/${Qt}`)??0,a=u=>i.get(u)??0,g=new Map,d=new Map,c=new Set,m=new Set,l=!1,p=(u,h,v)=>{let _=s(u)>0,b=a(u),N=b>0,$=`${u}/${h}`,f=o.get($)??0;v>0?o.set($,v):o.delete($);let S=b+v-f;S>0?i.set(u,S):i.delete(u);let w=s(u)>0,k=S>0;if(_!==w){w?R(u):E(u);for(let A of g.get(u)??[])A(w)}N&&!k&&queueMicrotask(()=>{let A=`${u}/`;for(let[T,x]of[...j.entries()])!T.startsWith(A)||x.conns.size>0||(j.delete(T),x.destroy())})},R=u=>{if(!e.hostRegistry||d.has(u))return;let h=()=>{e.hostRegistry?.setHost(u,e.selfAddress).catch(()=>{})};h();let v=setInterval(h,$r);v.unref?.(),d.set(u,v)},E=u=>{let h=d.get(u);h&&(clearInterval(h),d.delete(u)),e.hostRegistry&&e.hostRegistry.delHost(u,e.selfAddress).catch(()=>{})},y=(u,h,v)=>{let _;try{_=new URL(u.url??"/","http://localhost")}catch{Q(h,400,"malformed upgrade URL");return}h.on("error",()=>h.destroy()),h.on("close",()=>m.delete(h));let b=Dr(_.pathname);if(!b){if(_.pathname.startsWith(Je)){Q(h,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}m.add(h);return}c.add(h);let N=!1;(async()=>{let $=_.searchParams.get("token")??"",f=null;try{f=$===""?null:await e.verifyToken($,b.laneId,b.docName)}catch{f=null}if(f===null){Q(h,401,"invalid or missing lane doc token");return}let S=f;if(S.tenant!==void 0&&e.laneTenantOf){let w=null;try{w=await e.laneTenantOf(b.laneId)}catch{w=null}if(w==null||w==="")e.onLaneTenantMissing?.();else if(S.tenant!==w){Q(h,403,"lane doc token org does not match the lane record");return}}l||h.destroyed||(N=!0,n.handleUpgrade(u,h,v,w=>{c.delete(h),r.add(w),w.on("close",()=>r.delete(w));let k=S.scope===St||S.scope===void 0&&typeof S.app=="string"&&typeof S.fn=="string"&&S.aud==="sfu";if(k){let T=`${b.laneId}/${b.docName}`,x=(o.get(T)??0)+1;p(b.laneId,b.docName,x),x>1&&b.docName===Qt&&e.hostRegistry?.setHost(b.laneId,e.selfAddress).catch(()=>{})}w.on("close",()=>{if(!k)return;let T=`${b.laneId}/${b.docName}`;p(b.laneId,b.docName,Math.max(0,(o.get(T)??1)-1))}),Xt(w,u,{docName:`${b.laneId}/${b.docName}`,gc:!0})}))})().catch(()=>{!N&&!h.destroyed&&Q(h,500,"lane doc upgrade failed")}).finally(()=>c.delete(h))};return t.on("upgrade",y),{async close(){l=!0,t.off("upgrade",y);for(let h of[...d.keys()])E(h);await new Promise(h=>{if(r.size===0&&c.size===0){h();return}let v=r.size+c.size,_=()=>{v-=1,v<=0&&h()};for(let b of r)b.once("close",_);for(let b of c)b.once("close",_);for(let b of r)b.close(1001,"lane doc host shutting down");for(let b of c)b.destroy()}),o.clear(),i.clear(),g.clear()},roomDoc(u,h){return je(`${u}/${h}`,!0)},isHosted(u){return s(u)>0},onHostedChange(u,h){let v=g.get(u);return v||(v=new Set,g.set(u,v)),v.add(h),h(s(u)>0),()=>{v.delete(h)}}}}import Wr from"ws";L();var Hr="urun:catalog:v1";function tn(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,i=null,s=async()=>{let g=await t.redis.hgetall(Hr),d=[];for(let c of Object.values(g))try{d.push(JSON.parse(c))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
19
- `)}return r=d,o=n(),d},a=()=>r===null||n()-o>=e;return{rows(){return a()?(i||(i=s().finally(()=>{i=null})),i):Promise.resolve(r)},close(){r=null,i=null}}}import Gr from"ioredis";L();var Se="/inference-usage",nn=25e3;var Mr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function rn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Mr.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Se}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(nn)})}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) could not be reached within ${nn}ms: ${rn(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new P("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} with a body that is not JSON: ${rn(s)}`)}return dt(i,this.opts.onRejectedRow)}};var Kr=5e3,Br=1e3,jr=1500,Jr=3e3,Vr="/api/client-tokens";function Ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function on(t,e,n,r){Ee(t,e,{error:{message:n,type:r}})}async function zr(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Vr}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Jr)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Bs(t){let e=t.resolver??new le({gatewayUrl:t.baseUrl}),n=t.machine?new ce({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ae(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,i=null,s=(()=>{if(!t.lane)return null;if(!t.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 f=new Gr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),S=tn({redis:f});return{registry:Bt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Vt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(k,A)=>o?.onHostedChange(k,A)??(()=>()=>{}),roomDoc:(k,A)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(k,A)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(k,A)=>S.rows().then(T=>{let x=qe(T,A);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:S,redis:f}})(),a=t.registry??new ue({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:t.pooler}),g=t.probeControlPlane??(()=>zr(t.baseUrl)),d=async()=>{let f=null;for(let k of a.decisionPools()){f=k;break}if(!f)return null;let S=f.stats();if(S.some(k=>k.draining))return{ok:!1,detail:"decision pool draining"};if(S.every(k=>k.attached===0&&k.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let w=await f.pingReady(jr);return{ok:w,detail:w?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new ke({apiUrl:t.apiUrl}),m=t.ledgerClient??new ge({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),l=process.env.URUN_SHARED_ORG_ID?.trim(),p=process.env.URUN_SHARED_ORG_API_KEY?.trim();l&&p&&(async()=>{try{await a.decisionWarmerFor({orgId:l,apiKey:p})?.warmFor(yt)}catch(f){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(f instanceof Error?f.message:f)}
20
- `)}})();let R=async f=>Ue(de(f.headers.authorization),e,n),E=async f=>{let S=await R(f);if(S.billingAudience==="platform"&&S.creditsAdmissionOk===!1){let w=S.creditsRefusalReason;throw new q(w==="spend_cap_reached"||w==="insufficient_credits"?w:void 0)}return S},y=f=>f instanceof P?{status:f.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:f instanceof q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...f.code!==void 0?{code:f.code}:{}}:f instanceof D?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:f.detail}:null,u=wt({clients:async f=>a.clientsFor(await E(f)),usage:{authorize:f=>de(f.headers.authorization),lookup:(f,S)=>c.lookup(f,S)},statusOf:y,...t.requestLog?{requestLog:t.requestLog}:{},observe:f=>r.observe(f),ledger:{write:(f,S)=>m.write(de(f.headers.authorization),S),observe:f=>r.observeLedger(f),...t.ledgerLog?{report:t.ledgerLog}:{}}}),h=null,v=null,_=Fr((f,S)=>{let w=new URL(f.url??"/","http://localhost");(async()=>{if(f.method==="GET"&&w.pathname==="/healthz"){Ee(S,200,{ok:!0});return}if(f.method==="GET"&&w.pathname==="/readyz"){let T=Date.now();if((!h||T-h.at>=Kr)&&(h={at:T,...await g()}),!v||T-v.at>=Br){let z=await d();v=z===null?{at:T,ok:!0,detail:null}:{at:T,ok:z.ok,detail:z.detail}}let x=(h?.ready??!1)&&v.ok,Z=v.detail===null?h?.detail??"control plane not yet probed":`${h?.detail??"control plane not yet probed"}; ${v.detail}`;Ee(S,x?200:503,{ok:x,control_plane:Z});return}if(f.method==="GET"&&w.pathname==="/lanez"){Ee(S,200,{pools:s?await s.registry.status():null});return}let k=w.pathname==="/v1"||w.pathname.startsWith("/v1/"),A=w.pathname.startsWith("/partners/");if(!k&&!A){on(S,404,`no route for ${f.method} ${w.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}u(f,S)})().catch(k=>{if(!S.headersSent){on(S,500,String(k instanceof Error?k.message:k),"proxy_error");return}S.end()})}),b=t.conversations??new pe({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),N=[Qe(_,{authenticate:async f=>{let S=await Ue(f,e,n),w=b.connectionFor(S);return{clients:w.clients,scope:Oe(S.apiKey),onBindResumeHandle:w.bindResumeHandle,clientsForResume:w.clientsForResume,release:w.release}}}),tt(_,{clients:async f=>a.clientsFor(await E(f)),statusOf:y}).close,ot(_,{resolver:{resolve:async(f,S)=>{let w=await E(f),k=b.connectionFor(w),A;try{A=await lt(st(k.clients,t.realtimeCompanions),it(f),S,at(f))}catch(x){throw k.release().catch(()=>{}),x}let T=A.release;return{...A,release:async()=>{await T?.(),await k.release()}}}}})];if(t.lane&&s){let f=t.lane,S=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=en(_,{verifyToken:(k,A)=>Ne(k,A,f.tokenSecret,void 0,S),selfAddress:f.selfAddress,laneTenantOf:k=>s.redis.get(`lane_tenant:${k}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:S,hostRegistry:{setHost:(k,A)=>s.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${k}`,A,String(Zt)),delHost:k=>s.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${k}`,f.selfAddress)}}),i=Kt(_,{verifyToken:(k,A)=>Ne(k,A,f.tokenSecret,void 0,S),selfAddress:f.selfAddress,hostOf:async k=>{let A=await s.redis.get(`lane_hosts:${k}`);return A&&A.trim()!==""?A.trim():null},podToPodDial:(k,A,T)=>new Promise((x,Z)=>{(async()=>{let z=await s.redis.get(`lane_tenant:${k}`),sn=Y(k,f.tokenSecret,void 0,void 0,z||void 0),an=`ws://${T}/stream/${encodeURIComponent(k)}/${encodeURIComponent(A)}?token=${encodeURIComponent(sn)}`,Re=new Wr(an,be(A));Re.once("open",()=>x(Re)),Re.once("error",Z)})().catch(Z)})});let w=s;N.push(async()=>{await o.close(),await i.close(),await w.registry.close(),w.redis.quit().catch(()=>{})})}_.on("upgrade",(f,S)=>{let w=new URL(f.url??"/","http://localhost");w.pathname===Xe||w.pathname===et||w.pathname===rt||o!==null&&w.pathname.startsWith("/doc/")||i!==null&&w.pathname.startsWith("/stream/")||S.destroyed||(S.write(`HTTP/1.1 404 Not Found\r
21
- Connection: close\r
22
- \r
23
- no WS route for ${w.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),S.destroy())});let $=async()=>{for(let f of N)await f();await b.detachAll()};return{server:_,metricsServer:Et(r),metrics:r,edgeIdentityServer:At(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:$}}async function js(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await gt()||mt(),await e()}export{to as a,kt as b,se as c,un as d,fn as e,pn as f,mn as g,yn as h,ie as i,ae as j,Et as k,io as l,bn as m,vn as n,_n as o,Sn as p,Rt as q,En as r,Rn as s,Ln as t,At as u,P as v,D as w,de as x,xn as y,$n as z,le as A,Hn as B,Ie as C,go as D,mo as E,Yn as F,Oe as G,ue as H,Ot as I,qn as J,fe as K,pe as L,Zn as M,er as N,he as O,U as P,lr as Q,ge as R,Kr as S,Jr as T,Bs as U,js as V};
@@ -1 +0,0 @@
1
- import{c as m}from"./chunk-YSFSRI3D.js";m();var W=24e3,b="audio",w=class{constructor(r,t){this.backend=r;this.opts=t}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(r){if(!this.source)throw new Error("startOutbound() not called");let t=Buffer.from(r,"base64"),n=Math.floor(t.byteLength/2),s=new Int16Array(n);for(let a=0;a<n;a++)s[a]=t.readInt16LE(a*2);this.source.onData(s)}async startInbound(r){if(r==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(r),this.sink.onframe=t=>{let n=Buffer.from(t.samples.buffer,t.samples.byteOffset,t.samples.byteLength).toString("base64");for(let s of this.outHandlers)s(n)}}onOutputAudio(r){return this.outHandlers.add(r),()=>this.outHandlers.delete(r)}};async function H(e,r,t=1e4){let n=new w(r,{sampleRate:24e3}),s=await n.startOutbound();await e.stream(b).attach(s);let a=await V(e,t);return await n.startInbound(a),n}function V(e,r){let t=e.stream(b);return t.track!=null?Promise.resolve(t.track):new Promise((n,s)=>{let a,c=setTimeout(()=>{a?.(),s(new Error(`enableSessionAudio: no downstream audio track within ${r}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},r),u=o=>{o!=null&&(clearTimeout(c),a?.(),n(o))};a=t.on?.("track",u),t.track!=null&&u(t.track)})}var h="rt-video-in",y=256e3;function N(e){let r=e.stream(h),t=r.emit;if(typeof t!="function")throw new Error(`enableSessionVideo: session.stream('${h}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async n=>{if(n.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(n.byteLength>y)throw new Error(`enableSessionVideo: frame is ${n.byteLength} bytes \u2014 over the ${y}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await t.call(r,n)}}}var T=24e3,l=480,I=111;async function L(){let e=await import("opusscript"),r=e.default??e;return new r(T,1,2048)}async function $(){let e=await import("werift"),r=await L();return{createSource:()=>{let t=new e.MediaStreamTrack({kind:"audio"}),n=Math.random()*4294967295>>>0,s=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,c=new Int16Array(0);return{track:t,onData:u=>{let o=new Int16Array(c.length+u.length);o.set(c,0),o.set(u,c.length);let i=0;for(;o.length-i>=l;){let d=o.subarray(i,i+l);i+=l;let f=Buffer.from(d.buffer,d.byteOffset,d.byteLength),S=r.encode(f,l);s=s+1&65535,a=a+l>>>0;let E=new e.RtpHeader({version:2,payloadType:I,sequenceNumber:s,timestamp:a,ssrc:n,marker:!1}),A=new e.RtpPacket(E,S);t.writeRtp(A)}c=o.slice(i)}}},createSink:t=>{let n={onframe:null};return t.onReceiveRtp.subscribe(a=>{let c;try{c=r.decode(a.payload)}catch{return}let u=new Int16Array(c.length/2);for(let o=0;o<u.length;o++)u[o]=c.readInt16LE(o*2);n.onframe?.({samples:u})}),n}}}async function M(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let r=new e.nonstandard.RTCAudioSource;return{track:r.createTrack(),onData:n=>r.onData({samples:n,sampleRate:24e3})}},createSink:r=>{let t={onframe:null},n=new e.nonstandard.RTCAudioSink(r);return n.ondata=s=>{t.onframe?.(s)},t}}}m();import{WtControlDecoder as U,consumeWtDataStreams as _,encodeWtControlFrame as x,STREAM_END as D}from"@urun-sh/core";var p="rt-video-out",P="urun.videoOut.v1",g="h264";function k(e,r){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${r}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${r}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${r}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${r}: header key must be a boolean`)}function J(e,r){if(k(e,"encodeVideoOutRecord"),r.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let t=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(t.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${t.byteLength} bytes \u2014 over the u16 length prefix`);let n=new Uint8Array(2+t.byteLength+r.byteLength);return n[0]=t.byteLength&255,n[1]=t.byteLength>>8,n.set(t,2),n.set(r,2+t.byteLength),n}function O(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let r=e[0]|e[1]<<8;if(e.byteLength<2+r)throw new Error(`decodeVideoOutRecord: truncated record (header says ${r} bytes, ${e.byteLength-2} present)`);let t;try{t=JSON.parse(new TextDecoder().decode(e.subarray(2,2+r)))}catch(c){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(c)})`)}let n=t;if(n===null||typeof n!="object"||n.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(n?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let s=n;k(s,"decodeVideoOutRecord");let a=e.subarray(2+r);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:s,au:a.slice()}}async function Y(e){let r=e.wtDataEndpoint;if(typeof r!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let t=await r.call(e),n=t.sessionId??e.sessionId;if(typeof n!="string"||n.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:t.url,certHashes:t.certHashes,token:t.token,sessionId:n,stream:p,codec:g,framing:P}}var G="urun.videoOut.v2-ws";function Q(e){let r=e.stream(p);if(typeof r.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let t=new Set,n=new Set,s=new Set,a=o=>{for(let i of n)i(o)},c=!1,u=async()=>{for await(let o of r.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let i;try{i=O(o)}catch(d){a(d instanceof Error?d:new Error(String(d)));continue}for(let d of t)d(i)}for(let o of s)o()};return{codec:g,onOutputFrame:o=>(t.add(o),c||(c=!0,u().catch(i=>a(i instanceof Error?i:new Error(String(i))))),()=>t.delete(o)),onLaneError:o=>(n.add(o),()=>n.delete(o)),onEnd:o=>(s.add(o),()=>s.delete(o))}}function B(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let r=new Uint8Array(e.length/2);for(let t=0;t<r.length;t++)r[t]=parseInt(e.slice(t*2,t*2+2),16);return r}async function j(e,r,t){let n=t??(typeof globalThis.WebTransport=="function"?(i,d)=>new globalThis.WebTransport(i,d):void 0);if(!n)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let s=n(e.url,{serverCertificateHashes:e.certHashes.map(i=>({algorithm:"sha-256",value:B(i)}))});await s.ready;let a=await s.createBidirectionalStream();await a.writable.getWriter().write(x({t:"hello",token:e.token,sessionId:e.sessionId}));let c=a.readable.getReader(),u=new U,o=!1;for(;!o;){let{value:i,done:d}=await c.read();if(d)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(i)for(let f of u.push(i)){if(f.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await _(s.incomingUnidirectionalStreams,{onData:(i,d)=>{if(i===e.stream){if(d===D){r.onEnd?.();return}if(!(d instanceof Uint8Array)){r.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof d}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{r.onFrame(O(d))}catch(f){r.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:i=>r.onLaneError(i)})}export{W as a,w as b,H as c,h as d,y as e,N as f,$ as g,M as h,p as i,P as j,g as k,J as l,O as m,Y as n,G as o,Q as p,j as q};