@urun-sh/openai 0.6.38 → 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-B26FENQ3.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 +55 -55
  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-6M5JK4YC.js +0 -1
  42. package/dist/chunk-UQV3ZXCW.js +0 -2
  43. package/dist/chunk-YOFTYCYH.js +0 -64
  44. package/dist/chunk-ZA2LMA3I.js +0 -23
@@ -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-YOFTYCYH.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-B26FENQ3.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.38",
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.38"
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 +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};
@@ -1,2 +0,0 @@
1
- import{a as V}from"./chunk-CAR4AEQJ.js";import{f as ne,g as N,h as oe,i as te}from"./chunk-YOFTYCYH.js";import{c as j,f as G,g as B,p as q}from"./chunk-6M5JK4YC.js";import{a as se,b as U}from"./chunk-5MH6NSR2.js";import{a as T}from"./chunk-4NMMWAKD.js";import{b as K,c as J,d as X,g as Q,j as R,k as M,l as D,m as z,p as Y,q as b,r as Z,s as ee}from"./chunk-7AI75MPZ.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as x,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ee,DEFAULT_WHEN_LIVE_TIMEOUT_MS as le,isWakingPhase as ve,SessionFailedError as Ae}from"@urun-sh/core";A();import{SessionFailedError as ge}from"@urun-sh/core";var C=2;function we(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function ye(e){let i=e?.type;return i==="response.completed"||i==="error"}function ae(e){return async function(c,l){let f=await e.sessionFor(c.model);return(async function*(){for(let d=1;d<=C;d++){let{app:w,entry:g,identity:S}=d===1?f:await e.sessionFor(c.model);l?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let s=!1,a=!1;try{let u=await e.createStream(g,c);for await(let m of u){if(ye(m)&&(s=!0),we(m)){if(d>1)continue}else a=!0;yield m}}catch(u){if(u instanceof ge&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(d<C&&!a){await e.evict(w,g);continue}throw u}if(s)return;if(d<C&&!a){await e.evict(w,g);continue}return}})()}}import{randomUUID as pe}from"crypto";A();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Se="audio";function ce(e){let i=e.streamEndpoint(Se);return{sessionId:e.id,appendInputAudio(c){let l=Buffer.from(c,"base64");l.byteLength!==0&&i.send(he(new Uint8Array(l)))},onOutputAudio(){return()=>{}}}}var Oe=0,be=4,Ie=4;function Qe(e,i){let c=(d,w)=>{let g=(e[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(e[d])})`);return S},l=(e.URUN_DECISION_POOL_MIN??"").trim();if(l==="0")return null;let f=l?Number.parseInt(l,10):Oe;if(!Number.isInteger(f)||f<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=c("URUN_DECISION_POOL_MAX",Math.max(f,be));return{min:f,max:r,idleGraceMs:3e4,inFlightCap:c("URUN_DECISION_POOL_INFLIGHT_CAP",Ie),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function ze(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return N;let c=Number.parseInt(i,10);if(!Number.isInteger(c)||c<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return c*1e3}function $(e,i,c,l){let f=e[c];if(typeof f!="function")throw new Error(`app "${i}" has no function "${c}" (set URUN_FUNCTION)`);let r=l?f(void 0,l):f();if(typeof r.end!="function")throw new Error(`app "${i}" function "${c}" returned a session without end()`);return r}function ue(e,i,c,l){let{baseUrl:f,orgId:r,auth:d}=e,w=i.fnName??e.fnName,g=e.sessionStartOptions?.(c),S=l||g||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...g,...l}:void 0,s=y=>({session:y,responses:new T(y),gone:se(y,c)});if(d.lane==="jwt"){let y=x(i.appSlug,{baseUrl:f,orgId:r,jwt:d.jwt});return s($(y,i.appSlug,w,S))}if(d.lane==="machine"){let{machineToken:y,gatewayUrl:k}=d,I=(typeof e.subject=="function"?e.subject():e.subject)??pe(),n=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(n,i.appSlug,w,S))}let{apiKey:a,gatewayUrl:u}=d,m=(typeof e.subject=="function"?e.subject():e.subject)??pe(),h=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(a,{baseUrl:u,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:m,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(h,i.appSlug,w,S))}function fe(e){let i=e.session.id;if(typeof i!="string"||i.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return i}function me(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,c=e.status.error?.code;return i===410||i===409&&(c==="cancelled"||c==="expired")?!0:c==="client_ended"}var _e=new Set(["error","paused"]);function Ye(e){let{auth:i,catalog:c}=e,l=null,f=(d,w)=>{let g=ue(e,d,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{l?.evict(w,g)}),g},r=new ee({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:f,closeSession:async d=>{if(d.gone.dispose(),e.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:i.lane==="api-key"?()=>z({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(c?()=>V(c):null),listPrices:c?()=>X(c):null,shared:i.lane==="api-key"?()=>J({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let d=await e.catalogRows();return K(d)}:null,sessionKey:fe});return l=r,e.defaultApp!==null&&r.seed(e.defaultApp,f({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Ze(e,i){let c=e.decisionPool;if(!c)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let l=c.replicaId??"proxy",f=new Map,r=new Map,d=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
2
- `)},g=(s,a)=>{let u=f.get(a);if(u)return u;let m=new ne({min:c.min,max:c.max,idleGraceMs:c.idleGraceMs,inFlightCap:c.inFlightCap,replicaId:l,openSlot:async h=>{let y=ue(e,s,a,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>m.markSessionDead(y)),await L(y.session),w(`slot attached pool=${a} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${a} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof Ae&&me(h)});return r.set(a,{target:s,env:c}),f.set(a,m),m},S=async(s,a)=>{let u=r.get(a);if(u)try{let m=await i.poolTuningFor(s);g(s,a).retune({min:m?.min??u.env.min,max:m?.max??u.env.max,inFlightCap:m?.in_flight_cap??u.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){w(`pool tuning refresh failed pool=${a} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await g(s,b(s)).boot()},async sessionFor(s){let a=await i.resolveTargetFor(s),u=b(a),m=g(a,u);await S(a,u);let h=await m.acquire({timeoutMs:m.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:u,entry:h.entry,identity:Z(a)}},async warmFor(s){let a=await i.resolveTargetFor(s);await g(a,b(a)).boot()},end(s){let a=d.get(s)?.shift();a&&(d.get(s)?.length===0&&d.delete(s),a.release())},evict(s){for(let a of f.values())a.evict(s)},markSessionDead(s){for(let a of f.values())a.markSessionDead(s)},reap(){for(let[s,{target:a}]of r)S(a,s).then(()=>{let u=f.get(s);u&&u.reap()})},async pingReady(s){for(let a of f.values())if(await a.pingReady(s))return!0;return!1},stats(){return[...f.entries()].map(([s,a])=>({poolKey:s,...a.stats()}))},async drain(s){await Promise.all([...f.values()].map(a=>a.drain({timeoutMs:s})))},async close(){await Promise.all([...f.values()].map(s=>s.close()))}}}function Le(e){return ve(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le:Ee:le}async function L(e,i){let c=e.whenLive;if(typeof c!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await c.call(e,{timeout:Le(e.phase),signal:i})}async function H(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function en(e,i=B,c,l,f=N,r){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,s=new WeakMap,a=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",m=n=>{let o=D(n);if(!r||!o||o.app!==u)return null;let t=r.entryFor(o.key);if(!t)throw new R(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},h=async n=>m(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=d.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let p=await j(n.session,await i());return Object.assign(p,{sessionId:n.session.id})})(),d.set(n,o),o.catch(()=>{d.get(n)===o&&d.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:p=>t.appendInputAudio(p),onOutputAudio:p=>t.onOutputAudio(p),sessionId:a(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(d.get(n)===void 0||E!==void 0&&E.waiting===0)&&await H(n.session),_(t)}let p=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?p:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),d.delete(n),S.delete(n),H(n.session).catch(()=>{})),v(_(t))};t.addEventListener("abort",O,{once:!0});let W=()=>t.removeEventListener("abort",O);p.then(F=>{W(),E(F)},F=>{W(),v(F)})})};return{createResponse:ae({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return l?l.sessionFor(n):e.sessionFor(n)}:l?n=>l.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>a(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):l?l.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{me(t)&&(r&&r.owns(o)?r.evict(o):l?l.markSessionDead(o):e.evict(n,o),c?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=oe(U(await n.responses.responses.create(o),n.gone),f);if(!l&&!r)return t;let p=n;return(async function*(){try{yield*t}catch(E){throw te(E)&&(r&&r.owns(p)?r.evict(p):l&&(E instanceof R?l.markSessionDead(p):l.evict(p))),E}finally{r&&r.owns(p)?r.release(p):l?.end(p)}})()}catch(t){throw r&&r.owns(n)?r.release(n):l&&l.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let p=m(n);if(p){let E=p.entry.session;return ce(E)}let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await h(n);yield*Q(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=G(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=q(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),p=a(t.entry);if(p===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return M(u,p)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:t,entry:p}=await e.dedicatedSessionFor(n);return M(t,fe(p))},releaseSessionHandle:n=>{let o=D(n);if(!o)return;if(o.app.startsWith(Y)){(async()=>{let p=null;try{p=(await e.sessionForHandle(n)).entry}catch{return}await H(p.session).catch(()=>{}),await e.evict(o.app,p)})();return}if(!r||o.app!==u)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let p=await h(n);await L(p.session);let P=t!==void 0&&m(n)?new T({...p.session,consumerId:t},{sessionTag:t}):p.responses;return U(await P.responses.create(o),p.gone)},onSessionEnd:async(n,o)=>{let t=m(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:p}=await e.sessionForHandle(n),P=p.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!_e.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{Qe as a,ze as b,Ye as c,Ze as d,en as e};