@urun-sh/openai 0.6.42 → 0.6.44
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-gfg7qUoE.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
- package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
- package/dist/chunk-64VO62LW.js +1 -0
- package/dist/chunk-BA3NCMS5.js +6 -0
- package/dist/chunk-DMRZZTYI.js +4 -0
- package/dist/chunk-FNAZ2XBE.js +20 -0
- package/dist/chunk-G6AFKOVS.js +1 -0
- package/dist/{chunk-4NMMWAKD.js → chunk-HB5KNEY5.js} +1 -1
- package/dist/chunk-J3KCHTSA.js +6 -0
- package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
- package/dist/chunk-VQSCBUKT.js +66 -0
- package/dist/{chunk-QTHFMDZY.js → chunk-X5BLQXHK.js} +1 -1
- package/dist/chunk-XNRPTMSL.js +1 -0
- package/dist/chunk-Y774TOE7.js +2 -0
- package/dist/{composite-B-F2J0NK.d.cts → composite-DM2sT1Sp.d.cts} +320 -4
- package/dist/{composite-B--rGI5m.d.ts → composite-DNNAm0PY.d.ts} +91 -4
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +4 -4
- package/dist/gemini-live.d.ts +4 -4
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +49 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +45 -43
- package/dist/hosted/index.d.cts +54 -10
- package/dist/hosted/index.d.ts +11 -5
- package/dist/hosted/index.js +1 -1
- 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 +7 -7
- package/dist/pi-extension/index.d.cts +2 -2
- package/dist/pi-extension/index.d.ts +2 -2
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +55 -55
- package/dist/pooler/bin.cjs +40 -41
- package/dist/pooler/bin.js +39 -40
- package/dist/proxy/cli.cjs +55 -53
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.cjs +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +34 -32
- package/dist/proxy/index.d.cts +37 -214
- package/dist/proxy/index.d.ts +17 -65
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-Dox25ky9.d.cts → translator-C6MpaZS-.d.cts} +1 -1
- package/dist/{translator-BqpmZ-vh.d.ts → translator-CaOqL-V8.d.ts} +1 -1
- package/dist/{types-CHPtJx6d.d.cts → types-DiYzfHYN.d.cts} +2 -0
- package/dist/{types-CHPtJx6d.d.ts → types-DiYzfHYN.d.ts} +2 -0
- package/dist/{video-out-DnCKUUO2.d.cts → video-out-A8qMuI36.d.cts} +17 -3
- package/dist/{video-out-REmiQMBJ.d.ts → video-out-IoTqIbAw.d.ts} +6 -2
- package/package.json +2 -2
- package/dist/chunk-G7CSAISC.js +0 -1
- package/dist/chunk-GX243AIV.js +0 -1
- package/dist/chunk-HPUX2H65.js +0 -6
- package/dist/chunk-IFYB6QUQ.js +0 -64
- package/dist/chunk-KKCUIOL4.js +0 -1
- package/dist/chunk-OZ7HE3VG.js +0 -23
- package/dist/chunk-QNJKRB7Q.js +0 -2
- package/dist/chunk-XKCWX72M.js +0 -6
- package/dist/chunk-Z3QCHKJB.js +0 -1
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,215 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { P as ProxyClients,
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as
|
|
4
|
-
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-
|
|
1
|
+
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
+
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-DM2sT1Sp.cjs';
|
|
3
|
+
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-DM2sT1Sp.cjs';
|
|
4
|
+
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-C6MpaZS-.cjs';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.cjs';
|
|
7
|
-
import '../video-out-
|
|
8
|
-
import '../types-
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* `attachOpenAIRealtime(server, options)` — the WS upgrade hook for the OpenAI
|
|
12
|
-
* Realtime surface (GA protocol subset; see protocol.ts for the event subset).
|
|
13
|
-
*
|
|
14
|
-
* Contract (Main-owned composition; this lane claims ONLY `/v1/realtime`):
|
|
15
|
-
* - Upgrades on any other path are passed through UNTOUCHED — a plain
|
|
16
|
-
* `next()` listener, so sibling lanes (Gemini Live, Responses WS) and the
|
|
17
|
-
* hosted composition keep their own upgrade hooks.
|
|
18
|
-
* - Clients are resolved/authenticated ASYNCHRONOUSLY BEFORE the upgrade is
|
|
19
|
-
* accepted: no 101 is written until `resolver.resolve(req, signal)`
|
|
20
|
-
* settles. A thrown error maps `err.status` (default 502) to the HTTP
|
|
21
|
-
* reject; 401/403 keep their status.
|
|
22
|
-
* - THE CLIENT SOCKET'S OWN CLOSE is the cancellation signal for the wait:
|
|
23
|
-
* a `close`/`error` on the raw pre-upgrade socket aborts the signal the
|
|
24
|
-
* resolver rides. A resolver that settles AFTER the client vanished never
|
|
25
|
-
* upgrades — its binding is released through the binding's own `release`
|
|
26
|
-
* seam (the native detach; a still-queued admission ticket is cancelled
|
|
27
|
-
* underneath it by the backhaul's abort path). A client that closes after
|
|
28
|
-
* admission tears down through the connection's own ws-close wiring.
|
|
29
|
-
* - ONE structured log line per upgrade lifecycle event (`realtime_upgrade`:
|
|
30
|
-
* accept → admit → close, with the binding's session id and the client
|
|
31
|
-
* close reason) — the lane was previously invisible in the process log.
|
|
32
|
-
* - The resolved binding carries a PRIVATE native uRun session (fresh or
|
|
33
|
-
* explicitly-resumed) and, iff voice, a PRIVATE audio bridge — never the
|
|
34
|
-
* pooled tenant lane. The connection's cross-caller claim is invariant
|
|
35
|
-
* validation, not capacity policy.
|
|
36
|
-
* - Returns an async close function: waits for every touched socket to
|
|
37
|
-
* settle, then closes the internal WebSocketServer. It does NOT end the
|
|
38
|
-
* native uRun sessions (detach ≠ session death — resume is Main-owned;
|
|
39
|
-
* the binding seam decides lifetime).
|
|
40
|
-
*/
|
|
41
|
-
|
|
42
|
-
declare const OPENAI_REALTIME_PATH = "/v1/realtime";
|
|
43
|
-
/**
|
|
44
|
-
* The resolver seam — the ONLY credential, modality, and session-allocation
|
|
45
|
-
* authority this adapter recognizes. Implemented by Main's composition (and
|
|
46
|
-
* by tests with an injected fake). Accepted in EITHER form: a bare
|
|
47
|
-
* `(req, signal) => Promise<binding>` (the {@link ProxyClientsFor}-style
|
|
48
|
-
* convention) or a `{ resolve(req, signal) }` object. `signal` aborts when
|
|
49
|
-
* the CLIENT SOCKET closes/errors before the upgrade is accepted — the
|
|
50
|
-
* resolver SHOULD abandon its admission wait on it (the backhaul's
|
|
51
|
-
* `openAudioOn` rides the same signal into core `whenLive`'s own abort
|
|
52
|
-
* support); a resolver that ignores it still cannot admit an upgrade to a
|
|
53
|
-
* vanished client: the settled binding is released, never upgraded.
|
|
54
|
-
*/
|
|
55
|
-
type OpenAIRealtimeResolver<S = unknown> = ((req: IncomingMessage, signal?: AbortSignal) => Promise<RealtimeBinding<S>>) | {
|
|
56
|
-
resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<S>>;
|
|
57
|
-
};
|
|
58
|
-
interface RealtimeBinding<S = unknown> {
|
|
59
|
-
/**
|
|
60
|
-
* The PRIVATE native uRun session serving this conversation (the shared
|
|
61
|
-
* per-conversation factory in hosted/tenants.ts allocates it; reuse/multi-
|
|
62
|
-
* attach is sanctioned ONLY for the SAME authorized conversation on an
|
|
63
|
-
* explicit resume — two different conversations MUST NOT receive one
|
|
64
|
-
* session). The upstream turn seam is EITHER form:
|
|
65
|
-
* - `session.sendResponseCreate(params, input, requestId)` (the direct
|
|
66
|
-
* SdkTransport-style seam), or
|
|
67
|
-
* - `clients.createResponse(params)` — the canonical ProxyClients seam
|
|
68
|
-
* shape (`input` rides inside `params`). The shared binding composition
|
|
69
|
-
* (binding.ts, ENG-446) hands out a PINNED view of it: the call dials
|
|
70
|
-
* `createResponseOn(handle, …)` on the ONE pooled session the binding
|
|
71
|
-
* resolved with the audio bridge, so no turn on the connection can
|
|
72
|
-
* reach a second pooled session behind the bridge's back.
|
|
73
|
-
* A binding with neither is rejected at upgrade time, LOUD.
|
|
74
|
-
*/
|
|
75
|
-
session?: S & {
|
|
76
|
-
sendResponseCreate?(params: unknown, input: unknown[], requestId: string): Promise<AsyncIterable<unknown>>;
|
|
77
|
-
};
|
|
78
|
-
clients?: Pick<ProxyClients, 'createResponse'>;
|
|
79
|
-
/**
|
|
80
|
-
* Authoritative modality verdict from the resolver. A function NAME proves
|
|
81
|
-
* nothing — without `voice: true`, audio events are refused and no audio
|
|
82
|
-
* primitive is ever opened on the session.
|
|
83
|
-
*/
|
|
84
|
-
voice: boolean;
|
|
85
|
-
/** The PRIVATE audio bridge for THIS conversation (required iff `voice`). */
|
|
86
|
-
audioSession?: {
|
|
87
|
-
audio: {
|
|
88
|
-
appendInputAudio(base64Pcm16: string): void;
|
|
89
|
-
onOutputAudio(handler: (b64: string) => void): () => void;
|
|
90
|
-
/**
|
|
91
|
-
* The pooled uRun session this lane rides (backhaul `openAudioOn`
|
|
92
|
-
* reports core `Session.id`), when the backhaul knows it — the field the
|
|
93
|
-
* `realtime_upgrade` log line puts on every lifecycle event so an
|
|
94
|
-
* orphaned session is traceable from the proxy log alone. Null is the
|
|
95
|
-
* honest absence (an id-less session reports no id); sessionIdOf
|
|
96
|
-
* normalizes it to the omitted field below.
|
|
97
|
-
*/
|
|
98
|
-
sessionId?: string | null;
|
|
99
|
-
};
|
|
100
|
-
/** Cross-caller reuse registry (invariant validation; see connection.ts). */
|
|
101
|
-
openaiRealtimeClaims?: Set<RealtimeBinding['audioSession']>;
|
|
102
|
-
};
|
|
103
|
-
/** `model` the binding names for this conversation (overrides session config default). */
|
|
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>;
|
|
116
|
-
/**
|
|
117
|
-
* The GA transcription-session intent (`?intent=transcription`): this
|
|
118
|
-
* connection is a TRANSCRIPTION session — transcription events flow
|
|
119
|
-
* without the client opting in, and `response.create` answers the loud
|
|
120
|
-
* `unsupported` error (the connection stays open) because there are no
|
|
121
|
-
* model turns to create. Set by the shared binding composition (binding.ts)
|
|
122
|
-
* only when the resolver's URL carried the intent AND the model's catalog
|
|
123
|
-
* row vouches stt (the binding carries `turns`). Absent = the realtime
|
|
124
|
-
* (voice) session, today's behaviour.
|
|
125
|
-
*/
|
|
126
|
-
intent?: 'transcription';
|
|
127
|
-
/** True when `session` is a resumed authorized session (vs a fresh private one). */
|
|
128
|
-
resumed?: boolean;
|
|
129
|
-
/**
|
|
130
|
-
* The backend's OWN turn/transcript lane — the §5 `stt` named stream
|
|
131
|
-
* (urun.serve.transcribe_bridge wire shape: `t` = delta/final/turn_start/
|
|
132
|
-
* turn_end/turn_eager_end/turn_resumed, `delta` text, additive `start_ms`
|
|
133
|
-
* and semantic-VAD `confidence`). The resolver maps `session.stream('stt')
|
|
134
|
-
* .messages()` onto this. Its `turn_end` IS the native commit and
|
|
135
|
-
* `turn_start` IS the native barge-in — the adapter drives server-VAD
|
|
136
|
-
* emulation, real transcription events, and model-visible committed audio
|
|
137
|
-
* from it. Absent = the backend wired no turn lane: manual mode only.
|
|
138
|
-
*
|
|
139
|
-
* The CONSUMER passes its own lifecycle `signal` (the realtime connection's
|
|
140
|
-
* turn-lane controller): the lane must END its stream subscription when it
|
|
141
|
-
* aborts — the transport races its pulls against it — so the subscription
|
|
142
|
-
* never outlives the consumer. A consumer that passes none gets an
|
|
143
|
-
* un-raced lane (its own teardown is then its own problem).
|
|
144
|
-
*/
|
|
145
|
-
turns?: (signal?: AbortSignal) => AsyncIterable<{
|
|
146
|
-
kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
|
|
147
|
-
text?: string;
|
|
148
|
-
confidence?: number;
|
|
149
|
-
startMs?: number;
|
|
150
|
-
}>;
|
|
151
|
-
/**
|
|
152
|
-
* THE COMPOSITE LANE (ENG-451, openai-realtime/composite.ts): this binding
|
|
153
|
-
* composes THREE pinned sessions — the `stt` leg behind `turns` and the
|
|
154
|
-
* composed bridge's IN side, the bound chat row behind
|
|
155
|
-
* `clients.createResponse`, and the `tts` leg behind the bridge's OUT side
|
|
156
|
-
* and the per-sentence synthesis turns. The connection keys its
|
|
157
|
-
* live-transcription-in semantics on this marker: appends stream to the
|
|
158
|
-
* stt leg live, the client's commits own turn boundaries, a committed
|
|
159
|
-
* item's pending transcript gates the model turn (and is written into the
|
|
160
|
-
* item — it is the chat leg's input), and `turn_detection: null` is the
|
|
161
|
-
* only accepted mode. A dead leg's failure is a `SessionGoneError` NAMING
|
|
162
|
-
* the leg — the loud `session_gone` close carries the name.
|
|
163
|
-
*/
|
|
164
|
-
composite?: true;
|
|
165
|
-
/**
|
|
166
|
-
* THE COMPOSITE TURN'S PROMPT CANCEL (ENG-451): stop the ACTIVE turn's
|
|
167
|
-
* legs beyond the turn seam — the composite binding aborts its per-turn
|
|
168
|
-
* controller, which unwinds the tts leg's in-flight synthesis read and
|
|
169
|
-
* drops its queued sentence chunks NOW. The connection calls it from
|
|
170
|
-
* `response.cancel` and from teardown; the for-await `break` alone only
|
|
171
|
-
* unwinds at the turn stream's NEXT event, which is too late for legs
|
|
172
|
-
* that keep consuming GPU on their own. Absent (every one-session
|
|
173
|
-
* binding) = nothing to stop beyond the stream, exactly as before.
|
|
174
|
-
*/
|
|
175
|
-
cancelActiveTurn?: () => void;
|
|
176
|
-
/**
|
|
177
|
-
* Release THIS attachment when the socket closes (the hosted
|
|
178
|
-
* conversation-factory seam — the twin of the Gemini Live binding's
|
|
179
|
-
* `release`): per-attachment release, native detach underneath, the named
|
|
180
|
-
* session itself stays live. Absent (the local fixed-clients lane) = the
|
|
181
|
-
* pooled sessions are the process's own and outlive the socket.
|
|
182
|
-
*/
|
|
183
|
-
release?: () => Promise<void> | void;
|
|
184
|
-
}
|
|
185
|
-
interface OpenAIRealtimeOptions<S = unknown> {
|
|
186
|
-
resolver: OpenAIRealtimeResolver<S>;
|
|
187
|
-
/**
|
|
188
|
-
* Where the per-upgrade structured `realtime_upgrade` lines go (ONE
|
|
189
|
-
* newline-terminated JSON object per lifecycle event: accept → admit →
|
|
190
|
-
* close). Absent, the line goes to this process's stdout through the repo's
|
|
191
|
-
* canonical guarded write — the hosted container's collected log stream.
|
|
192
|
-
* Emitted unconditionally, never behind a verbosity flag: this lane's
|
|
193
|
-
* lifecycle was previously invisible in the process log, which is exactly
|
|
194
|
-
* why an orphaned queued admission could only be diagnosed from the
|
|
195
|
-
* session-server side.
|
|
196
|
-
*/
|
|
197
|
-
log?: (line: string) => void;
|
|
198
|
-
/**
|
|
199
|
-
* Where the caller-message boundary's WITHHOLD receipts go (ENG-538): every
|
|
200
|
-
* time a realtime event keeps raw error text off the wire, the raw text is
|
|
201
|
-
* owed here — one newline-terminated line per withheld failure, carrying the
|
|
202
|
-
* connection/session ids for correlation. Absent, the receipt goes to
|
|
203
|
-
* `console.error` of THIS process; the hosted proxy passes its canonical
|
|
204
|
-
* operator sink so nothing is ever dropped on the floor.
|
|
205
|
-
*/
|
|
206
|
-
operatorLog?: (line: string) => void;
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Attach the OpenAI Realtime WS endpoint to `server`. Upgrades on any other
|
|
210
|
-
* path pass through untouched. Returns an async close function.
|
|
211
|
-
*/
|
|
212
|
-
declare function attachOpenAIRealtime<S = unknown>(server: Server, options: OpenAIRealtimeOptions<S>): () => Promise<void>;
|
|
7
|
+
import '../video-out-A8qMuI36.cjs';
|
|
8
|
+
import '../types-DiYzfHYN.cjs';
|
|
213
9
|
|
|
214
10
|
/**
|
|
215
11
|
* The local OpenAI-compatible proxy — `npx @urun-sh/openai proxy`.
|
|
@@ -502,11 +298,14 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
502
298
|
* convention, never nothing.
|
|
503
299
|
*/
|
|
504
300
|
private readonly operatorLog;
|
|
301
|
+
/** The turn-stall bound in ms (see {@link REALTIME_TURN_STALL_MS}). */
|
|
302
|
+
private readonly turnStallMs;
|
|
505
303
|
private config;
|
|
506
304
|
private readonly sessionId;
|
|
507
305
|
private readonly conversationId;
|
|
508
306
|
private readonly items;
|
|
509
|
-
/** Uncommitted input audio (base64 PCM16 chunks) held locally until commit.
|
|
307
|
+
/** Uncommitted input audio (base64 PCM16 chunks) held locally until commit.
|
|
308
|
+
* Each chunk may carry the client's `capture_wall_ms` staleness stamp (optional; absent = unstamped). */
|
|
510
309
|
private pendingAudioBytes;
|
|
511
310
|
private pendingAudioTotalBytes;
|
|
512
311
|
/**
|
|
@@ -573,6 +372,14 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
573
372
|
constructor(opts: {
|
|
574
373
|
ws: WebSocket;
|
|
575
374
|
binding: RealtimeBinding<S>;
|
|
375
|
+
/**
|
|
376
|
+
* Frames the client sent while the binding was still resolving (the
|
|
377
|
+
* attach hook's waiting-status early upgrade buffers them) — replayed
|
|
378
|
+
* through the SAME onMessage path after this constructor's own greeting,
|
|
379
|
+
* so a session.update sent the moment the socket opened is never lost
|
|
380
|
+
* behind a queued admission.
|
|
381
|
+
*/
|
|
382
|
+
replayFrames?: string[];
|
|
576
383
|
/** Fired once at teardown, with the reason (the surface's structured close log rides it). */
|
|
577
384
|
onClosed?: (conn: OpenAIRealtimeConnection<S>, info: {
|
|
578
385
|
reason: string;
|
|
@@ -582,6 +389,13 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
582
389
|
* Absent, this process's stderr.
|
|
583
390
|
*/
|
|
584
391
|
operatorLog?: (line: string) => void;
|
|
392
|
+
/**
|
|
393
|
+
* The turn-stall bound in ms (see {@link REALTIME_TURN_STALL_MS}):
|
|
394
|
+
* silence after the turn's FIRST upstream event longer than this ends
|
|
395
|
+
* the turn visibly. `0` disables. Tests shrink it; prod rides the
|
|
396
|
+
* default.
|
|
397
|
+
*/
|
|
398
|
+
turnStallMs?: number;
|
|
585
399
|
});
|
|
586
400
|
/**
|
|
587
401
|
* Consume the backend's OWN turn/transcript lane (§5 stt stream): the
|
|
@@ -677,6 +491,15 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
677
491
|
* unawaited promise reach `for await` as "R is not async iterable" (the
|
|
678
492
|
* prod-usw2 speak-turn kill, 2026-09-14).
|
|
679
493
|
*/
|
|
494
|
+
/**
|
|
495
|
+
* THE STALL-BOUNDED TURN SOURCE: the first `next()` is unbounded (the
|
|
496
|
+
* dial's cold-boot / admission wait legitimately runs minutes); every
|
|
497
|
+
* SUBSEQUENT event must arrive within `turnStallMs` of the last one or
|
|
498
|
+
* the source is DEAD — the wrapper unwinds the upstream through its own
|
|
499
|
+
* `return()` and throws {@link TurnStalledError}, which the turn body
|
|
500
|
+
* ends VISIBLY. `0` disables.
|
|
501
|
+
*/
|
|
502
|
+
private stallBoundedTurn;
|
|
680
503
|
private upstreamStream;
|
|
681
504
|
private startResponse;
|
|
682
505
|
/**
|
|
@@ -904,7 +727,7 @@ declare function realtimeModelOf(req: IncomingMessage): string | undefined;
|
|
|
904
727
|
* and the bridge opens — a refused upgrade admits nothing. On an stt row
|
|
905
728
|
* the intent is recorded on the binding (a transcription session).
|
|
906
729
|
*/
|
|
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>>;
|
|
730
|
+
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
908
731
|
/**
|
|
909
732
|
* The LOCAL lane resolver: fixed pooled clients, optional fixed apiKey (the
|
|
910
733
|
* same shared-secret rule the local Gemini Live lane applies — a mismatched
|
|
@@ -920,7 +743,7 @@ declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle'
|
|
|
920
743
|
* invents a default pairing.
|
|
921
744
|
*/
|
|
922
745
|
declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
|
|
923
|
-
resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<ProxyClients>>;
|
|
746
|
+
resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
924
747
|
};
|
|
925
748
|
|
|
926
|
-
export { type GeminiLiveCall, type GeminiLiveClients,
|
|
749
|
+
export { type GeminiLiveCall, type GeminiLiveClients, type OpenAIProxyOptions, OpenAIRealtimeConnection, ProxyClients, RealtimeBinding, ResumptionRegistry, attachGeminiLive, createOpenAIProxy, fixedClientsResolver, realtimeBindingFor, realtimeModelOf, serveGeminiLiveSocket };
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -1,67 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { P as ProxyClients,
|
|
3
|
-
export { D as DialObserver, a as DialReport, g as
|
|
4
|
-
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-
|
|
1
|
+
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
+
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-DNNAm0PY.js';
|
|
3
|
+
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-DNNAm0PY.js';
|
|
4
|
+
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CaOqL-V8.js';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.js';
|
|
7
|
-
import '../video-out-
|
|
8
|
-
import '../types-
|
|
9
|
-
|
|
10
|
-
declare const OPENAI_REALTIME_PATH = "/v1/realtime";
|
|
11
|
-
|
|
12
|
-
type OpenAIRealtimeResolver<S = unknown> = ((req: IncomingMessage, signal?: AbortSignal) => Promise<RealtimeBinding<S>>) | {
|
|
13
|
-
resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<S>>;
|
|
14
|
-
};
|
|
15
|
-
interface RealtimeBinding<S = unknown> {
|
|
16
|
-
|
|
17
|
-
session?: S & {
|
|
18
|
-
sendResponseCreate?(params: unknown, input: unknown[], requestId: string): Promise<AsyncIterable<unknown>>;
|
|
19
|
-
};
|
|
20
|
-
clients?: Pick<ProxyClients, 'createResponse'>;
|
|
21
|
-
|
|
22
|
-
voice: boolean;
|
|
23
|
-
|
|
24
|
-
audioSession?: {
|
|
25
|
-
audio: {
|
|
26
|
-
appendInputAudio(base64Pcm16: string): void;
|
|
27
|
-
onOutputAudio(handler: (b64: string) => void): () => void;
|
|
28
|
-
|
|
29
|
-
sessionId?: string | null;
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
openaiRealtimeClaims?: Set<RealtimeBinding['audioSession']>;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
model?: string;
|
|
36
|
-
|
|
37
|
-
video?: () => Promise<ProxyVideoLane>;
|
|
38
|
-
|
|
39
|
-
intent?: 'transcription';
|
|
40
|
-
|
|
41
|
-
resumed?: boolean;
|
|
42
|
-
|
|
43
|
-
turns?: (signal?: AbortSignal) => AsyncIterable<{
|
|
44
|
-
kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
|
|
45
|
-
text?: string;
|
|
46
|
-
confidence?: number;
|
|
47
|
-
startMs?: number;
|
|
48
|
-
}>;
|
|
49
|
-
|
|
50
|
-
composite?: true;
|
|
51
|
-
|
|
52
|
-
cancelActiveTurn?: () => void;
|
|
53
|
-
|
|
54
|
-
release?: () => Promise<void> | void;
|
|
55
|
-
}
|
|
56
|
-
interface OpenAIRealtimeOptions<S = unknown> {
|
|
57
|
-
resolver: OpenAIRealtimeResolver<S>;
|
|
58
|
-
|
|
59
|
-
log?: (line: string) => void;
|
|
60
|
-
|
|
61
|
-
operatorLog?: (line: string) => void;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
declare function attachOpenAIRealtime<S = unknown>(server: Server, options: OpenAIRealtimeOptions<S>): () => Promise<void>;
|
|
7
|
+
import '../video-out-IoTqIbAw.js';
|
|
8
|
+
import '../types-DiYzfHYN.js';
|
|
65
9
|
|
|
66
10
|
interface OpenAIProxyOptions extends ProxyHandlerOptions {
|
|
67
11
|
clients: ProxyClients;
|
|
@@ -119,6 +63,8 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
119
63
|
private readonly onClosed?;
|
|
120
64
|
|
|
121
65
|
private readonly operatorLog;
|
|
66
|
+
|
|
67
|
+
private readonly turnStallMs;
|
|
122
68
|
private config;
|
|
123
69
|
private readonly sessionId;
|
|
124
70
|
private readonly conversationId;
|
|
@@ -159,11 +105,15 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
159
105
|
ws: WebSocket;
|
|
160
106
|
binding: RealtimeBinding<S>;
|
|
161
107
|
|
|
108
|
+
replayFrames?: string[];
|
|
109
|
+
|
|
162
110
|
onClosed?: (conn: OpenAIRealtimeConnection<S>, info: {
|
|
163
111
|
reason: string;
|
|
164
112
|
}) => void;
|
|
165
113
|
|
|
166
114
|
operatorLog?: (line: string) => void;
|
|
115
|
+
|
|
116
|
+
turnStallMs?: number;
|
|
167
117
|
});
|
|
168
118
|
|
|
169
119
|
private startTurnLane;
|
|
@@ -194,6 +144,8 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
194
144
|
private releaseVoiceBinding;
|
|
195
145
|
private warnAudioOnlyTranscriptGap;
|
|
196
146
|
|
|
147
|
+
|
|
148
|
+
private stallBoundedTurn;
|
|
197
149
|
private upstreamStream;
|
|
198
150
|
private startResponse;
|
|
199
151
|
|
|
@@ -240,10 +192,10 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
240
192
|
|
|
241
193
|
declare function realtimeModelOf(req: IncomingMessage): string | undefined;
|
|
242
194
|
|
|
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>>;
|
|
195
|
+
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
244
196
|
|
|
245
197
|
declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
|
|
246
|
-
resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<ProxyClients>>;
|
|
198
|
+
resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
247
199
|
};
|
|
248
200
|
|
|
249
|
-
export { type GeminiLiveCall, type GeminiLiveClients,
|
|
201
|
+
export { type GeminiLiveCall, type GeminiLiveClients, type OpenAIProxyOptions, OpenAIRealtimeConnection, ProxyClients, RealtimeBinding, ResumptionRegistry, attachGeminiLive, createOpenAIProxy, fixedClientsResolver, realtimeBindingFor, realtimeModelOf, serveGeminiLiveSocket };
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{F as I,a as n,b as p,c as m,l,
|
|
1
|
+
import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-VQSCBUKT.js";import{a as o,h as t}from"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-BA3NCMS5.js";import{i as r,j as i}from"../chunk-J3KCHTSA.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,6 +1,8 @@
|
|
|
1
1
|
/** The narrow subset of @urun-sh/core's Session the SDK depends on. */
|
|
2
2
|
interface UrunDocLike {
|
|
3
3
|
set(patch: Record<string, unknown>): void;
|
|
4
|
+
/** Remove the key at `path` (segments) — a real delete (core `SessionDocumentImpl.delete`). */
|
|
5
|
+
delete(path: readonly string[]): void;
|
|
4
6
|
get(path?: string, defaultValue?: unknown): unknown;
|
|
5
7
|
on(event: 'change', handler: (snapshot: Record<string, unknown>) => void): () => void;
|
|
6
8
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as UrunSessionLike } from './types-
|
|
1
|
+
import { b as UrunSessionLike } from './types-DiYzfHYN.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The ONE native audio sample rate of the session transport: the SFU Opus leg
|
|
@@ -28,6 +28,13 @@ interface AudioBackend {
|
|
|
28
28
|
* a silent no-op (a dead sink is exactly the placeholder this replaces).
|
|
29
29
|
*/
|
|
30
30
|
createSink(remoteTrack: unknown): AudioSink;
|
|
31
|
+
/** Release codec resources. opusscript _mallocs ~230 KB per instance from
|
|
32
|
+
* the SHARED WASM heap — buffers GC never reclaims — and a dropped backend
|
|
33
|
+
* without dispose leaks them per session (once the heap grows past a
|
|
34
|
+
* captured view, every opus call in the process throws 'offset is out of
|
|
35
|
+
* bounds'). Backend implementations without native resources keep no-op
|
|
36
|
+
* (optional member). */
|
|
37
|
+
dispose?(): void;
|
|
31
38
|
}
|
|
32
39
|
declare class AudioBridge {
|
|
33
40
|
private readonly backend;
|
|
@@ -52,8 +59,11 @@ declare class AudioBridge {
|
|
|
52
59
|
*/
|
|
53
60
|
setDataEmit(emit: ((payload: Buffer) => Promise<void>) | null): void;
|
|
54
61
|
startOutbound(): Promise<unknown>;
|
|
55
|
-
/** OpenAI: input_audio_buffer.append (base64 PCM16) → publish frames.
|
|
56
|
-
|
|
62
|
+
/** OpenAI: input_audio_buffer.append (base64 PCM16) → publish frames.
|
|
63
|
+
* `captureWallMs` is advisory staleness metadata; the native RTP leg has no
|
|
64
|
+
* per-item stamp wire, so it is accepted and dropped here (the §5 lane path
|
|
65
|
+
* in lane-audio.ts is the consumer that preserves it). */
|
|
66
|
+
appendInputAudio(base64Pcm16: string, captureWallMs?: number): void;
|
|
57
67
|
/**
|
|
58
68
|
* Wire the runtime's downstream audio track into the output-frame fan-out.
|
|
59
69
|
* `remoteTrack` is the REAL Opus `MediaStreamTrack` the SFU produces for this
|
|
@@ -67,6 +77,10 @@ declare class AudioBridge {
|
|
|
67
77
|
* caller must await the real track before calling this.
|
|
68
78
|
*/
|
|
69
79
|
startInbound(remoteTrack: unknown): Promise<void>;
|
|
80
|
+
/** Release the backend's codec resources (the opusscript WASM heap). The
|
|
81
|
+
* ONE teardown seam every bridge retirement must call — see
|
|
82
|
+
* :data:`AudioBackend.dispose`. Idempotent; post-dispose appends throw. */
|
|
83
|
+
dispose(): void;
|
|
70
84
|
/** Emits base64 PCM16 → caller wraps as OpenAI response.audio.delta. */
|
|
71
85
|
onOutputAudio(handler: (base64Pcm16: string) => void): () => void;
|
|
72
86
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as UrunSessionLike } from './types-
|
|
1
|
+
import { b as UrunSessionLike } from './types-DiYzfHYN.js';
|
|
2
2
|
|
|
3
3
|
declare const NATIVE_AUDIO_SAMPLE_RATE = 24000;
|
|
4
4
|
|
|
@@ -15,6 +15,8 @@ interface AudioBackend {
|
|
|
15
15
|
createSource(): AudioSource;
|
|
16
16
|
|
|
17
17
|
createSink(remoteTrack: unknown): AudioSink;
|
|
18
|
+
|
|
19
|
+
dispose?(): void;
|
|
18
20
|
}
|
|
19
21
|
declare class AudioBridge {
|
|
20
22
|
private readonly backend;
|
|
@@ -34,10 +36,12 @@ declare class AudioBridge {
|
|
|
34
36
|
setDataEmit(emit: ((payload: Buffer) => Promise<void>) | null): void;
|
|
35
37
|
startOutbound(): Promise<unknown>;
|
|
36
38
|
|
|
37
|
-
appendInputAudio(base64Pcm16: string): void;
|
|
39
|
+
appendInputAudio(base64Pcm16: string, captureWallMs?: number): void;
|
|
38
40
|
|
|
39
41
|
startInbound(remoteTrack: unknown): Promise<void>;
|
|
40
42
|
|
|
43
|
+
dispose(): void;
|
|
44
|
+
|
|
41
45
|
onOutputAudio(handler: (base64Pcm16: string) => void): () => void;
|
|
42
46
|
}
|
|
43
47
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.44",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.6.
|
|
73
|
+
"@urun-sh/core": "^0.6.43"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"@prometheus-io/client": "^0.16.1",
|
package/dist/chunk-G7CSAISC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as p}from"./chunk-YSFSRI3D.js";p();import{Queue as x}from"bullmq";import{randomUUID as R}from"crypto";var P=3e4,v=60,S=1e3,E=12e4;function y(r){let c;try{c=JSON.parse(r)}catch{return null}if(typeof c!="object"||c===null||!("proxy_url"in c))return null;let u=c;return typeof u.proxy_url!="string"||u.proxy_url===""?null:{proxy_url:u.proxy_url,occupant_id:typeof u.occupant_id=="string"?u.occupant_id:"",capacity:typeof u.capacity=="number"?u.capacity:0,heartbeat_ms:typeof u.heartbeat_ms=="number"?u.heartbeat_ms:0}}function q(r){let c=r.now??Date.now,u=new Map,m=new Map,g=new Map,_=new Map,f=new Set,L=e=>{let n=u.get(e);return n||(n=r.queueFor?.(e)??h(e),u.set(e,n)),n},h=e=>{let n=r.redis,o=new x(e,{prefix:"bull:dispatch",connection:n});return{add:(i,d,a)=>o.add(i,d,a),reassertWaiting:async i=>{let a=(await o.getJobs(["waiting"])).filter(t=>t.data?.session_kind==="lane").sort((t,s)=>t.timestamp-s.timestamp);if(a.length===0)return{found:0};for(let t of a)try{await t.updateData({...t.data,demand_reaffirmed_at_ms:i,...r.mintRuntimeToken?{runtime_token:r.mintRuntimeToken(String(t.data.session_id))}:{}})}catch{}for(let t of a.slice(1))try{await t.remove()}catch{}return{found:a.length}},close:()=>o.close()}},b=async e=>{let n=await r.redis.hgetall(`lanes:${e}`),o=[];for(let[a,t]of Object.entries(n)){let s=y(t);s&&s.proxy_url===r.docHostUrl&&o.push(a)}if(o.length===0)return[];let i=await r.redis.mget(...o.map(a=>`lane_hosts:${a}`)),d=[];return o.forEach((a,t)=>{let s=i[t];s&&d.push({laneId:a,host:s})}),d},k=async(e,n)=>{let o=m.get(e)??0,i=c();if(i-o<P)return;m.set(e,i);let d=L(e);if((await d.reassertWaiting(c()).catch(s=>{throw m.delete(e),s})).found>0){_.set(n??"",(_.get(n??"")??0)+1),r.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:n});return}let t=`lane-${R().replaceAll("-","")}`;await d.add("session",{session_id:t,logical_id:t,incarnation:i,session_kind:"lane",lane_id:t,session_server_url:r.docHostUrl,proxy_url:r.docHostUrl,session_idle_timeout_seconds:v,thread_key:"lane",demand_reaffirmed_at_ms:c(),...r.mintRuntimeToken?{runtime_token:r.mintRuntimeToken(t)}:{}},{jobId:`${t}#${i}`,attempts:3}),g.set(n??"",(g.get(n??"")??0)+1),r.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:n})};return{async pick({pool:e,model:n,holdMs:o=0}){f.add(e);let i=async()=>{try{await k(e,n)}catch(s){m.delete(e),r.onEvent?.({kind:"lane_demand_failed",pool:e,model:n,reason:s instanceof Error?s.message:String(s)})}},d=async()=>{try{return await b(e)}catch{return[]}},a=await d();if(a.length>0)return a;await i();let t=c()+o;for(;c()<t;){if(await new Promise(s=>setTimeout(s,S)),a=await d(),a.length>0)return a;await i()}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async n=>{let o=[];try{let i=await r.redis.hgetall(`lanes:${n}`),d=Object.keys(i),a=d.length===0?[]:await r.redis.mget(...d.map(s=>`lane_hosts:${s}`)),t=c();o=d.map((s,D)=>{let w=i[s],l=w===void 0?null:y(w);return{laneId:s,occupantId:l?.occupant_id??"",capacity:l?.capacity??0,heartbeatAgeMs:l===null?null:t-l.heartbeat_ms,advertisedHere:l?.proxy_url===r.docHostUrl,hosted:!!a[D]}})}catch{}return{pool:n,lanes:o,lastDemandAt:m.get(n)??null}}))},demandCounters(){return[...new Set([...g.keys(),..._.keys()])].sort().map(n=>({model:n,enqueued:g.get(n)??0,reaffirmed:_.get(n)??0}))},async close(){await Promise.all([...u.values()].map(e=>e.close().catch(()=>{}))),u.clear()}}}export{E as a,q as b};
|
package/dist/chunk-GX243AIV.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var w="llm-resp";async function*v(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*g(e,t){let o=`${w}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*v(t,e.stream(o).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}i();var k=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,v as d,g as e,k as f};
|