@urun-sh/openai 0.2.60 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ResponsesClient-BYx3YLGo.d.ts +26 -0
- package/dist/ResponsesClient-Dft3bg3b.d.cts +26 -0
- package/dist/chunk-54VWZJU7.js +6 -0
- package/dist/chunk-5NXM4IO3.js +2 -0
- package/dist/chunk-CWJRDBDC.js +1 -0
- package/dist/chunk-F2TEK34X.js +1 -0
- package/dist/chunk-G3NMGP4N.js +1 -0
- package/dist/chunk-M6ICU4F5.js +40 -0
- package/dist/chunk-UVAY7Q7Z.js +1 -0
- package/dist/chunk-XHIIEA6Z.js +1 -0
- package/dist/chunk-YSFSRI3D.js +1 -0
- package/dist/chunk-ZW6ENXZY.js +1 -0
- package/dist/gemini-live.cjs +2 -0
- package/dist/gemini-live.d.cts +120 -0
- package/dist/gemini-live.d.ts +79 -0
- package/dist/gemini-live.js +1 -0
- package/dist/hosted/bin.cjs +56 -0
- package/dist/hosted/bin.js +23 -0
- package/dist/hosted/index.cjs +34 -0
- package/dist/hosted/index.d.cts +621 -0
- package/dist/hosted/index.d.ts +226 -0
- package/dist/hosted/index.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +4 -4
- package/dist/pi-extension/index.d.cts +2 -1
- package/dist/pi-extension/index.d.ts +2 -1
- package/dist/pi-extension/index.js +7 -7
- package/dist/pi-extension/standalone.cjs +54 -54
- package/dist/proxy/cli.cjs +39 -39
- package/dist/proxy/cli.js +14 -19
- package/dist/proxy/index.cjs +22 -22
- package/dist/proxy/index.d.cts +5 -182
- package/dist/proxy/index.d.ts +5 -67
- package/dist/proxy/index.js +1 -1
- package/dist/server-BfME37pQ.d.cts +200 -0
- package/dist/server-l1himPxc.d.ts +82 -0
- package/dist/translator-C9uPKypK.d.ts +130 -0
- package/dist/translator-CcDBEfvm.d.cts +227 -0
- package/dist/{ResponsesClient-y8g6OfNN.d.cts → types-lsVTbNcH.d.cts} +16 -24
- package/dist/{ResponsesClient-y8g6OfNN.d.ts → types-lsVTbNcH.d.ts} +8 -24
- package/dist/video-out-CWesbk12.d.ts +155 -0
- package/dist/video-out-D20UuJ8G.d.cts +298 -0
- package/package.json +22 -2
- package/dist/chunk-4FUBGLFN.js +0 -41
- package/dist/chunk-OLE2YJO3.js +0 -1
- package/dist/chunk-SSZL77P5.js +0 -1
- package/dist/chunk-VFHQZ4OM.js +0 -1
- package/dist/chunk-VXTNG2TP.js +0 -1
- package/dist/media-DCHTX3Ez.d.cts +0 -68
- package/dist/media-DCHTX3Ez.d.ts +0 -42
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { b as UrunSessionLike } from './types-lsVTbNcH.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The ONE native audio sample rate of the session transport: the SFU Opus leg
|
|
5
|
+
* runs 24 kHz mono, so every PCM16 chunk entering `AudioBridge.appendInputAudio`
|
|
6
|
+
* and every chunk emitted by `onOutputAudio` is 24 kHz mono 16-bit LE. Protocol
|
|
7
|
+
* adapters (OpenAI Realtime, Gemini Live) resample at THEIR edge to this rate.
|
|
8
|
+
*/
|
|
9
|
+
declare const NATIVE_AUDIO_SAMPLE_RATE = 24000;
|
|
10
|
+
/** Pluggable audio backend so tests don't need real WebRTC. In production, `nodeAudioBackend()` wraps @roamhq/wrtc. */
|
|
11
|
+
interface AudioSource {
|
|
12
|
+
track: unknown;
|
|
13
|
+
onData(frame: Int16Array): void;
|
|
14
|
+
}
|
|
15
|
+
interface AudioSink {
|
|
16
|
+
onframe: ((frame: {
|
|
17
|
+
samples: Int16Array;
|
|
18
|
+
}) => void) | null;
|
|
19
|
+
}
|
|
20
|
+
interface AudioBackend {
|
|
21
|
+
createSource(): AudioSource;
|
|
22
|
+
/**
|
|
23
|
+
* Build a sink that pulls PCM16 frames OFF the runtime's downstream audio
|
|
24
|
+
* track (`remoteTrack`, the real Opus `MediaStreamTrack` the SFU now produces
|
|
25
|
+
* — see session-server-ts audio ingest). The production backend wires a real
|
|
26
|
+
* `RTCAudioSink(remoteTrack)`; the sink's `onframe` is invoked per decoded
|
|
27
|
+
* 10ms frame. `remoteTrack` is REQUIRED — a missing track is a wiring bug, not
|
|
28
|
+
* a silent no-op (a dead sink is exactly the placeholder this replaces).
|
|
29
|
+
*/
|
|
30
|
+
createSink(remoteTrack: unknown): AudioSink;
|
|
31
|
+
}
|
|
32
|
+
declare class AudioBridge {
|
|
33
|
+
private readonly backend;
|
|
34
|
+
private readonly opts;
|
|
35
|
+
private source;
|
|
36
|
+
private sink;
|
|
37
|
+
private outHandlers;
|
|
38
|
+
constructor(backend: AudioBackend, opts: {
|
|
39
|
+
sampleRate: number;
|
|
40
|
+
});
|
|
41
|
+
startOutbound(): Promise<unknown>;
|
|
42
|
+
/** OpenAI: input_audio_buffer.append (base64 PCM16) → publish frames. */
|
|
43
|
+
appendInputAudio(base64Pcm16: string): void;
|
|
44
|
+
/**
|
|
45
|
+
* Wire the runtime's downstream audio track into the output-frame fan-out.
|
|
46
|
+
* `remoteTrack` is the REAL Opus `MediaStreamTrack` the SFU produces for this
|
|
47
|
+
* session (`session.stream('rt-audio-out').track`). The backend attaches a
|
|
48
|
+
* real `RTCAudioSink` to it; each decoded PCM16 frame is re-emitted as base64
|
|
49
|
+
* to every `onOutputAudio` handler (the OpenAI `response.audio.delta` source).
|
|
50
|
+
*
|
|
51
|
+
* Throws if `remoteTrack` is absent — the previous build silently created a
|
|
52
|
+
* dead sink that never fired, so voice OUT looked "wired" but produced no
|
|
53
|
+
* audio. A missing track here means the consume side did not attach yet; the
|
|
54
|
+
* caller must await the real track before calling this.
|
|
55
|
+
*/
|
|
56
|
+
startInbound(remoteTrack: unknown): Promise<void>;
|
|
57
|
+
/** Emits base64 PCM16 → caller wraps as OpenAI response.audio.delta. */
|
|
58
|
+
onOutputAudio(handler: (base64Pcm16: string) => void): () => void;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The ONE canonical session-audio wiring — every protocol surface that carries
|
|
62
|
+
* audio over a uRun session (OpenAI Realtime `enableAudio`, the Gemini Live
|
|
63
|
+
* proxy lane) rides THIS function; none re-implements the dance:
|
|
64
|
+
*
|
|
65
|
+
* 1. `bridge.startOutbound()` → attach the local track to `rt-audio-in`
|
|
66
|
+
* 2. await the runtime's downstream track on `rt-audio-out` (consumed
|
|
67
|
+
* ASYNCHRONOUSLY after the WebRTC handshake — may not exist yet)
|
|
68
|
+
* 3. `bridge.startInbound(track)` → decoded PCM16 fans out via `onOutputAudio`
|
|
69
|
+
*
|
|
70
|
+
* Fails loud (rejects) if the runtime never produces voice OUT within
|
|
71
|
+
* `timeoutMs` — a video-only/text-only app is a wiring gap, not a silent no-op.
|
|
72
|
+
*/
|
|
73
|
+
declare function enableSessionAudio(session: UrunSessionLike, backend: AudioBackend, timeoutMs?: number): Promise<AudioBridge>;
|
|
74
|
+
/**
|
|
75
|
+
* The named-DATA stream video frames ride browser→runtime (the video-frame twin
|
|
76
|
+
* of the `rt-audio-in` media lane). Apps consume it as
|
|
77
|
+
* `ctx.stream('rt-video-in', kind='data')` — each segment is one encoded JPEG
|
|
78
|
+
* frame (raw bytes, no envelope beyond the §5 stream framing).
|
|
79
|
+
*/
|
|
80
|
+
declare const RT_VIDEO_IN_STREAM = "rt-video-in";
|
|
81
|
+
/**
|
|
82
|
+
* Per-frame wire-fit budget, the TS twin of urun-python
|
|
83
|
+
* `image_codec.IMAGE_MESSAGE_BUDGET`: mediasoup's transport `maxMessageSize`
|
|
84
|
+
* and Chrome's `a=max-message-size` are both 262144 bytes, and an SCTP message
|
|
85
|
+
* beyond the ceiling is dropped SILENTLY by the mediasoup worker (live root
|
|
86
|
+
* cause dev-usw2 2026-07-10: a 300,675-byte JPEG reached the SFU and simply
|
|
87
|
+
* never arrived). 256000 leaves slack for the §5 stream envelope framing. A
|
|
88
|
+
* frame over budget MUST be rejected loudly here — the transport would turn it
|
|
89
|
+
* into a silent drop.
|
|
90
|
+
*/
|
|
91
|
+
declare const VIDEO_FRAME_MESSAGE_BUDGET = 256000;
|
|
92
|
+
/** The frame-lane handle: one encoded JPEG frame per call, in call order. */
|
|
93
|
+
interface VideoFrameLane {
|
|
94
|
+
sendInputFrame(jpegFrame: Uint8Array): Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The ONE canonical session video-frame wiring: discrete JPEG frames →
|
|
98
|
+
* `session.stream(RT_VIDEO_IN_STREAM).emit(bytes)` (core's §5 named-DATA
|
|
99
|
+
* produce). Fails loud if the session's stream surface has no `emit` — a
|
|
100
|
+
* frame-receiving surface without the data-produce seam is a wiring gap, never
|
|
101
|
+
* a silent drop. There is no downstream video leg: Live-style protocols output
|
|
102
|
+
* TEXT/AUDIO only, and the runtime's video OUT rides the existing consume path.
|
|
103
|
+
*/
|
|
104
|
+
declare function enableSessionVideo(session: UrunSessionLike): VideoFrameLane;
|
|
105
|
+
/**
|
|
106
|
+
* Production backend for the werift transport (@urun-sh/core). Replaces the
|
|
107
|
+
* wrtc backend, whose `RTCAudioSink`/`RTCAudioSource` are incompatible with
|
|
108
|
+
* werift's read-only-`id` `MediaStreamTrack`.
|
|
109
|
+
*/
|
|
110
|
+
declare function weriftAudioBackend(): Promise<AudioBackend>;
|
|
111
|
+
/**
|
|
112
|
+
* @deprecated wrtc backend — INCOMPATIBLE with @urun-sh/core's werift transport
|
|
113
|
+
* (its `RTCAudioSink`/`RTCAudioSource` set the foreign track's read-only `id`).
|
|
114
|
+
* Use {@link weriftAudioBackend}. Kept for any non-werift transport.
|
|
115
|
+
*/
|
|
116
|
+
declare function nodeAudioBackend(): Promise<AudioBackend>;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Video OUTPUT over the named §5 WT/QUIC stream — the platform lane a
|
|
120
|
+
* beyond-parity protocol extension (Gemini Live `urun.videoOut`) points
|
|
121
|
+
* clients at, plus the client leg that consumes it.
|
|
122
|
+
*
|
|
123
|
+
* The delivery path is ENTIRELY first-party (urun-infra#1608, deployed):
|
|
124
|
+
* the runtime emits per-frame records on the named §5 data stream
|
|
125
|
+
* {@link RT_VIDEO_OUT_STREAM}; the relay's egress sink fans each §5 envelope
|
|
126
|
+
* to the wt-gateway, which multiplexes it onto ONE ordered reliable QUIC
|
|
127
|
+
* unidirectional stream per name on the leg's existing WebTransport session.
|
|
128
|
+
* Nothing here invents a transport or a second framing:
|
|
129
|
+
*
|
|
130
|
+
* - §5 envelope: core `encodeStreamEnvelope`/`decodeStreamEnvelope`
|
|
131
|
+
* (`[0x01][kind][payload]`) — the LOCKED twin, byte-identical to SCTP.
|
|
132
|
+
* - Uni-stream framing: core `consumeWtDataStreams`/`WtDataStreamParser`
|
|
133
|
+
* (`[0x01][nameLen][name utf8]` then repeated `[u32 LE len][envelope]`).
|
|
134
|
+
* - Control handshake: core `encodeWtControlFrame`/`WtControlDecoder`
|
|
135
|
+
* (`{t:'hello', token, sessionId}` → `hello-ack`), the same dance
|
|
136
|
+
* core's WebTransportSession performs.
|
|
137
|
+
*
|
|
138
|
+
* The ONLY new bytes are the per-record extension envelope (spec v1, below):
|
|
139
|
+
* a JSON header + one encoded access unit inside each §5 BINARY payload.
|
|
140
|
+
*
|
|
141
|
+
* EXTENSION ENVELOPE SPEC v1 (framing id {@link VIDEO_OUT_FRAMING}):
|
|
142
|
+
* record = [u16 LE headerLen][headerLen bytes UTF-8 JSON][AU bytes…]
|
|
143
|
+
* header = {"v":1,"seq":<int≥0>,"ptsUs":<int>,"codec":<string>,"key":<bool>}
|
|
144
|
+
* v MUST be 1 (any other value rejects the record loudly)
|
|
145
|
+
* seq per-stream monotonically increasing from 0 (gap = relay loss bug:
|
|
146
|
+
* the lane is ordered+reliable, so a gap is LOUD, never smoothed)
|
|
147
|
+
* ptsUs presentation timestamp in microseconds
|
|
148
|
+
* codec the AU's codec id (`"h264"` = Annex-B H.264 in v1; the record
|
|
149
|
+
* header is AUTHORITATIVE over the capability-level default)
|
|
150
|
+
* key true iff the AU decodes standalone (IDR/keyframe)
|
|
151
|
+
* AU exactly one encoded video access unit; MUST be non-empty
|
|
152
|
+
* One record per §5 BINARY envelope; the producer ends the stream with the
|
|
153
|
+
* §5 END envelope (core STREAM_END), never by dropping the connection.
|
|
154
|
+
*/
|
|
155
|
+
|
|
156
|
+
/** The named §5 data stream video OUT rides (downstream twin of rt-video-in). */
|
|
157
|
+
declare const RT_VIDEO_OUT_STREAM = "rt-video-out";
|
|
158
|
+
/** Framing id advertised in the capability handshake; names spec v1 above. */
|
|
159
|
+
declare const VIDEO_OUT_FRAMING = "urun.videoOut.v1";
|
|
160
|
+
/** Capability-level default AU codec (per-record `header.codec` is authoritative). */
|
|
161
|
+
declare const VIDEO_OUT_DEFAULT_CODEC = "h264";
|
|
162
|
+
/** The parsed per-record JSON header (spec v1). */
|
|
163
|
+
interface VideoOutRecordHeader {
|
|
164
|
+
v: 1;
|
|
165
|
+
seq: number;
|
|
166
|
+
ptsUs: number;
|
|
167
|
+
codec: string;
|
|
168
|
+
key: boolean;
|
|
169
|
+
}
|
|
170
|
+
/** One decoded video-out record: header + one encoded access unit. */
|
|
171
|
+
interface VideoOutRecord {
|
|
172
|
+
header: VideoOutRecordHeader;
|
|
173
|
+
au: Uint8Array;
|
|
174
|
+
}
|
|
175
|
+
/** Encode ONE record (spec v1): `[u16 LE headerLen][JSON header][AU]`. */
|
|
176
|
+
declare function encodeVideoOutRecord(header: Omit<VideoOutRecordHeader, 'v'>, au: Uint8Array): Uint8Array;
|
|
177
|
+
/** Decode ONE record (spec v1). Every contract violation is LOUD. */
|
|
178
|
+
declare function decodeVideoOutRecord(payload: Uint8Array): VideoOutRecord;
|
|
179
|
+
/**
|
|
180
|
+
* The negotiated capability a granting proxy returns in `setupComplete` —
|
|
181
|
+
* everything the client leg needs to dial the relay's WT endpoint and read
|
|
182
|
+
* the named stream: the #1608 offer surface (url/certHashes/token), the
|
|
183
|
+
* session id the WT hello requires, and the stream/codec/framing brand.
|
|
184
|
+
*/
|
|
185
|
+
interface VideoOutEndpoint {
|
|
186
|
+
transport: 'webtransport';
|
|
187
|
+
url: string;
|
|
188
|
+
/** sha-256 cert hashes, lowercase hex — WebTransport `serverCertificateHashes`. */
|
|
189
|
+
certHashes: string[];
|
|
190
|
+
/** The per-leg gateway token (#1608: the token's data flag subscribes the leg). */
|
|
191
|
+
token: string;
|
|
192
|
+
/** The uRun session id the WT hello names (`{t:'hello', token, sessionId}`). */
|
|
193
|
+
sessionId: string;
|
|
194
|
+
stream: typeof RT_VIDEO_OUT_STREAM;
|
|
195
|
+
codec: string;
|
|
196
|
+
framing: typeof VIDEO_OUT_FRAMING;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The ONE canonical session wiring for video OUT over QUIC: ask the core
|
|
200
|
+
* session for its §5-over-WT data-lane endpoint (the urun-infra#1608
|
|
201
|
+
* `TransportOfferResponse.webtransport` surface: url + certHashes + token,
|
|
202
|
+
* negotiated with `wtData: true`) and brand it with the rt-video-out stream
|
|
203
|
+
* name and framing. Fails LOUD when the core session exposes no
|
|
204
|
+
* `wtDataEndpoint()` — a session without the dial-negotiation data-lane seam
|
|
205
|
+
* is a missing platform primitive, never a silent skip and NEVER a cue to
|
|
206
|
+
* inline frames on some other lane.
|
|
207
|
+
*/
|
|
208
|
+
declare function negotiateSessionVideoOutQuic(session: UrunSessionLike): Promise<VideoOutEndpoint>;
|
|
209
|
+
/** Framing id the WS-inline capability ack names (spec v2: chunks ride the
|
|
210
|
+
* Bidi WS itself as `{"urun.videoOut": {v:1, seq, ptsUs, codec, key, data}}`
|
|
211
|
+
* extension server messages — base64 AU inside JSON). */
|
|
212
|
+
declare const VIDEO_OUT_WS_FRAMING = "urun.videoOut.v2-ws";
|
|
213
|
+
/**
|
|
214
|
+
* The native video-OUT lane the compat surface fans onto the WS: decoded
|
|
215
|
+
* spec-v1 records from the session's named §5 `rt-video-out` downstream.
|
|
216
|
+
*/
|
|
217
|
+
interface VideoOutLane {
|
|
218
|
+
/** Capability-level default codec (per-record `header.codec` is authoritative). */
|
|
219
|
+
codec: string;
|
|
220
|
+
onOutputFrame(handler: (record: VideoOutRecord) => void): () => void;
|
|
221
|
+
/** LOUD per-lane protocol errors (malformed record, non-BINARY payload). */
|
|
222
|
+
onLaneError(handler: (err: Error) => void): () => void;
|
|
223
|
+
/** The producer ended the stream — normal completion. */
|
|
224
|
+
onEnd(handler: () => void): () => void;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The ONE canonical session wiring for the compat surface's video OUT: consume
|
|
228
|
+
* the session's named §5 `rt-video-out` data stream via the core consume seam
|
|
229
|
+
* (`session.stream(name).messages()` — the downstream twin of the `emit`
|
|
230
|
+
* produce seam #309's video-in rides) and fan each decoded spec-v1 record to
|
|
231
|
+
* subscribers. The pump starts on the FIRST frame subscriber, so no frame is
|
|
232
|
+
* dropped before the adapter wires its fan-out. Fails LOUD (sync) when the
|
|
233
|
+
* stream surface has no `messages()`; malformed records surface on
|
|
234
|
+
* `onLaneError`, never silently skipped. Requires NO WebTransport anywhere —
|
|
235
|
+
* this lane is self-sufficient over whichever transport the session runs.
|
|
236
|
+
*/
|
|
237
|
+
declare function openSessionVideoOutLane(session: UrunSessionLike): VideoOutLane;
|
|
238
|
+
/** Where decoded frames land. Errors are surfaced, never swallowed. */
|
|
239
|
+
interface VideoOutSink {
|
|
240
|
+
onFrame(record: VideoOutRecord): void;
|
|
241
|
+
/** The producer ended the stream (§5 END envelope) — normal completion. */
|
|
242
|
+
onEnd?(): void;
|
|
243
|
+
/** A per-stream protocol violation (bad record/envelope). LOUD, stream-fatal. */
|
|
244
|
+
onLaneError(err: Error): void;
|
|
245
|
+
}
|
|
246
|
+
interface WtByteReader {
|
|
247
|
+
read(): Promise<{
|
|
248
|
+
value?: Uint8Array;
|
|
249
|
+
done: boolean;
|
|
250
|
+
}>;
|
|
251
|
+
cancel?(reason?: unknown): Promise<void>;
|
|
252
|
+
}
|
|
253
|
+
/** Structural WebTransport slice (the DOM lib doesn't ship WT everywhere this
|
|
254
|
+
* package compiles — the same pattern as core's webtransport-session). */
|
|
255
|
+
interface VideoOutWtSession {
|
|
256
|
+
ready: Promise<unknown>;
|
|
257
|
+
incomingUnidirectionalStreams: {
|
|
258
|
+
getReader(): {
|
|
259
|
+
read(): Promise<{
|
|
260
|
+
value?: {
|
|
261
|
+
getReader(): WtByteReader;
|
|
262
|
+
};
|
|
263
|
+
done: boolean;
|
|
264
|
+
}>;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
createBidirectionalStream(): Promise<{
|
|
268
|
+
writable: {
|
|
269
|
+
getWriter(): {
|
|
270
|
+
write(chunk: Uint8Array): Promise<void>;
|
|
271
|
+
};
|
|
272
|
+
};
|
|
273
|
+
readable: {
|
|
274
|
+
getReader(): WtByteReader;
|
|
275
|
+
};
|
|
276
|
+
}>;
|
|
277
|
+
close?(info?: unknown): void;
|
|
278
|
+
}
|
|
279
|
+
/** Dial seam: `(url, {serverCertificateHashes}) => WT session`. Defaults to
|
|
280
|
+
* `globalThis.WebTransport`; inject a factory where the platform has none. */
|
|
281
|
+
type VideoOutWtConnect = (url: string, options: {
|
|
282
|
+
serverCertificateHashes: Array<{
|
|
283
|
+
algorithm: 'sha-256';
|
|
284
|
+
value: Uint8Array;
|
|
285
|
+
}>;
|
|
286
|
+
}) => VideoOutWtSession;
|
|
287
|
+
/**
|
|
288
|
+
* Consume the negotiated video-out lane: dial the relay's WT endpoint, run
|
|
289
|
+
* the canonical hello/hello-ack control handshake, then accept the per-name
|
|
290
|
+
* uni streams via core `consumeWtDataStreams` and deliver each decoded
|
|
291
|
+
* record on the sink. Streams with OTHER names legitimately share the
|
|
292
|
+
* session (token deltas, captions) and are ignored here — they are not
|
|
293
|
+
* errors. Resolves when the session's accept loop ends; rejects loudly on
|
|
294
|
+
* dial/handshake/accept-loop death.
|
|
295
|
+
*/
|
|
296
|
+
declare function consumeVideoOut(endpoint: VideoOutEndpoint, sink: VideoOutSink, connect?: VideoOutWtConnect): Promise<void>;
|
|
297
|
+
|
|
298
|
+
export { type AudioBackend as A, NATIVE_AUDIO_SAMPLE_RATE as N, RT_VIDEO_IN_STREAM as R, VIDEO_FRAME_MESSAGE_BUDGET as V, AudioBridge as a, type AudioSink as b, type AudioSource as c, RT_VIDEO_OUT_STREAM as d, VIDEO_OUT_DEFAULT_CODEC as e, VIDEO_OUT_FRAMING as f, VIDEO_OUT_WS_FRAMING as g, type VideoFrameLane as h, type VideoOutEndpoint as i, type VideoOutLane as j, type VideoOutRecord as k, type VideoOutRecordHeader as l, type VideoOutSink as m, type VideoOutWtConnect as n, type VideoOutWtSession as o, consumeVideoOut as p, decodeVideoOutRecord as q, enableSessionAudio as r, enableSessionVideo as s, encodeVideoOutRecord as t, negotiateSessionVideoOutQuic as u, nodeAudioBackend as v, openSessionVideoOutLane as w, weriftAudioBackend as x };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -27,6 +27,26 @@
|
|
|
27
27
|
"default": "./dist/proxy/index.cjs"
|
|
28
28
|
}
|
|
29
29
|
},
|
|
30
|
+
"./gemini-live": {
|
|
31
|
+
"import": {
|
|
32
|
+
"types": "./dist/gemini-live.d.ts",
|
|
33
|
+
"default": "./dist/gemini-live.js"
|
|
34
|
+
},
|
|
35
|
+
"require": {
|
|
36
|
+
"types": "./dist/gemini-live.d.cts",
|
|
37
|
+
"default": "./dist/gemini-live.cjs"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"./hosted": {
|
|
41
|
+
"import": {
|
|
42
|
+
"types": "./dist/hosted/index.d.ts",
|
|
43
|
+
"default": "./dist/hosted/index.js"
|
|
44
|
+
},
|
|
45
|
+
"require": {
|
|
46
|
+
"types": "./dist/hosted/index.d.cts",
|
|
47
|
+
"default": "./dist/hosted/index.cjs"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
30
50
|
"./pi-extension": {
|
|
31
51
|
"import": {
|
|
32
52
|
"types": "./dist/pi-extension/index.d.ts",
|
|
@@ -50,7 +70,7 @@
|
|
|
50
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
51
71
|
},
|
|
52
72
|
"peerDependencies": {
|
|
53
|
-
"@urun-sh/core": "^0.
|
|
73
|
+
"@urun-sh/core": "^0.3.1"
|
|
54
74
|
},
|
|
55
75
|
"dependencies": {
|
|
56
76
|
"openai": "4.104.0",
|
package/dist/chunk-4FUBGLFN.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import{b as V,c as me}from"./chunk-VXTNG2TP.js";var Ce="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",We=1007,Ee=1008,H=1011,ge=1008,i=class extends Error{constructor(e,o=We){super(e);this.closeCode=o}closeCode},x=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,ae=["setup","clientContent","realtimeInput","toolResponse"];function Te(t){let n;try{n=JSON.parse(t)}catch{throw new i("client message is not valid JSON")}let e=x(n);if(!e)throw new i("client message must be a JSON object");let o=ae.filter(u=>e[u]!==void 0),s=Object.keys(e).filter(u=>!ae.includes(u));if(s.length>0)throw new i(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${ae.join(", ")}`);if(o.length!==1)throw new i(`client message must contain exactly one of ${ae.join(", ")} (got ${o.length})`);let r=o[0],a=x(e[r]);if(!a)throw new i(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function Ne(t,n){if(typeof t=="string")return t;let e=x(t),o=e?e.parts:void 0;if(!Array.isArray(o))throw new i(`${n}: expected a Content with a parts array`);let s=[];for(let r of o){let a=x(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new i(`${n}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new i(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new i(`${n}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
|
|
2
|
-
`)}var Xe={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Qe={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ze=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Ie=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function et(t){let n=x(t);if(!n)throw new i("setup.realtimeInputConfig must be an object");for(let s of Object.keys(n))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new i(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let e=x(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!e)throw new i("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(e??{}))if(s!=="disabled")throw new i(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(e?.disabled!==!0)throw new i("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(n.activityHandling!==void 0){if(!Ie.includes(n.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Ie.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var tt=["temperature","maxOutputTokens","responseModalities"];function Pe(t){for(let[c,g]of Object.entries(Qe))if(t[c]!==void 0)throw new i(g);for(let c of Object.keys(t))if(!Ze.includes(c))throw new i(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new i('setup.model is required (format "models/{model}")');let n=t.model.replace(/^models\//,""),e,o,s=!1,r=x(t.generationConfig);if(t.generationConfig!==void 0&&!r)throw new i("setup.generationConfig must be an object");if(r){for(let c of Object.keys(r))if(!tt.includes(c))throw new i(`unsupported generationConfig field "${c}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new i("generationConfig.temperature must be a number");e=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new i("generationConfig.maxOutputTokens must be a number");o=r.maxOutputTokens}if(r.responseModalities!==void 0){let c=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let g of c){let p=String(g).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new i(`responseModalities ${JSON.stringify(g)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let a=[];t.systemInstruction!==void 0&&a.push({role:"system",content:Ne(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new i("setup.tools must be an array");u=[];for(let c of t.tools){let g=x(c);if(!g)throw new i("setup.tools entries must be objects");for(let p of Object.keys(g))if(p!=="functionDeclarations")throw new i(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let p of g.functionDeclarations){let h=x(p);if(!h||typeof h.name!="string")throw new i("functionDeclarations entries require a string name");u.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}u.length===0&&(u=void 0)}let f={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=x(t.sessionResumption);if(!c)throw new i("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(c))if(g!=="handle")throw new i(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new i("sessionResumption.handle must be a non-empty string when present");f={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=t.realtimeInputConfig===void 0?Xe:et(t.realtimeInputConfig);return{model:n,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:d,sessionResumption:f}}function Me(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function $e(t){let n=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function Le(t){for(let o of Object.keys(t))if(o!=="turns"&&o!=="turnComplete")throw new i(`unsupported clientContent field "${o}"`);let n=t.turns===void 0?[]:t.turns;if(!Array.isArray(n))throw new i("clientContent.turns must be an array");let e=[];for(let o of n){let s=x(o);if(!s)throw new i("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new i(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);e.push({role:r==="model"?"assistant":"user",content:Ne(s,"clientContent.turns")})}return{items:e,turnComplete:t.turnComplete===!0}}var ue=16e3,Ue=24e3,nt=`audio/pcm;rate=${Ue}`,je=Buffer.alloc(960).toString("base64");function ot(t,n,e){if(n===e)return t;let o=Math.floor(t.length*e/n),s=new Int16Array(o),r=n/e,a=t.length-1;for(let u=0;u<o;u++){let f=u*r,d=Math.floor(f);if(d>=a){s[u]=t[a];continue}let c=f-d;s[u]=Math.round(t[d]+(t[d+1]-t[d])*c)}return s}function st(t){let n=x(t);if(!n)throw new i("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new i("realtimeInput.video.data must be non-empty base64");let e=Buffer.from(n.data,"base64");if(e.length<3||e[0]!==255||e[1]!==216)throw new i("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(e)}function rt(t){let n=x(t);if(!n)throw new i("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let e=/;\s*rate=(\d+)/.exec(n.mimeType);if(e&&Number(e[1])!==ue)throw new i(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ue} Hz (audio/pcm;rate=${ue})`);if(typeof n.data!="string"||n.data.length===0)throw new i("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.data,"base64");if(o.length===0||o.length%2!==0)throw new i(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let a=0;a<s.length;a++)s[a]=o.readInt16LE(a*2);let r=ot(s,ue,Ue);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Be(t){if(t.mediaChunks!==void 0)throw new i('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new i("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=t.activityStart!==void 0?"activityStart":"activityEnd",r=x(t[s]);if(!r||Object.keys(r).length!==0)throw new i(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(t))if(!n.includes(o))throw new i(`unsupported realtimeInput field "${o}"`);let e=n.filter(o=>t[o]!==void 0);if(e.length!==1)throw new i(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${e.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:rt(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:st(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new i("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new i("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function qe(t){for(let n of Object.keys(t))if(n!=="functionResponses")throw new i(`unsupported toolResponse field "${n}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new i("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(n=>{let e=x(n);if(!e||typeof e.id!="string"||e.id.length===0)throw new i("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:e.id,output:JSON.stringify(e.response??null)}})}function De(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Je(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:nt,data:t}}]}}}}function He(t){let n=x(t)??{},e=Array.isArray(n.output)?n.output:[],o=[],s=[],r=typeof n.output_text=="string"?n.output_text:"";if(!r)for(let d of e){let c=x(d);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let g of c.content){let p=x(g);p?.type==="output_text"&&typeof p.text=="string"&&(r+=p.text)}}r&&s.push({role:"assistant",content:r});for(let d of e){let c=x(d);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new i(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,H);let g=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(g)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${g}`,H)}o.push({id:c.call_id,name:c.name,args:p}),s.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:g})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let u=x(n.usage),f={serverContent:{turnComplete:!0}};if(u){let d={};typeof u.input_tokens=="number"&&(d.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(d.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(d.totalTokenCount=u.total_tokens),Object.keys(d).length>0&&(f.usageMetadata=d)}return a.push(f),{messages:a,assistantItems:s}}import{createServer as ct}from"http";import{randomUUID as it}from"crypto";import{WebSocketServer as at}from"ws";var ut=256,he=class{snapshots=new Map;store(n,e){for(this.snapshots.set(n,e);this.snapshots.size>ut;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},ne=t=>t.slice(0,120),ye=class{constructor(n,e,o){this.ws=n;this.clients=e;this.registry=o;n.on("message",s=>this.onMessage(s)),n.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;video=null;activityOpen=!1;activeTurn=null;send(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof V){this.ws.close(Ee,ne(n.message));return}if(n instanceof me){this.ws.close(ge,ne(n.message));return}if(n instanceof i){this.ws.close(n.closeCode,ne(n.message));return}this.ws.close(H,ne(String(n instanceof Error?n.message:n)))}onMessage(n){try{let e=Te(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(e.kind==="setup"){this.handleSetup(e.setup).catch(s=>this.fail(s));return}if(!this.config)throw new i(`"${e.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(e.kind==="clientContent"){let{items:s,turnComplete:r}=Le(e.clientContent);this.transcript.push(...s),r&&this.enqueue(()=>this.runTurn());return}if(e.kind==="realtimeInput"){let s=Be(e.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:je);return}this.transcript.push(...qe(e.toolResponse)),this.enqueue(()=>this.runTurn())}catch(e){this.fail(e)}}async handleSetup(n){if(this.config)throw new i("setup may only be sent once, as the first client message");let e=Pe(n),o=e.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new i("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",ge);if(s.model!==e.model)throw new i(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${e.model}", per the Live API session-resumption contract)`);if(e.systemItems.length>0)throw new i("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r)))}else this.proxyHandle=await this.clients.sessionHandle(e.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...e.systemItems);this.config=e,this.send({setupComplete:{}}),e.audioModality&&this.ensureAudioLane(),e.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new i("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openAudio;if(!e)throw new i("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",H);return this.audio=(async()=>{let o=await e.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(s=>this.send(Je(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(e=>e.appendInputAudio(n)).catch(e=>this.fail(e))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new i("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openVideo;if(!e)throw new i("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",H);return this.video=Promise.resolve(e.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(e=>e.sendInputFrame(n)).catch(e=>this.fail(e))}onActivity(n,e){if(!e.activity.manualActivity)throw new i(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="activityStart"){if(this.activityOpen)throw new i("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,e.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new i("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(e=>this.fail(e))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let e=await this.clients.sessionHandle(n.model);this.proxyHandle=e;let o=it();this.registry.store(o,{model:n.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Me(o))}async handleUpstreamEnd(n){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let e=null;try{e=await this.clients.sessionHandle(this.config.model)}catch{}if(e!==null&&e!==this.proxyHandle){this.proxyHandle=e,this.unsubscribeEnd=await this.clients.onSessionEnd(e,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send($e(n.timeLeftMs)),this.ws.close(H,ne(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let e={interrupted:!1};this.activeTurn=e;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),s,r=!1;for await(let f of o){if(e.interrupted)break;let d=f;if(d.type==="error")throw new i(`upstream error: ${JSON.stringify(d)}`,H);if(d.type==="response.completed"){s=d.response,r=!0;continue}let c=De(d);c&&this.send(c)}if(e.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!r)throw new i("upstream produced no response.completed event",H);let{messages:a,assistantItems:u}=He(s);this.transcript.push(...u);for(let f of a)this.send(f);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},lt=(t,n)=>{let e=t.headers["x-goog-api-key"];if(typeof e=="string")return e;let o=t.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Fe(t,n){let e=new at({noServer:!0}),o=new he;t.on("upgrade",(s,r,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==Ce){r.write(`HTTP/1.1 404 Not Found\r
|
|
3
|
-
Connection: close\r
|
|
4
|
-
\r
|
|
5
|
-
no WS route for ${u.pathname}`),r.destroy();return}if(n.apiKey&<(s,u)!==n.apiKey){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
6
|
-
Connection: close\r
|
|
7
|
-
\r
|
|
8
|
-
invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,f=>{new ye(f,n.clients,o)})})}var ke=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=o}modelEntry(n){let e=this.models[n];if(e)return e;let o=Object.keys(this.models).length>=dt?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let o=this,s=performance.now(),r=null,a=0;return(async function*(){for await(let f of n)f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(r===null&&(r=performance.now(),o.ttftMs.push(r-s),o.ttftMs.length>512&&o.ttftMs.shift()),a+=1,o.tokensOut+=1,o.charsOut+=f.delta.length,e!==void 0&&(o.modelEntry(e).tokens_out+=1)),yield f;let u=(performance.now()-(r??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((o,s)=>o-s);return e[Math.floor(e.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((e,o)=>e+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}};function xe(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function q(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function F(t,n,e,o="invalid_request_error"){q(t,n,{error:{message:e,type:o}})}function B(t,n,e,o){q(t,n,{type:"error",error:{type:e,message:o}})}function Re(t,n,e){if(n==="anthropic"){q(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}q(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var dt=256,pt=128;function Ae(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,pt)}var Ge=64*1024*1024,le=class extends Error{};async function ft(t){let n=[],e=0;for await(let s of t){if(e+=s.length,e>Ge)throw new le(`request body exceeds ${Ge} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function W(t,n,e,o){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:o}]}}var mt=256;function gt(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var ve=class{conversations=new Map;thread(n,e){let o=gt(e);if(n==null)return o;let s=this.conversations.get(String(n));if(!s)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(n,e,o){this.conversations.set(n,[...e,{role:"assistant",content:o}]);for(let s of this.conversations.keys()){if(this.conversations.size<=mt)break;this.conversations.delete(s)}}};function oe(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function z(t){return t.find(n=>n.type==="response.completed")?.response??null}function ce(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=e(n.input_tokens),s=e(n.output_tokens);if(o===0&&s===0)return null;let r=e(n.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:r}}function Ve(t){let n=ce(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Ke(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let s of o.content)s.type==="reasoning_text"&&(e+=String(s.text??""));return e}function se(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var K=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),o=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},ht=["<tool_call>","<function="];function yt(t){return ht.find(n=>t.includes(n))}function X(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Q(t,n,e){if(!(!t||n>0))return yt(e)}function _t(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var de=class extends Error{};function wt(t,n){return Array.isArray(n)?n.map(e=>{let o=e;if(o.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let s=o.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new de(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function kt(t){let n=[];for(let e of t){if(e.role==="tool"){n.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&n.push({role:"assistant",content:e.content});for(let o of e.tool_calls){let s=o.function??{};n.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}n.push({...e,content:wt(e.role,e.content)})}return n}function _e(t){return oe(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function ze(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function vt(t,n,e,o,s){let r=t.stream===!0,a;try{a=e.thread(t.previous_response_id,t.input)}catch(m){F(o,400,String(m instanceof Error?m.message:m));return}t.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(t.input)));let u=`resp_${Math.random().toString(36).slice(2,14)}`,f=t.store!==!1,d=Ae(t);s.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await n.createResponse({model:t.model,input:a,stream:r,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(m){if(m instanceof V){Re(o,"openai",m);return}throw m}let p=[];if(r){xe(o);let m=y=>{o.write(`event: ${String(y.type??"message")}
|
|
9
|
-
data: ${JSON.stringify(y)}
|
|
10
|
-
|
|
11
|
-
`)},P=y=>y.response&&typeof y.response=="object"?{...y,response:{...y.response,id:u}}:y,S=`item_${u.slice(5)}`,M=`rs_${u.slice(5)}`,E=!1,$=!1,l=0,k=()=>{E||(E=!0,m({type:"response.created",response:{id:u,object:"response",status:"in_progress"}}))},U=!1,C=0,L="",j=()=>{U&&(U=!1,m({type:"response.reasoning_text.done",item_id:M,output_index:C,content_index:0,text:L}),m({type:"response.output_item.done",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:L}],status:"completed"}}))},T=!1,w=0,A="",D=y=>{T&&(T=!1,m({type:"response.output_text.done",item_id:S,output_index:w,content_index:0,text:A}),m({type:"response.content_part.done",item_id:S,output_index:w,content_index:0,part:{type:"output_text",text:A}}),m({type:"response.output_item.done",output_index:w,item:{id:S,type:"message",role:"assistant",status:y,content:[{type:"output_text",text:A}]}}))},J=new K,v=null,Y=-1,Z=y=>{if(!v)return;let R=v;v=null,m({type:"response.function_call_arguments.done",item_id:R.fcId,output_index:R.outputIndex,arguments:R.args}),m({type:"response.output_item.done",output_index:R.outputIndex,item:{id:R.fcId,type:"function_call",call_id:R.callId??R.fcId,name:R.name??"",arguments:R.args,status:y}})},ee=!1;for await(let y of s.track(g,d)){p.push(y);let R=String(y.type??"");if(R==="response.created"||R==="response.in_progress"){E=!0,m(P(y));continue}if(R==="response.output_item.added"){$=!0,m(P(y));continue}if(R==="response.reasoning_text.delta"&&!$){k(),U||(U=!0,C=l++,m({type:"response.output_item.added",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[],status:"in_progress"}})),L+=String(y.delta??""),m({type:"response.reasoning_text.delta",item_id:M,output_index:C,content_index:0,delta:y.delta});continue}if(R==="response.output_text.delta"&&!$){k(),j(),T||(T=!0,w=l++,m({type:"response.output_item.added",output_index:w,item:{id:S,type:"message",role:"assistant",status:"in_progress",content:[]}}),m({type:"response.content_part.added",item_id:S,output_index:w,content_index:0,part:{type:"output_text",text:""}})),A+=String(y.delta??""),m({type:R,item_id:S,output_index:w,content_index:0,delta:y.delta});continue}let I=$?null:se(y);if(I){if(k(),j(),D("completed"),J.add(I),I.tool_index!==Y){Z("completed"),Y=I.tool_index;let _=l++;v={fcId:`fc_${u.slice(5)}_${I.tool_index}`,outputIndex:_,callId:I.call_id,name:I.name,args:""},m({type:"response.output_item.added",output_index:_,item:{id:v.fcId,type:"function_call",call_id:v.callId??v.fcId,name:v.name??"",arguments:"",status:"in_progress"}})}v&&(I.call_id&&(v.callId=I.call_id),I.name&&(v.name=I.name),v.args+=I.delta,m({type:"response.function_call_arguments.delta",item_id:v.fcId,output_index:v.outputIndex,delta:I.delta}));continue}if(R==="response.completed"&&!$){let _=oe(y.response),b=Q(c,J.size+_.length,A);if(b){ee=!0,m({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:X(d,b)}});break}j(),D("completed"),Z("completed"),J.size===0&&_.forEach(G=>{let te=l++,ie=G.id??G.call_id??`fc_${te}`,fe=G.arguments??"",Se={id:ie,type:"function_call",call_id:G.call_id??ie,name:G.name??""};m({type:"response.output_item.added",output_index:te,item:{...Se,arguments:"",status:"in_progress"}}),m({type:"response.function_call_arguments.delta",item_id:ie,output_index:te,delta:fe}),m({type:"response.function_call_arguments.done",item_id:ie,output_index:te,arguments:fe}),m({type:"response.output_item.done",output_index:te,item:{...Se,arguments:fe,status:"completed"}})}),m(P(y));continue}m(P(y))}j(),D("incomplete"),Z("incomplete"),f&&!ee&&e.remember(u,a,ze(p,z(p))),o.write(`data: [DONE]
|
|
12
|
-
|
|
13
|
-
`),o.end();return}let h=null;for await(let m of s.track(g,d)){if(p.push(m),m.type==="error"){F(o,502,JSON.stringify(m),"upstream_error");return}m.type==="response.completed"&&(h=m.response)}if(h==null){F(o,502,"upstream produced no response.completed event","upstream_error");return}let O=ze(p,h),N=Q(c,oe(h).length,O);if(N){F(o,502,X(d,N),"upstream_error");return}f&&e.remember(u,a,O),q(o,200,{...h,id:u})}async function xt(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){F(e,400,"chat/completions requires a messages array");return}let r=String(t.model??"urun"),a=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,u;try{u=kt(s)}catch(l){if(l instanceof de){F(e,400,l.message);return}throw l}let f=Ae(t);o.model(f);let d=Array.isArray(t.tools)&&t.tools.length>0,c;try{c=await n.createResponse({model:t.model,input:u,stream:!0,tools:_t(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(l){if(l instanceof V){Re(e,"openai",l);return}throw l}if(t.stream===!0){xe(e);let l=[],k=new K,U="";e.write(`data: ${JSON.stringify(W(a,r,{role:"assistant"},null))}
|
|
14
|
-
|
|
15
|
-
`);for await(let w of o.track(c,f)){l.push(w);let A=se(w);if(w.type==="response.output_text.delta"&&typeof w.delta=="string")U+=w.delta,e.write(`data: ${JSON.stringify(W(a,r,{content:w.delta},null))}
|
|
16
|
-
|
|
17
|
-
`);else if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")e.write(`data: ${JSON.stringify(W(a,r,{reasoning_content:w.delta},null))}
|
|
18
|
-
|
|
19
|
-
`);else if(A){let{call:D,isNew:J}=k.add(A),v=J?{index:A.tool_index,id:D.id??`call_${A.tool_index}`,type:"function",function:{name:D.name??"",arguments:A.delta}}:{index:A.tool_index,function:{arguments:A.delta}};e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:[v]},null))}
|
|
20
|
-
|
|
21
|
-
`)}else if(w.type==="error"){e.write(`data: ${JSON.stringify({error:w})}
|
|
22
|
-
|
|
23
|
-
`),e.end();return}}let C=_e(z(l)),L=Q(d,k.size+C.length,U);if(L){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:X(f,L)}})}
|
|
24
|
-
|
|
25
|
-
`),e.end();return}k.size===0&&C.length>0&&e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:C},null))}
|
|
26
|
-
|
|
27
|
-
`);let j=k.size>0||C.length>0;e.write(`data: ${JSON.stringify(W(a,r,{},j?"tool_calls":"stop"))}
|
|
28
|
-
|
|
29
|
-
`),ce(z(l))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[],usage:Ve(z(l))})}
|
|
30
|
-
|
|
31
|
-
`),e.write(`data: [DONE]
|
|
32
|
-
|
|
33
|
-
`),e.end();return}let g="",p="",h=[],O=new K;for await(let l of o.track(c,f)){h.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(g+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(p+=l.delta);let k=se(l);if(k&&O.add(k),l.type==="error"){F(e,502,JSON.stringify(l),"upstream_error");return}}let N=z(h),m=_e(N),P=m.length>0?m:_e({output:O.items()}),S=Q(d,P.length,g);if(S){F(e,502,X(f,S),"upstream_error");return}let M=P.map(({index:l,...k})=>k),E={role:"assistant",content:g||null},$=p||Ke(N);$&&(E.reasoning_content=$),M.length>0&&(E.tool_calls=M),q(e,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,message:E,finish_reason:M.length>0?"tool_calls":"stop"}],usage:Ve(N)})}function Rt(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var re=class extends Error{};function pe(t){return new re(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function At(t){if(Array.isArray(t))return t.map(n=>{let e=n;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema}})}function St(t){if(t==null)return;let n=t.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:t.name};throw new re(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function It(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw pe(typeof t);let n="";for(let e of t){let o=String(e.type??"");if(o!=="text")throw pe(`tool_result > ${o}`);n+=String(e.text??"")}return n}function bt(t){let{role:n,content:e}=t;if(typeof e=="string")return[{role:n,content:e}];if(e==null)return[];if(!Array.isArray(e))throw pe(typeof e);let o=[],s="",r=()=>{s&&(o.push({role:n,content:s}),s="")};for(let a of e){let u=String(a.type??"");if(u==="text")s+=String(a.text??"");else if(u==="tool_use")r(),o.push({type:"function_call",call_id:a.id,name:a.name,arguments:JSON.stringify(a.input??{})});else if(u==="tool_result")r(),o.push({type:"function_call_output",call_id:a.tool_use_id,output:It(a.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw pe(u)}}return r(),o}function we(t){return oe(t).map((n,e)=>{let o;try{o=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${e}`,name:n.name??"",input:o}})}async function Ot(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){B(e,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){B(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){B(e,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(l=>typeof l!="string"))){B(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let r=String(t.model??"urun"),a=`msg_${Math.random().toString(36).slice(2,14)}`,u=[],f;try{t.system&&u.push({role:"system",content:Rt(t.system)});for(let l of s)u.push(...bt(l));f=St(t.tool_choice)}catch(l){if(l instanceof re){B(e,400,"invalid_request_error",l.message);return}throw l}let d=Ae(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await n.createResponse({model:t.model,input:u,stream:!0,tools:At(t.tools),tool_choice:f,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences})}catch(l){if(l instanceof V){Re(e,"anthropic",l);return}throw l}let p=(l,k)=>{e.destroyed||e.write(`event: ${l}
|
|
34
|
-
data: ${JSON.stringify({type:l,...k})}
|
|
35
|
-
|
|
36
|
-
`)};if(t.stream===!0){let l=o.track(g,d);xe(e),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:r,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let k=0,U="",C=0,L="none",j=()=>L,T=-1,w=-1,A=new K,D=[],J=()=>{L!=="none"&&(L="none",p("content_block_stop",{index:T}))},v=(_,b)=>{J(),L=_,T=C++,p("content_block_start",{index:T,content_block:b})};for await(let _ of l){if(e.destroyed)break;D.push(_);let b=se(_);if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")j()!=="thinking"&&v("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:T,delta:{type:"thinking_delta",thinking:_.delta}});else if(_.type==="response.output_text.delta"&&typeof _.delta=="string")j()!=="text"&&v("text",{type:"text",text:""}),k+=1,U+=_.delta,p("content_block_delta",{index:T,delta:{type:"text_delta",text:_.delta}});else if(b){let{call:G}=A.add(b);(j()!=="tool"||b.tool_index!==w)&&(w=b.tool_index,v("tool",{type:"tool_use",id:G.id??`call_${b.tool_index}`,name:G.name??"",input:{}})),b.delta&&p("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:b.delta}})}else if(_.type==="error"){p("error",{error:{type:"api_error",message:JSON.stringify(_)}}),e.end();return}}if(e.destroyed)return;let Y=z(D),Z=oe(Y),ee=Q(c,A.size+Z.length,U);if(ee){p("error",{error:{type:"api_error",message:X(d,ee)}}),e.end();return}J();let y=[];if(A.size===0)try{y=we(Y)}catch(_){p("error",{error:{type:"api_error",message:String(_ instanceof Error?_.message:_)}}),e.end();return}C===0&&y.length===0&&(v("text",{type:"text",text:""}),J()),y.forEach(_=>{let b=C++;p("content_block_start",{index:b,content_block:{..._,input:{}}}),p("content_block_delta",{index:b,delta:{type:"input_json_delta",partial_json:JSON.stringify(_.input??{})}}),p("content_block_stop",{index:b})});let R=A.size>0||y.length>0,I=ce(Y);p("message_delta",{delta:{stop_reason:R?"tool_use":"end_turn"},usage:I?{input_tokens:I.input_tokens,output_tokens:I.output_tokens}:{output_tokens:k}}),p("message_stop",{}),e.end();return}let h="",O="",N=[],m=new K;for await(let l of o.track(g,d)){N.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(h+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(O+=l.delta);let k=se(l);if(k&&m.add(k),l.type==="error"){B(e,502,"api_error",JSON.stringify(l));return}if(e.destroyed)break}if(e.destroyed)return;let P=z(N),S;try{S=we(P),S.length===0&&m.size>0&&(S=we({output:m.items()}))}catch(l){B(e,502,"api_error",String(l instanceof Error?l.message:l));return}let M=Q(c,S.length,h);if(M){B(e,502,"api_error",X(d,M));return}let E=[],$=O||Ke(P);$&&E.push({type:"thinking",thinking:$}),(h||S.length===0)&&E.push({type:"text",text:h}),E.push(...S),q(e,200,{id:a,type:"message",role:"assistant",content:E,model:r,stop_reason:S.length>0?"tool_use":"end_turn",usage:ce(P)??{input_tokens:0,output_tokens:0}})}function Dt(t){let{clients:n,apiKey:e,identity:o}=t,s=new ve,r=new ke,a=ct((u,f)=>{let d=new URL(u.url??"/","http://localhost"),c=d.pathname==="/v1/messages"||d.pathname.startsWith("/v1/messages/"),g=(p,h,O,N)=>c?B(f,p,N,h):F(f,p,h,O);(async()=>{if(u.method==="GET"&&d.pathname==="/healthz"){q(f,200,{ok:!0});return}if(u.method==="GET"&&d.pathname==="/stats"){q(f,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(e&&(u.headers.authorization??"")!==`Bearer ${e}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}if(u.method==="GET"&&d.pathname==="/v1/models"){q(f,200,await n.listModels());return}if(u.method!=="POST"){g(404,`no route for ${u.method} ${d.pathname}`,"invalid_request_error","not_found_error");return}let p;try{p=await ft(u)}catch(O){if(O instanceof le){g(413,O.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let h=Buffer.byteLength(JSON.stringify(p));if(d.pathname==="/v1/responses"){r.request("responses",h,h),await vt(p,n,s,f,r);return}if(d.pathname==="/v1/chat/completions"){r.request("chat_completions",h,h),await xt(p,n,f,r);return}if(d.pathname==="/v1/messages"){r.request("messages",h,h),await Ot(p,n,f,r);return}if(d.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",h,h),B(f,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}g(404,`no route for POST ${d.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let h=String(p instanceof Error?p.message:p);if(!f.headersSent){g(500,h,"proxy_error","api_error");return}f.destroyed||(c?f.write(`event: error
|
|
37
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
|
|
38
|
-
|
|
39
|
-
`):f.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
|
|
40
|
-
|
|
41
|
-
`)),f.end()})});return Fe(a,{clients:n,apiKey:e}),a}export{Ce as a,Dt as b};
|
package/dist/chunk-OLE2YJO3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
async function a(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}async function i(t){return{object:"list",data:(await a(t)).map(e=>({id:`${e.model_id}:${e.variant}`,object:"model",created:0,owned_by:"urun"}))}}export{a,i as b};
|
package/dist/chunk-SSZL77P5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function g(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let n=e,r=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:r.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}function _(e,n,r,t){let o=e.response??{},i={request_id:r,consumer_id:t,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function f(e,n,r){let t={request_id:n,consumer_id:r,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(t.model=e.model),e.tools!==void 0&&(t.tools=e.tools),e.tool_choice!==void 0&&(t.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(t.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(t.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(t.chat_template_kwargs=e.chat_template_kwargs),t}var w="llm-resp";async function*d(e,n){let r=`${w}:${n}`,t=`resp_${n}`;yield{type:"response.created",response:{id:t,status:"in_progress"}};let o=new Map;for await(let i of e.stream(r).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:t,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:t,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let p=typeof a.index=="number"?a.index:0,u=o.get(p)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(p,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${p}`,tool_index:p,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:t,status:"completed",...s.body}};return}else if(s.t==="error"){yield g(s);return}}}var b="llm",m=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(b).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,r){let t=f(n,r,this.consumerId);return this.write(t),d(this.session,r)}sendResponseCreate(n,r,t){let o=_(n,r,t,this.consumerId);return this.write(o),d(this.session,t)}};var y=0;function h(){return y+=1,`req_${Date.now().toString(36)}_${y.toString(36)}`}var k=class{transport;constructor(n){this.transport=new m(n)}responses={create:async n=>{let r=h(),t=this.transport.sendResponses(n,r);return Object.assign((async function*(){yield*t})(),{requestId:r})}}};export{g as a,m as b,k as c};
|
package/dist/chunk-VFHQZ4OM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var l=class{constructor(n,e){this.backend=n;this.opts=e}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let e=Buffer.from(n,"base64"),t=Math.floor(e.byteLength/2),a=new Int16Array(t);for(let o=0;o<t;o++)a[o]=e.readInt16LE(o*2);this.source.onData(a)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=e=>{let t=Buffer.from(e.samples.buffer,e.samples.byteOffset,e.samples.byteLength).toString("base64");for(let a of this.outHandlers)a(t)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function R(r,n,e=1e4){let t=new l(n,{sampleRate:24e3}),a=await t.startOutbound();await r.stream("rt-audio-in").attach(a);let o=await h(r,e);return await t.startInbound(o),t}function h(r,n){let e=r.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((t,a)=>{let o,i=setTimeout(()=>{o?.(),a(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),u=s=>{s!=null&&(clearTimeout(i),o?.(),t(s))};o=e.on?.("track",u),e.track!=null&&u(e.track)})}var m="rt-video-in",p=256e3;function E(r){let n=r.stream(m),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${m}') 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 t=>{if(t.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(t.byteLength>p)throw new Error(`enableSessionVideo: frame is ${t.byteLength} bytes \u2014 over the ${p}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await e.call(n,t)}}}var S=24e3,d=480,y=111;async function v(){let r=await import("opusscript"),n=r.default??r;return new n(S,1,2048)}async function g(){let r=await import("werift"),n=await v();return{createSource:()=>{let e=new r.MediaStreamTrack({kind:"audio"}),t=Math.random()*4294967295>>>0,a=Math.random()*65535&65535,o=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:e,onData:u=>{let s=new Int16Array(i.length+u.length);s.set(i,0),s.set(u,i.length);let c=0;for(;s.length-c>=d;){let f=s.subarray(c,c+d);c+=d;let k=Buffer.from(f.buffer,f.byteOffset,f.byteLength),w=n.encode(k,d);a=a+1&65535,o=o+d>>>0;let A=new r.RtpHeader({version:2,payloadType:y,sequenceNumber:a,timestamp:o,ssrc:t,marker:!1}),b=new r.RtpPacket(A,w);e.writeRtp(b)}i=s.slice(c)}}},createSink:e=>{let t={onframe:null};return e.onReceiveRtp.subscribe(o=>{let i;try{i=n.decode(o.payload)}catch{return}let u=new Int16Array(i.length/2);for(let s=0;s<u.length;s++)u[s]=i.readInt16LE(s*2);t.onframe?.({samples:u})}),t}}}async function P(){let r=await import("@roamhq/wrtc");return{createSource:()=>{let n=new r.nonstandard.RTCAudioSource;return{track:n.createTrack(),onData:t=>n.onData({samples:t,sampleRate:24e3})}},createSink:n=>{let e={onframe:null},t=new r.nonstandard.RTCAudioSink(n);return t.ondata=a=>{e.onframe?.(a)},e}}}export{R as a,E as b,g as c,P as d};
|
package/dist/chunk-VXTNG2TP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var v="https://api.urun.sh/v1";function c(o){return o.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var a=class extends Error{},p=class extends Error{},u="urs1.";function f(o,e){return u+Buffer.from(JSON.stringify([o,e]),"utf8").toString("base64url")}function g(o){if(!o.startsWith(u))return null;try{let e=JSON.parse(Buffer.from(o.slice(u.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function A(o){let e=o.fetchImpl??fetch,t=`${o.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(t,{headers:{Authorization:`Bearer ${o.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${s.status}`);let i=await s.json();if(!Array.isArray(i.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(i.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${i.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return i.apps}var y=6e4,h=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??y;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let t=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:t},t}servable(e){return e.filter(t=>t.function_name===this.opts.fnName&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=new Set([this.opts.defaultApp]);if(this.opts.listApps)for(let t of this.servable(await this.deployedApps()))e.add(t);for(let t of this.pool.keys())e.add(t);return[this.opts.defaultApp,...[...e].filter(t=>t!==this.opts.defaultApp).sort()]}async resolveApp(e){let t=(e??"").trim();if(!t||t==="urun")return this.opts.defaultApp;let s=c(t);if(s===this.opts.defaultApp)return this.opts.defaultApp;if(this.pool.has(s))return s;if(this.opts.listApps){let i=await this.deployedApps(),r=this.servable(i);if(r.includes(s))return s;let n=r.filter(d=>d.startsWith(`${s}-`));if(n.length===1)return n[0];if(n.length>1)throw new a(`model "${t}" is ambiguous across deployed apps ${n.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===s||d.app_slug.startsWith(`${s}-`));if(l)throw new a(`model "${t}" maps to app "${l.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let r=(await this.opts.listCatalog()).find(n=>t===n.model_id||t===`${n.model_id}:${n.variant}`||s===c(n.model_id)||s===c(`${n.model_id}-${n.variant}`));if(r)throw new a(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${r.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return this.opts.defaultApp}async sessionFor(e){let t=await this.resolveApp(e),s=this.pool.get(t);return s||(s=Promise.resolve(this.opts.openSession(t)),this.pool.set(t,s),s.catch(()=>this.pool.delete(t))),{app:t,entry:await s}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let s=t(e);if(typeof s!="string"||s.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return s}async handleFor(e){let{app:t,entry:s}=await this.sessionFor(e);return{app:t,handle:f(t,this.keyOf(s))}}async sessionForHandle(e){let t=g(e);if(!t)throw new p(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:s,key:i}=t,r=this.pool.get(s),n=r?await r.then(l=>l,()=>null):null;if(n===null)throw new p(`the session behind this handle (app "${s}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(n)!==i)throw new p(`the session behind this handle (app "${s}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:s,entry:n}}async evict(e,t){let s=this.pool.get(e);!s||await s.then(r=>r,()=>null)!==t||this.pool.get(e)!==s||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(t=>({id:t,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let e=[...this.pool.values()];this.pool.clear();let t=[];if(await Promise.all(e.map(async s=>{try{await this.opts.closeSession(await s)}catch(i){t.push(String(i instanceof Error?i.message:i))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{v as a,a as b,p as c,A as d,h as e};
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
/** Pluggable audio backend so tests don't need real WebRTC. In production, `nodeAudioBackend()` wraps @roamhq/wrtc. */
|
|
2
|
-
interface AudioSource {
|
|
3
|
-
track: unknown;
|
|
4
|
-
onData(frame: Int16Array): void;
|
|
5
|
-
}
|
|
6
|
-
interface AudioSink {
|
|
7
|
-
onframe: ((frame: {
|
|
8
|
-
samples: Int16Array;
|
|
9
|
-
}) => void) | null;
|
|
10
|
-
}
|
|
11
|
-
interface AudioBackend {
|
|
12
|
-
createSource(): AudioSource;
|
|
13
|
-
/**
|
|
14
|
-
* Build a sink that pulls PCM16 frames OFF the runtime's downstream audio
|
|
15
|
-
* track (`remoteTrack`, the real Opus `MediaStreamTrack` the SFU now produces
|
|
16
|
-
* — see session-server-ts audio ingest). The production backend wires a real
|
|
17
|
-
* `RTCAudioSink(remoteTrack)`; the sink's `onframe` is invoked per decoded
|
|
18
|
-
* 10ms frame. `remoteTrack` is REQUIRED — a missing track is a wiring bug, not
|
|
19
|
-
* a silent no-op (a dead sink is exactly the placeholder this replaces).
|
|
20
|
-
*/
|
|
21
|
-
createSink(remoteTrack: unknown): AudioSink;
|
|
22
|
-
}
|
|
23
|
-
declare class AudioBridge {
|
|
24
|
-
private readonly backend;
|
|
25
|
-
private readonly opts;
|
|
26
|
-
private source;
|
|
27
|
-
private sink;
|
|
28
|
-
private outHandlers;
|
|
29
|
-
constructor(backend: AudioBackend, opts: {
|
|
30
|
-
sampleRate: number;
|
|
31
|
-
});
|
|
32
|
-
startOutbound(): Promise<unknown>;
|
|
33
|
-
/** OpenAI: input_audio_buffer.append (base64 PCM16) → publish frames. */
|
|
34
|
-
appendInputAudio(base64Pcm16: string): void;
|
|
35
|
-
/**
|
|
36
|
-
* Wire the runtime's downstream audio track into the output-frame fan-out.
|
|
37
|
-
* `remoteTrack` is the REAL Opus `MediaStreamTrack` the SFU produces for this
|
|
38
|
-
* session (`session.stream('rt-audio-out').track`). The backend attaches a
|
|
39
|
-
* real `RTCAudioSink` to it; each decoded PCM16 frame is re-emitted as base64
|
|
40
|
-
* to every `onOutputAudio` handler (the OpenAI `response.audio.delta` source).
|
|
41
|
-
*
|
|
42
|
-
* Throws if `remoteTrack` is absent — the previous build silently created a
|
|
43
|
-
* dead sink that never fired, so voice OUT looked "wired" but produced no
|
|
44
|
-
* audio. A missing track here means the consume side did not attach yet; the
|
|
45
|
-
* caller must await the real track before calling this.
|
|
46
|
-
*/
|
|
47
|
-
startInbound(remoteTrack: unknown): Promise<void>;
|
|
48
|
-
/** Emits base64 PCM16 → caller wraps as OpenAI response.audio.delta. */
|
|
49
|
-
onOutputAudio(handler: (base64Pcm16: string) => void): () => void;
|
|
50
|
-
}
|
|
51
|
-
/** The frame-lane handle: one encoded JPEG frame per call, in call order. */
|
|
52
|
-
interface VideoFrameLane {
|
|
53
|
-
sendInputFrame(jpegFrame: Uint8Array): Promise<void>;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Production backend for the werift transport (@urun-sh/core). Replaces the
|
|
57
|
-
* wrtc backend, whose `RTCAudioSink`/`RTCAudioSource` are incompatible with
|
|
58
|
-
* werift's read-only-`id` `MediaStreamTrack`.
|
|
59
|
-
*/
|
|
60
|
-
declare function weriftAudioBackend(): Promise<AudioBackend>;
|
|
61
|
-
/**
|
|
62
|
-
* @deprecated wrtc backend — INCOMPATIBLE with @urun-sh/core's werift transport
|
|
63
|
-
* (its `RTCAudioSink`/`RTCAudioSource` set the foreign track's read-only `id`).
|
|
64
|
-
* Use {@link weriftAudioBackend}. Kept for any non-werift transport.
|
|
65
|
-
*/
|
|
66
|
-
declare function nodeAudioBackend(): Promise<AudioBackend>;
|
|
67
|
-
|
|
68
|
-
export { type AudioBackend as A, type VideoFrameLane as V, AudioBridge as a, type AudioSink as b, type AudioSource as c, nodeAudioBackend as n, weriftAudioBackend as w };
|
package/dist/media-DCHTX3Ez.d.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
interface AudioSource {
|
|
3
|
-
track: unknown;
|
|
4
|
-
onData(frame: Int16Array): void;
|
|
5
|
-
}
|
|
6
|
-
interface AudioSink {
|
|
7
|
-
onframe: ((frame: {
|
|
8
|
-
samples: Int16Array;
|
|
9
|
-
}) => void) | null;
|
|
10
|
-
}
|
|
11
|
-
interface AudioBackend {
|
|
12
|
-
createSource(): AudioSource;
|
|
13
|
-
|
|
14
|
-
createSink(remoteTrack: unknown): AudioSink;
|
|
15
|
-
}
|
|
16
|
-
declare class AudioBridge {
|
|
17
|
-
private readonly backend;
|
|
18
|
-
private readonly opts;
|
|
19
|
-
private source;
|
|
20
|
-
private sink;
|
|
21
|
-
private outHandlers;
|
|
22
|
-
constructor(backend: AudioBackend, opts: {
|
|
23
|
-
sampleRate: number;
|
|
24
|
-
});
|
|
25
|
-
startOutbound(): Promise<unknown>;
|
|
26
|
-
|
|
27
|
-
appendInputAudio(base64Pcm16: string): void;
|
|
28
|
-
|
|
29
|
-
startInbound(remoteTrack: unknown): Promise<void>;
|
|
30
|
-
|
|
31
|
-
onOutputAudio(handler: (base64Pcm16: string) => void): () => void;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
interface VideoFrameLane {
|
|
35
|
-
sendInputFrame(jpegFrame: Uint8Array): Promise<void>;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
declare function weriftAudioBackend(): Promise<AudioBackend>;
|
|
39
|
-
|
|
40
|
-
declare function nodeAudioBackend(): Promise<AudioBackend>;
|
|
41
|
-
|
|
42
|
-
export { type AudioBackend as A, type VideoFrameLane as V, AudioBridge as a, type AudioSink as b, type AudioSource as c, nodeAudioBackend as n, weriftAudioBackend as w };
|