@urun-sh/openai 0.6.30 → 0.6.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/chunk-5473ZAQ4.js +17 -0
  2. package/dist/chunk-7OH7UJ2H.js +60 -0
  3. package/dist/chunk-CAR4AEQJ.js +1 -0
  4. package/dist/{chunk-76BZLCGT.js → chunk-GL7EWL3V.js} +1 -1
  5. package/dist/chunk-KTMDSM7F.js +2 -0
  6. package/dist/chunk-L6HTHDVV.js +1 -0
  7. package/dist/chunk-LM4E5YM2.js +19 -0
  8. package/dist/chunk-M3YMNU5P.js +6 -0
  9. package/dist/chunk-NN6TQQUG.js +1 -0
  10. package/dist/chunk-OOCRI7ZM.js +6 -0
  11. package/dist/chunk-PAYCMH5F.js +1 -0
  12. package/dist/{responses-turn-BGb_XPOa.d.ts → composite-DMawda97.d.ts} +125 -83
  13. package/dist/{responses-turn-DXrwiPJh.d.cts → composite-DtBebn0Y.d.cts} +545 -309
  14. package/dist/gemini-live.cjs +2 -2
  15. package/dist/gemini-live.d.cts +85 -105
  16. package/dist/gemini-live.d.ts +48 -48
  17. package/dist/gemini-live.js +1 -1
  18. package/dist/hosted/bin.cjs +56 -42
  19. package/dist/hosted/bin.js +4 -22
  20. package/dist/hosted/index.cjs +52 -38
  21. package/dist/hosted/index.d.cts +230 -7
  22. package/dist/hosted/index.d.ts +114 -3
  23. package/dist/hosted/index.js +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.cts +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/{models-DUdx_Y6X.d.cts → models-D7F0bLJ3.d.cts} +14 -0
  29. package/dist/{models-DUdx_Y6X.d.ts → models-D7F0bLJ3.d.ts} +6 -0
  30. package/dist/pi-extension/index.cjs +6 -6
  31. package/dist/pi-extension/index.js +1 -1
  32. package/dist/pi-extension/standalone.cjs +33 -33
  33. package/dist/pooler/bin.cjs +335 -0
  34. package/dist/pooler/bin.js +316 -0
  35. package/dist/proxy/cli.cjs +58 -53
  36. package/dist/proxy/cli.js +1 -1
  37. package/dist/proxy/conformance-probe.cjs +1 -0
  38. package/dist/proxy/conformance-probe.js +1 -0
  39. package/dist/proxy/index.cjs +31 -28
  40. package/dist/proxy/index.d.cts +315 -167
  41. package/dist/proxy/index.d.ts +85 -53
  42. package/dist/proxy/index.js +1 -1
  43. package/package.json +14 -4
  44. package/dist/chunk-55LV3IXW.js +0 -62
  45. package/dist/chunk-7V2JKPIG.js +0 -1
  46. package/dist/chunk-CUDFHFNX.js +0 -4
  47. package/dist/chunk-K23AZPI4.js +0 -1
  48. package/dist/chunk-OPMTYD3Z.js +0 -2
  49. package/dist/chunk-WUNJ3FMI.js +0 -8
@@ -1,11 +1,11 @@
1
1
  import { Server } from 'node:http';
2
+ import { c as LedgerOutcome, I as InferenceRecord, i as RouteTarget, S as SessionGoneError, k as billingIdentityOf, P as ProxyClients, M as ModelRouter, j as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-DtBebn0Y.cjs';
2
3
  import * as _prometheus_io_client from '@prometheus-io/client';
3
4
  import { Registry } from '@prometheus-io/client';
4
- import { c as LedgerOutcome, I as InferenceRecord, S as SessionGoneError, j as billingIdentityOf, P as ProxyClients, M as ModelRouter, i as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure } from '../responses-turn-DXrwiPJh.cjs';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
6
6
  import { U as UrunResponses } from '../ResponsesClient-_OZERUjH.cjs';
7
7
  import { b as UrunSessionLike } from '../types-CHPtJx6d.cjs';
8
- import '../models-DUdx_Y6X.cjs';
8
+ import { C as CatalogRow } from '../models-D7F0bLJ3.cjs';
9
9
  import '../video-out-BsuLqlID.cjs';
10
10
 
11
11
  /**
@@ -106,6 +106,25 @@ declare class InferenceMetrics {
106
106
  private readonly ledgerQueue;
107
107
  private readonly labelCardinality;
108
108
  private readonly labelOverflows;
109
+ private readonly lanesReady;
110
+ private readonly lanePickMs;
111
+ private readonly laneFirstEventMs;
112
+ private readonly lane503Fast;
113
+ /**
114
+ * ORG BINDING: tenant-bearing /doc tokens accepted WITHOUT a lane record to
115
+ * bind against (lane_tenant key absent, or its lookup threw). Fail-open by
116
+ * design (the strict derived-key ladder is the primary gate), but a climbing
117
+ * series means the runtime's lane_tenant writer regressed — alert on it
118
+ * (Main ruling), never let the fence silently degrade.
119
+ */
120
+ private readonly laneDocTenantMissing;
121
+ /**
122
+ * THE BUILD STAMP (lane 30, PLAN B.5): always 1, labels naming the image
123
+ * commit this process was built from (`URUN_BUILD_COMMIT`, baked by the
124
+ * image workflow — 'unknown' when unset). A pod still serving an old
125
+ * image after a roll is otherwise invisible on the metrics surface.
126
+ */
127
+ private readonly buildInfo;
109
128
  constructor(options?: {
110
129
  defaultMetrics?: boolean;
111
130
  });
@@ -119,6 +138,13 @@ declare class InferenceMetrics {
119
138
  * disagreement would be invisible.
120
139
  */
121
140
  observeLedger(outcome: LedgerOutcome): void;
141
+ /** THE LANE PLANE's observation surface (fed by proxy/lane-registry.ts). */
142
+ observeLaneReady(model: string, count: number): void;
143
+ observeLanePick(model: string, durationMs: number): void;
144
+ observeLaneFirstEvent(model: string, durationMs: number): void;
145
+ observeLane503Fast(model: string): void;
146
+ /** ORG BINDING: a tenant-bearing /doc token accepted with NO lane record. */
147
+ observeLaneDocTenantMissing(): void;
122
148
  /**
123
149
  * Count ONE completed `/v1` request. Takes the very record
124
150
  * `inferenceRequestLine` serializes, so the counters and the billing log can
@@ -174,9 +200,21 @@ declare class ProxyAuthError extends Error {
174
200
  readonly status: number;
175
201
  constructor(message: string, status?: number);
176
202
  }
177
- /** The control plane could not be reached/asked. Loud 502, never a pass. */
203
+ /**
204
+ * The control plane could not be reached/asked. Loud 502, never a pass.
205
+ *
206
+ * THE CALLER-MESSAGE BOUNDARY (ENG-538, final review round 5): `message` is
207
+ * the CALLER's line — short, honest, actionable, no internals. The operator's
208
+ * evidence (the gateway URL, the underlying failure text) rides `detail`,
209
+ * which the classified relay branches send to the operator sink — never to
210
+ * the caller. Before this split the constructor embedded the gateway URL and
211
+ * the raw underlying text into `message` itself, and every classified relay
212
+ * position passed them straight to the wire.
213
+ */
178
214
  declare class ControlPlaneUnavailableError extends Error {
179
- constructor(message: string);
215
+ /** Operator-only evidence: the gateway URL and/or the underlying failure text. */
216
+ readonly detail?: string;
217
+ constructor(message: string, detail?: string);
180
218
  }
181
219
  /** The verified caller: their key, and the org the control plane bound it to. */
182
220
  interface CallerIdentity {
@@ -258,6 +296,89 @@ interface DecisionPoolStats {
258
296
  lastMissAgeMs: number | null;
259
297
  }
260
298
 
299
+ /** One advertised registry row, read back as status (no secrets, no demand). */
300
+ interface LaneRegistryStatusRow {
301
+ laneId: string;
302
+ occupantId: string;
303
+ capacity: number;
304
+ /** ms since the runtime's last heartbeat; null when the row is malformed. */
305
+ heartbeatAgeMs: number | null;
306
+ /** Advertised with THIS region's docHostUrl (a peer region's row is listed but flagged). */
307
+ advertisedHere: boolean;
308
+ /** A `lane_hosts:` lease exists — the runtime doc-connected somewhere. */
309
+ hosted: boolean;
310
+ }
311
+
312
+ /**
313
+ * THE LANE REGISTRY — pick, reuse, and join lanes (plan A4.2/A5.2).
314
+ *
315
+ * OWNERSHIP (owner ruling 2026-10-12): the `lanes:*` / `lane_hosts:*`
316
+ * registry reads and the dispatch-queue demand live in the POOLER
317
+ * (`pooler/lane-demand.ts`) — ONE minter per region, never a Queue per
318
+ * proxy replica. This module is the proxy's remnant: the entry cache and
319
+ * the doc-session join. A dial asks the pooler's lane plane for the ready
320
+ * candidates (registry read + demand + cold-wake hold behind it), then
321
+ * picks SELF-hosted first (in-process bridge, honest in-flight counts),
322
+ * least-loaded; a lane hosted on a PEER replica is joined pod-to-pod as a
323
+ * y-websocket CLIENT over the library's own `createWebsocketDocConnector`
324
+ * — never a hand-rolled sync.
325
+ *
326
+ * Lanes are REUSED across requests (that is the point): one lane serves
327
+ * many concurrent turns; the entry cache is keyed by laneId and only a gone
328
+ * verdict (host room empty / remote doc plane failed) retires an entry.
329
+ */
330
+
331
+ interface LanePoolPick {
332
+ app: string;
333
+ entry: PoolEntry;
334
+ identity: {
335
+ kind: 'catalog';
336
+ model_id: string;
337
+ variant: string;
338
+ };
339
+ }
340
+ /** Read-only per-pool lane facts — the "why 503" surface (owner 2026-10-07). */
341
+ interface LaneStatusRow extends LaneRegistryStatusRow {
342
+ }
343
+ /** Read-only per-pool lane facts — the "why 503" surface (owner 2026-10-07). */
344
+ interface LanePoolStatus {
345
+ pool: string;
346
+ lanes: LaneStatusRow[];
347
+ /** This replica's open entries (picked lanes with live doc sessions). */
348
+ local: Array<{
349
+ laneId: string;
350
+ inFlight: number;
351
+ self: boolean;
352
+ host: string;
353
+ }>;
354
+ lastRefusalAt: number | null;
355
+ lastDemandAt: number | null;
356
+ }
357
+ interface LanePools {
358
+ /**
359
+ * The rehome seam's sessionFor for ONE resolved SHARED target: least-loaded
360
+ * ready lane (self-hosted first, in-process in-flight count), reuse-first.
361
+ * None ready (the pooler's demand + cold-wake hold expired) ⇒ demand
362
+ * already submitted pooler-side + `LaneCapacityError`.
363
+ */
364
+ sessionFor(model: string | undefined, target: RouteTarget): Promise<LanePoolPick>;
365
+ /** Stream-end release of one lane lease (no-op for foreign entries). */
366
+ release(entry: PoolEntry): void;
367
+ owns(entry: PoolEntry): boolean;
368
+ /** The live entry for a lane id (a handle's key), or null once evicted. */
369
+ entryFor(laneId: string): PoolEntry | null;
370
+ /** Read-only per-pool facts for the status endpoint; NEVER mints a demand. */
371
+ status(): Promise<LanePoolStatus[]>;
372
+ /** The lane's host vanished (conns == 0 / remote plane failed): retire it. */
373
+ evict(entry: PoolEntry): void;
374
+ close(): Promise<void>;
375
+ stats(): Array<{
376
+ pool: string;
377
+ laneId: string;
378
+ inFlight: number;
379
+ }>;
380
+ }
381
+
261
382
  /**
262
383
  * SESSION GONE for the proxy serve lane — level-triggered, keyed off the
263
384
  * transport's OWN close/rejection signals (live defect, prod-usw2 2026-08-12).
@@ -439,9 +560,11 @@ interface DecisionPools {
439
560
  boot(): Promise<void>;
440
561
  /** The rehome seam's sessionFor: least-loaded attached slot lease.
441
562
  *
442
- * THE NO-WAIT CONTRACT (owner ruling 2026-10-03): never awaits a slot
443
- * open — throws {@link DecisionCapacityError} when no attached slot is
444
- * ready, after submitting the out-of-band add. */
563
+ * THE SYNC WARM-WAIT CONTRACT (owner ruling 2026-10-08, superseding the
564
+ * 2026-10-03 no-wait ruling): the dial HOLDS up to the model's warm-wait
565
+ * bound (20s default) against an already-submitted slot open, then throws
566
+ * the typed retryable {@link DecisionPoolCapacityError} with the warming
567
+ * phase split. */
445
568
  sessionFor(model: string | undefined): Promise<{
446
569
  app: string;
447
570
  entry: PoolEntry;
@@ -457,6 +580,14 @@ interface DecisionPools {
457
580
  end(entry: PoolEntry): void;
458
581
  /** A pool entry's runtime detached: PAUSED + re-submit (re-adopt). */
459
582
  evict(entry: PoolEntry): void;
583
+ /**
584
+ * A pool entry's session died a TERMINAL death (410 `reaped_orphaned_request`
585
+ * class — the platform reaped the corpse; see isWedgingVerdict's 410
586
+ * branch): the slot's identity ROTATES (generation bump) so the next
587
+ * acquire mints exactly ONE FRESH logical session instead of re-adopting
588
+ * the corpse and 410-looping until restart (#631).
589
+ */
590
+ markSessionDead(entry: PoolEntry): void;
460
591
  /** Idle scale-down, above min. Owner-driven cadence (the 5s reap tick). */
461
592
  reap(): void;
462
593
  stats(): Array<{
@@ -473,6 +604,16 @@ interface DecisionPools {
473
604
  close(): Promise<void>;
474
605
  }
475
606
 
607
+ /** The pooler channel's auth fence: the in-cluster shared secret. */
608
+ interface PoolerClientConfig {
609
+ /** The pooler service's in-cluster base (`http://pooler.urun.svc:8080`). */
610
+ baseUrl: string;
611
+ /** The shared bearer the proxies present (`URUN_POOLER_TOKEN`). */
612
+ token: string;
613
+ /** The region this proxy serves (`region` in the submit body). */
614
+ region: string;
615
+ }
616
+
476
617
  /**
477
618
  * PER-CALLER BACKHAULS — the multi-tenant half of the hosted endpoint.
478
619
  *
@@ -544,6 +685,18 @@ interface TenantRegistryOptions {
544
685
  apiUrl: string;
545
686
  /** The model-catalog oracle for routing rule 5, or null. */
546
687
  catalog: CatalogConfig | null;
688
+ /**
689
+ * THE VALKEY CATALOG rows (owner ruling: the proxy never touches
690
+ * Supabase). Present ⇒ every tenant's router reads these and `catalog`
691
+ * MUST be null (the two are mutually exclusive on this surface).
692
+ */
693
+ catalogRows?: () => Promise<CatalogRow[]>;
694
+ /**
695
+ * THE REPLICA'S LANE POOLS (plan A5.2) — one per replica, shared across
696
+ * tenants (a lane belongs to the shared org's app, never to a caller).
697
+ * Present ⇒ every shared req/resp target acquires through the lane pick.
698
+ */
699
+ lanes?: LanePools;
547
700
  /** Injected in tests; production builds real uRun backhauls. A stub may
548
701
  * also carry its own `decision` pool (tests drive the readiness ping). */
549
702
  build?: (caller: CallerIdentity) => {
@@ -551,6 +704,14 @@ interface TenantRegistryOptions {
551
704
  clients: ProxyClients;
552
705
  decision?: DecisionPools;
553
706
  };
707
+ /**
708
+ * THE POOLER CUTOVER (design ref-shared-endpoint-pooler-design.md):
709
+ * present ⇒ every tenant's `createResponse` routes through the pooler's
710
+ * internal HTTP surface and the proxy holds no pool state — auth +
711
+ * translation only. Absent ⇒ the proxy keeps its own backhaul behavior,
712
+ * byte-identical to before.
713
+ */
714
+ pooler?: PoolerClientConfig;
554
715
  }
555
716
  /**
556
717
  * A stable, non-secret `subject` for one caller's client tokens. Derived from
@@ -648,6 +809,10 @@ interface ConversationBackhaulOptions {
648
809
  apiUrl: string;
649
810
  /** The model-catalog oracle for routing rule 5, or null. */
650
811
  catalog: CatalogConfig | null;
812
+ /** The Valkey catalog mirror (lane mode) — exclusive with `catalog`. */
813
+ catalogRows?: () => Promise<CatalogRow[]>;
814
+ /** The replica's lane pools: a SHARED model's realtime binding attaches to its lane. */
815
+ lanes?: LanePools;
651
816
  /** Injected in tests; production builds real uRun backhauls. */
652
817
  build?: (caller: CallerIdentity, conversation: {
653
818
  id: string;
@@ -1070,6 +1235,49 @@ interface HostedConfig {
1070
1235
  keyId: string;
1071
1236
  key: string;
1072
1237
  };
1238
+ /**
1239
+ * THE LANE PLANE (plan A5.2) — launcher-injected external inputs; ABSENT ⇒
1240
+ * lane mode is OFF and the proxy's behavior is byte-identical to before.
1241
+ * All four values are required together (half-configured is the
1242
+ * silent-degradation shape — refuse to start).
1243
+ *
1244
+ * URUN_LANE_DOC_HOST_URL the region's PUBLIC doc-host URL the runtime
1245
+ * dials and the registry's proxy_url carries
1246
+ * (e.g. wss://inference.urun.sh);
1247
+ * URUN_LANE_VALKEY_URL the regional Valkey (registry + demand);
1248
+ * URUN_SESSION_TOKEN_SECRET the shared control-plane secret the runtime's
1249
+ * per-dial doc token is minted with (the SAME
1250
+ * value session-server-ts's upgrade auth uses)
1251
+ * — doc upgrades 401 when absent;
1252
+ * URUN_LANE_SELF_ADDRESS this replica's pod-to-pod address
1253
+ * ("<pod ip>:<port>", downward-API injected) —
1254
+ * the lane_hosts self check.
1255
+ */
1256
+ lane?: {
1257
+ docHostUrl: string;
1258
+ valkeyUrl: string;
1259
+ tokenSecret: string;
1260
+ selfAddress: string;
1261
+ };
1262
+ /**
1263
+ * THE POOLER CUTOVER (shared-endpoint pooler design, owner-DECIDED
1264
+ * 2026-10-10): launcher-injected external inputs; ABSENT ⇒ the proxy keeps
1265
+ * its own backhaul/pool behavior, byte-identical to before. PRESENT ⇒ the
1266
+ * proxy's `createResponse` seam routes through the pooler's internal HTTP
1267
+ * surface and the proxy holds NO pool state (auth + translation only).
1268
+ * All three values are required together (half-configured is the
1269
+ * silent-degradation shape — refuse to start).
1270
+ *
1271
+ * URUN_POOLER_URL the pooler service's in-cluster base
1272
+ * (e.g. http://pooler.urun.svc:8080);
1273
+ * URUN_POOLER_TOKEN the in-cluster shared secret the proxies present;
1274
+ * URUN_POOLER_REGION the region this proxy serves (`region` in submits).
1275
+ */
1276
+ pooler?: {
1277
+ baseUrl: string;
1278
+ token: string;
1279
+ region: string;
1280
+ };
1073
1281
  }
1074
1282
  /**
1075
1283
  * Read and VALIDATE the deployment's external inputs. Every failure is loud
@@ -1099,6 +1307,11 @@ declare function resolveHostedConfig(env?: NodeJS.ProcessEnv): HostedConfig;
1099
1307
  * reachable, because a replica that cannot verify API keys
1100
1308
  * or list apps can serve nothing and must be pulled out of
1101
1309
  * the Service rather than answering 502s.
1310
+ * GET /lanez the per-pool lane status line (owner hardening
1311
+ * 2026-10-07): which occupant/lane is advertised, whether
1312
+ * its doc host lease is live, this replica's in-flight
1313
+ * counts, the last no-ready refusal. READ-ONLY — it never
1314
+ * mints a demand or wakes compute.
1102
1315
  * * /v1/... the compat surface, org-scoped by the Bearer key, including
1103
1316
  * the canonical usage-query lane POST /v1/usage/requests
1104
1317
  * (proxy/usage.ts — a batch read of the per-request
@@ -1180,6 +1393,16 @@ interface HostedProxyOptions extends HostedConfig {
1180
1393
  * assertion on the exposition text is not swamped by process noise.
1181
1394
  */
1182
1395
  defaultMetrics?: boolean;
1396
+ /**
1397
+ * THE COMPOSITE REALTIME LANE'S PAIRING SOURCE (ENG-451,
1398
+ * openai-realtime/composite.ts): for each chat-row `?model=`, the pinned
1399
+ * `{stt, tts, voice?}` trio that makes it realtime-capable on
1400
+ * `WS /v1/realtime`. Absent ⇒ the seam answers `null` ⇒ chat models keep
1401
+ * today's loud 404 (behaviour on main, unchanged). The PRODUCTION source
1402
+ * of the pairing (catalog field vs proxy config) is an open owner
1403
+ * decision — this option is the seam the eventual source wires into.
1404
+ */
1405
+ realtimeCompanions?: RealtimeCompanionsFor;
1183
1406
  }
1184
1407
  /**
1185
1408
  * Build (not listen) the hosted endpoint. The caller owns listen/close,
@@ -1,11 +1,11 @@
1
1
  import { Server } from 'node:http';
2
+ import { c as LedgerOutcome, I as InferenceRecord, i as RouteTarget, S as SessionGoneError, k as billingIdentityOf, P as ProxyClients, M as ModelRouter, j as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-DMawda97.js';
2
3
  import * as _prometheus_io_client from '@prometheus-io/client';
3
4
  import { Registry } from '@prometheus-io/client';
4
- import { c as LedgerOutcome, I as InferenceRecord, S as SessionGoneError, j as billingIdentityOf, P as ProxyClients, M as ModelRouter, i as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure } from '../responses-turn-BGb_XPOa.js';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
6
6
  import { U as UrunResponses } from '../ResponsesClient-CSSrOYD8.js';
7
7
  import { b as UrunSessionLike } from '../types-CHPtJx6d.js';
8
- import '../models-DUdx_Y6X.js';
8
+ import { C as CatalogRow } from '../models-D7F0bLJ3.js';
9
9
  import '../video-out-Cawtm7SF.js';
10
10
 
11
11
  declare const METRICS_PORT = 9464;
@@ -50,12 +50,27 @@ declare class InferenceMetrics {
50
50
  private readonly ledgerQueue;
51
51
  private readonly labelCardinality;
52
52
  private readonly labelOverflows;
53
+ private readonly lanesReady;
54
+ private readonly lanePickMs;
55
+ private readonly laneFirstEventMs;
56
+ private readonly lane503Fast;
57
+
58
+ private readonly laneDocTenantMissing;
59
+
60
+ private readonly buildInfo;
53
61
  constructor(options?: {
54
62
  defaultMetrics?: boolean;
55
63
  });
56
64
 
57
65
  observeLedger(outcome: LedgerOutcome): void;
58
66
 
67
+ observeLaneReady(model: string, count: number): void;
68
+ observeLanePick(model: string, durationMs: number): void;
69
+ observeLaneFirstEvent(model: string, durationMs: number): void;
70
+ observeLane503Fast(model: string): void;
71
+
72
+ observeLaneDocTenantMissing(): void;
73
+
59
74
  observe(record: InferenceRecord): void;
60
75
 
61
76
  scrape(): Promise<string>;
@@ -71,7 +86,9 @@ declare class ProxyAuthError extends Error {
71
86
  }
72
87
 
73
88
  declare class ControlPlaneUnavailableError extends Error {
74
- constructor(message: string);
89
+
90
+ readonly detail?: string;
91
+ constructor(message: string, detail?: string);
75
92
  }
76
93
 
77
94
  interface CallerIdentity {
@@ -123,6 +140,64 @@ interface DecisionPoolStats {
123
140
  lastMissAgeMs: number | null;
124
141
  }
125
142
 
143
+ interface LaneRegistryStatusRow {
144
+ laneId: string;
145
+ occupantId: string;
146
+ capacity: number;
147
+
148
+ heartbeatAgeMs: number | null;
149
+
150
+ advertisedHere: boolean;
151
+
152
+ hosted: boolean;
153
+ }
154
+
155
+ interface LanePoolPick {
156
+ app: string;
157
+ entry: PoolEntry;
158
+ identity: {
159
+ kind: 'catalog';
160
+ model_id: string;
161
+ variant: string;
162
+ };
163
+ }
164
+
165
+ interface LaneStatusRow extends LaneRegistryStatusRow {
166
+ }
167
+
168
+ interface LanePoolStatus {
169
+ pool: string;
170
+ lanes: LaneStatusRow[];
171
+
172
+ local: Array<{
173
+ laneId: string;
174
+ inFlight: number;
175
+ self: boolean;
176
+ host: string;
177
+ }>;
178
+ lastRefusalAt: number | null;
179
+ lastDemandAt: number | null;
180
+ }
181
+ interface LanePools {
182
+
183
+ sessionFor(model: string | undefined, target: RouteTarget): Promise<LanePoolPick>;
184
+
185
+ release(entry: PoolEntry): void;
186
+ owns(entry: PoolEntry): boolean;
187
+
188
+ entryFor(laneId: string): PoolEntry | null;
189
+
190
+ status(): Promise<LanePoolStatus[]>;
191
+
192
+ evict(entry: PoolEntry): void;
193
+ close(): Promise<void>;
194
+ stats(): Array<{
195
+ pool: string;
196
+ laneId: string;
197
+ inFlight: number;
198
+ }>;
199
+ }
200
+
126
201
  interface SessionGoneWatch {
127
202
 
128
203
  gone(): SessionGoneError | null;
@@ -188,6 +263,8 @@ interface DecisionPools {
188
263
 
189
264
  evict(entry: PoolEntry): void;
190
265
 
266
+ markSessionDead(entry: PoolEntry): void;
267
+
191
268
  reap(): void;
192
269
  stats(): Array<{
193
270
  poolKey: string;
@@ -197,6 +274,15 @@ interface DecisionPools {
197
274
  close(): Promise<void>;
198
275
  }
199
276
 
277
+ interface PoolerClientConfig {
278
+
279
+ baseUrl: string;
280
+
281
+ token: string;
282
+
283
+ region: string;
284
+ }
285
+
200
286
  declare const MAX_TENANTS = 512;
201
287
  interface TenantRegistryOptions {
202
288
 
@@ -206,11 +292,17 @@ interface TenantRegistryOptions {
206
292
 
207
293
  catalog: CatalogConfig | null;
208
294
 
295
+ catalogRows?: () => Promise<CatalogRow[]>;
296
+
297
+ lanes?: LanePools;
298
+
209
299
  build?: (caller: CallerIdentity) => {
210
300
  router: ModelRouter<PoolEntry>;
211
301
  clients: ProxyClients;
212
302
  decision?: DecisionPools;
213
303
  };
304
+
305
+ pooler?: PoolerClientConfig;
214
306
  }
215
307
 
216
308
  declare function tenantSubject(apiKey: string): string;
@@ -258,6 +350,10 @@ interface ConversationBackhaulOptions {
258
350
 
259
351
  catalog: CatalogConfig | null;
260
352
 
353
+ catalogRows?: () => Promise<CatalogRow[]>;
354
+
355
+ lanes?: LanePools;
356
+
261
357
  build?: (caller: CallerIdentity, conversation: {
262
358
  id: string;
263
359
  subject: string;
@@ -367,6 +463,19 @@ interface HostedConfig {
367
463
  keyId: string;
368
464
  key: string;
369
465
  };
466
+
467
+ lane?: {
468
+ docHostUrl: string;
469
+ valkeyUrl: string;
470
+ tokenSecret: string;
471
+ selfAddress: string;
472
+ };
473
+
474
+ pooler?: {
475
+ baseUrl: string;
476
+ token: string;
477
+ region: string;
478
+ };
370
479
  }
371
480
 
372
481
  declare function resolveHostedConfig(env?: NodeJS.ProcessEnv): HostedConfig;
@@ -396,6 +505,8 @@ interface HostedProxyOptions extends HostedConfig {
396
505
  requestLog?: (line: string) => void;
397
506
 
398
507
  defaultMetrics?: boolean;
508
+
509
+ realtimeCompanions?: RealtimeCompanionsFor;
399
510
  }
400
511
 
401
512
  declare function createHostedProxy(options: HostedProxyOptions): {
@@ -1 +1 @@
1
- import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-WUNJ3FMI.js";import"../chunk-OPMTYD3Z.js";import"../chunk-K23AZPI4.js";import"../chunk-55LV3IXW.js";import"../chunk-76BZLCGT.js";import"../chunk-CUDFHFNX.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-7V2JKPIG.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
1
+ import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-5473ZAQ4.js";import"../chunk-KTMDSM7F.js";import"../chunk-CAR4AEQJ.js";import"../chunk-7OH7UJ2H.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-PAYCMH5F.js";import"../chunk-L6HTHDVV.js";import"../chunk-M3YMNU5P.js";import"../chunk-GL7EWL3V.js";import"../chunk-NN6TQQUG.js";import"../chunk-OOCRI7ZM.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Q=Object.create;var h=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},L=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Z(t))!te.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=X(t,o))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?Q(ee(e)):{},L(t||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e)),re=e=>L(h({},"__esModule",{value:!0}),e);var fe={};ne(fe,{RT_VIDEO_OUT_STREAM:()=>y,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>T,SUPPORTED_RESPONSES_EVENTS:()=>x,UrunRealtime:()=>_,UrunResponses:()=>v,VIDEO_OUT_DEFAULT_CODEC:()=>E,VIDEO_OUT_FRAMING:()=>A,VIDEO_OUT_WS_FRAMING:()=>q,consumeVideoOut:()=>j,decodeVideoOutRecord:()=>b,encodeVideoOutRecord:()=>W,isSupportedClientEvent:()=>G,isSupportedResponsesEvent:()=>Y,listModels:()=>$,negotiateSessionVideoOutQuic:()=>H,nodeAudioBackend:()=>M,openSessionVideoOutLane:()=>F,toErrorEvent:()=>m,weriftAudioBackend:()=>D});module.exports=re(fe);function I(e,t,n,r){let o=e.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};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 V(e,t,n){let r={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(r.model=e.model),e.tools!==void 0&&(r.tools=e.tools),e.tool_choice!==void 0&&(r.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(r.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(r.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(r.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(r.stop=e.stop),typeof e.reasoning_effort=="string"&&(r.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(r.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(r.response_format=e.response_format),typeof e.voice=="string"&&(r.voice=e.voice),typeof e.language=="string"&&(r.language=e.language),r}function m(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,n=t.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:t.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var oe="llm-resp";async function*O(e,t){let n=`${oe}:${t}`,r=`resp_${t}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let i of e.stream(n).messages()){let a=i;if(a.t==="delta"){if(typeof a.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:a.delta}),typeof a.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:a.reasoning}),Array.isArray(a.tool_calls))for(let c of a.tool_calls){let s=typeof c.index=="number"?c.index:0,d=o.get(s)??{};c.id&&(d.id=c.id),c.function?.name&&(d.name=c.function.name),o.set(s,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${s}`,tool_index:s,call_id:d.id,name:d.name,delta:c.function?.arguments??""}}}else if(a.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...a.body}};return}else if(a.t==="error"){yield m(a);return}}}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var g=class e{constructor(t,n=e.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let t=this.session.doc("llm");if(t.synced===!0||typeof t.onSynced!="function")return;let n;await new Promise((o,i)=>{let a=t.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{a(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let r=V(t,n,this.consumerId);return this.write(r),O(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=I(t,n,r,this.consumerId);return this.write(o),O(this.session,r)})}async writeGated(t,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var U="audio",R=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let i=0;i<r;i++)o[i]=n.readInt16LE(i*2);this.source.onData(o)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function P(e,t,n=1e4){let r=new R(t,{sampleRate:24e3}),o=await r.startOutbound();await e.stream(U).attach(o);let i=await se(e,n);return await r.startInbound(i),r}function se(e,t){let n=e.stream(U);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let i,a=setTimeout(()=>{i?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),c=s=>{s!=null&&(clearTimeout(a),i?.(),r(s))};i=n.on?.("track",c),n.track!=null&&c(n.track)})}var ie=24e3,w=480,ae=111;async function de(){let e=await import("opusscript"),t=e.default??e;return new t(ie,1,2048)}async function D(){let e=await import("werift"),t=await de();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:c=>{let s=new Int16Array(a.length+c.length);s.set(a,0),s.set(c,a.length);let d=0;for(;s.length-d>=w;){let u=s.subarray(d,d+w);d+=w;let l=Buffer.from(u.buffer,u.byteOffset,u.byteLength),J=t.encode(l,w);o=o+1&65535,i=i+w>>>0;let K=new e.RtpHeader({version:2,payloadType:ae,sequenceNumber:o,timestamp:i,ssrc:r,marker:!1}),z=new e.RtpPacket(K,J);n.writeRtp(z)}a=s.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(i=>{let a;try{a=t.decode(i.payload)}catch{return}let c=new Int16Array(a.length/2);for(let s=0;s<c.length;s++)c[s]=a.readInt16LE(s*2);r.onframe?.({samples:c})}),r}}}async function M(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:r=>t.onData({samples:r,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},r=new e.nonstandard.RTCAudioSink(t);return r.ondata=o=>{n.onframe?.(o)},n}}}var C=0;function ce(){return C+=1,`rt_${Date.now().toString(36)}_${C.toString(36)}`}var _=class{constructor(t,n={}){this.session=t;this.opts=n;this.transport=new g(t)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await P(this.session,this.opts.audioBackend),this.audio.onOutputAudio(t=>this.emit({type:"response.audio.delta",delta:t}))}on(t,n){return this.handlers.add(n),()=>this.handlers.delete(n)}emit(t){for(let n of this.handlers)n(t)}send(t){switch(t.type){case"conversation.item.create":{let n=(t.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:t.item?.role??"user",content:n});return}case"response.create":{let n=ce();this.currentRequestId=n,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:t.response},this.conversation,n);for await(let o of r)this.emit(o)}catch(r){this.emit(m(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(t.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};var B=0;function ue(){return B+=1,`req_${Date.now().toString(36)}_${B.toString(36)}`}var v=class{transport;constructor(t){this.transport=new g(t)}responses={create:async t=>{let n=ue(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function pe(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}async function $(e){return{object:"list",data:(await pe(e)).map(n=>({id:`${n.model_id}:${n.variant}`,object:"model",created:0,owned_by:"urun"}))}}var f=require("@urun-sh/core"),y="rt-video-out",A="urun.videoOut.v1",E="h264";function N(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function W(e,t){if(N(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+t.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(t,2+n.byteLength),r}function b(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;N(o,"decodeVideoOutRecord");let i=e.subarray(2+t);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:i.slice()}}async function H(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),r=n.sessionId??e.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:y,codec:E,framing:A}}var q="urun.videoOut.v2-ws";function F(e){let t=e.stream(y);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${y}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,i=s=>{for(let d of r)d(s)},a=!1,c=async()=>{for await(let s of t.messages()){if(!(s instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${y}" delivered a non-BINARY \xA75 payload (${typeof s}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=b(s)}catch(u){i(u instanceof Error?u:new Error(String(u)));continue}for(let u of n)u(d)}for(let s of o)s()};return{codec:E,onOutputFrame:s=>(n.add(s),a||(a=!0,c().catch(d=>i(d instanceof Error?d:new Error(String(d))))),()=>n.delete(s)),onLaneError:s=>(r.add(s),()=>r.delete(s)),onEnd:s=>(o.add(s),()=>o.delete(s))}}function le(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function j(e,t,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,u)=>new globalThis.WebTransport(d,u):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let o=r(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:le(d)}))});await o.ready;let i=await o.createBidirectionalStream();await i.writable.getWriter().write((0,f.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=i.readable.getReader(),c=new f.WtControlDecoder,s=!1;for(;!s;){let{value:d,done:u}=await a.read();if(u)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of c.push(d)){if(l.t==="hello-ack"){s=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await(0,f.consumeWtDataStreams)(o.incomingUnidirectionalStreams,{onData:(d,u)=>{if(d===e.stream){if(u===f.STREAM_END){t.onEnd?.();return}if(!(u instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(b(u))}catch(l){t.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>t.onLaneError(d)})}var T=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],x=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function G(e){return T.includes(e)}function Y(e){return x.includes(e)}0&&(module.exports={RT_VIDEO_OUT_STREAM,SUPPORTED_REALTIME_CLIENT_EVENTS,SUPPORTED_RESPONSES_EVENTS,UrunRealtime,UrunResponses,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeVideoOutRecord,encodeVideoOutRecord,isSupportedClientEvent,isSupportedResponsesEvent,listModels,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,toErrorEvent,weriftAudioBackend});
1
+ "use strict";var Q=Object.create;var h=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},L=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Z(t))!te.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=X(t,o))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?Q(ee(e)):{},L(t||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e)),re=e=>L(h({},"__esModule",{value:!0}),e);var me={};ne(me,{RT_VIDEO_OUT_STREAM:()=>y,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>T,SUPPORTED_RESPONSES_EVENTS:()=>x,UrunRealtime:()=>k,UrunResponses:()=>v,VIDEO_OUT_DEFAULT_CODEC:()=>b,VIDEO_OUT_FRAMING:()=>R,VIDEO_OUT_WS_FRAMING:()=>q,consumeVideoOut:()=>j,decodeVideoOutRecord:()=>E,encodeVideoOutRecord:()=>W,isSupportedClientEvent:()=>G,isSupportedResponsesEvent:()=>Y,listModels:()=>$,negotiateSessionVideoOutQuic:()=>H,nodeAudioBackend:()=>M,openSessionVideoOutLane:()=>F,toErrorEvent:()=>m,weriftAudioBackend:()=>D});module.exports=re(me);function I(e,t,n,r){let o=e.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function V(e,t,n){let r={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(r.model=e.model),e.tools!==void 0&&(r.tools=e.tools),e.tool_choice!==void 0&&(r.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(r.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(r.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(r.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(r.stop=e.stop),typeof e.reasoning_effort=="string"&&(r.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(r.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(r.response_format=e.response_format),typeof e.voice=="string"&&(r.voice=e.voice),typeof e.language=="string"&&(r.language=e.language),r}function m(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,n=t.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:t.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var oe="llm-resp";async function*se(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let c=typeof a.index=="number"?a.index:0,i=r.get(c)??{};a.id&&(i.id=a.id),a.function?.name&&(i.name=a.function.name),r.set(c,i),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:i.id,name:i.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield m(s);return}}}async function*O(e,t){let n=`${oe}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*se(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var g=class e{constructor(t,n=e.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let t=this.session.doc("llm");if(t.synced===!0||typeof t.onSynced!="function")return;let n;await new Promise((o,s)=>{let a=t.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{a(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(t){t.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let r=V(t,n,this.consumerId);return this.write(r),O(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=I(t,n,r,this.consumerId);return this.write(o),O(this.session,r)})}async writeGated(t,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var U="audio",A=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function P(e,t,n=1e4){let r=new A(t,{sampleRate:24e3}),o=await r.startOutbound();await e.stream(U).attach(o);let s=await ie(e,n);return await r.startInbound(s),r}function ie(e,t){let n=e.stream(U);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,a=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),c=i=>{i!=null&&(clearTimeout(a),s?.(),r(i))};s=n.on?.("track",c),n.track!=null&&c(n.track)})}var ae=24e3,w=480,de=111;async function ce(){let e=await import("opusscript"),t=e.default??e;return new t(ae,1,2048)}async function D(){let e=await import("werift"),t=await ce();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:c=>{let i=new Int16Array(a.length+c.length);i.set(a,0),i.set(c,a.length);let d=0;for(;i.length-d>=w;){let u=i.subarray(d,d+w);d+=w;let l=Buffer.from(u.buffer,u.byteOffset,u.byteLength),J=t.encode(l,w);o=o+1&65535,s=s+w>>>0;let K=new e.RtpHeader({version:2,payloadType:de,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),z=new e.RtpPacket(K,J);n.writeRtp(z)}a=i.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let a;try{a=t.decode(s.payload)}catch{return}let c=new Int16Array(a.length/2);for(let i=0;i<c.length;i++)c[i]=a.readInt16LE(i*2);r.onframe?.({samples:c})}),r}}}async function M(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:r=>t.onData({samples:r,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},r=new e.nonstandard.RTCAudioSink(t);return r.ondata=o=>{n.onframe?.(o)},n}}}var C=0;function ue(){return C+=1,`rt_${Date.now().toString(36)}_${C.toString(36)}`}var k=class{constructor(t,n={}){this.session=t;this.opts=n;this.transport=new g(t)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await P(this.session,this.opts.audioBackend),this.audio.onOutputAudio(t=>this.emit({type:"response.audio.delta",delta:t}))}on(t,n){return this.handlers.add(n),()=>this.handlers.delete(n)}emit(t){for(let n of this.handlers)n(t)}send(t){switch(t.type){case"conversation.item.create":{let n=(t.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:t.item?.role??"user",content:n});return}case"response.create":{let n=ue();this.currentRequestId=n,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:t.response},this.conversation,n);for await(let o of r)this.emit(o)}catch(r){this.emit(m(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(t.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};var B=0;function pe(){return B+=1,`req_${Date.now().toString(36)}_${B.toString(36)}`}var v=class{transport;constructor(t){this.transport=new g(t)}responses={create:async t=>{let n=pe(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function le(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}async function $(e){return{object:"list",data:(await le(e)).map(n=>({id:`${n.model_id}:${n.variant}`,object:"model",created:0,owned_by:"urun"}))}}var f=require("@urun-sh/core"),y="rt-video-out",R="urun.videoOut.v1",b="h264";function N(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function W(e,t){if(N(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+t.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(t,2+n.byteLength),r}function E(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;N(o,"decodeVideoOutRecord");let s=e.subarray(2+t);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}async function H(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),r=n.sessionId??e.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:y,codec:b,framing:R}}var q="urun.videoOut.v2-ws";function F(e){let t=e.stream(y);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${y}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=i=>{for(let d of r)d(i)},a=!1,c=async()=>{for await(let i of t.messages()){if(!(i instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${y}" delivered a non-BINARY \xA75 payload (${typeof i}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=E(i)}catch(u){s(u instanceof Error?u:new Error(String(u)));continue}for(let u of n)u(d)}for(let i of o)i()};return{codec:b,onOutputFrame:i=>(n.add(i),a||(a=!0,c().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(i)),onLaneError:i=>(r.add(i),()=>r.delete(i)),onEnd:i=>(o.add(i),()=>o.delete(i))}}function fe(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function j(e,t,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,u)=>new globalThis.WebTransport(d,u):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let o=r(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:fe(d)}))});await o.ready;let s=await o.createBidirectionalStream();await s.writable.getWriter().write((0,f.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=s.readable.getReader(),c=new f.WtControlDecoder,i=!1;for(;!i;){let{value:d,done:u}=await a.read();if(u)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of c.push(d)){if(l.t==="hello-ack"){i=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await(0,f.consumeWtDataStreams)(o.incomingUnidirectionalStreams,{onData:(d,u)=>{if(d===e.stream){if(u===f.STREAM_END){t.onEnd?.();return}if(!(u instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(E(u))}catch(l){t.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>t.onLaneError(d)})}var T=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],x=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function G(e){return T.includes(e)}function Y(e){return x.includes(e)}0&&(module.exports={RT_VIDEO_OUT_STREAM,SUPPORTED_REALTIME_CLIENT_EVENTS,SUPPORTED_RESPONSES_EVENTS,UrunRealtime,UrunResponses,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeVideoOutRecord,encodeVideoOutRecord,isSupportedClientEvent,isSupportedResponsesEvent,listModels,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,toErrorEvent,weriftAudioBackend});
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.cjs';
2
2
  import { A as AudioBackend } from './video-out-BsuLqlID.cjs';
3
3
  export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-BsuLqlID.cjs';
4
4
  export { U as UrunResponses } from './ResponsesClient-_OZERUjH.cjs';
5
- export { M as ModelList, a as ModelObject, l as listModels } from './models-DUdx_Y6X.cjs';
5
+ export { M as ModelList, a as ModelObject, l as listModels } from './models-D7F0bLJ3.cjs';
6
6
  export { RealtimeClientEvent, RealtimeServerEvent } from 'openai/resources/beta/realtime/realtime';
7
7
  export { ResponseStreamEvent } from 'openai/resources/responses/responses';
8
8
 
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.js';
2
2
  import { A as AudioBackend } from './video-out-Cawtm7SF.js';
3
3
  export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-Cawtm7SF.js';
4
4
  export { U as UrunResponses } from './ResponsesClient-CSSrOYD8.js';
5
- export { M as ModelList, a as ModelObject, l as listModels } from './models-DUdx_Y6X.js';
5
+ export { M as ModelList, a as ModelObject, l as listModels } from './models-D7F0bLJ3.js';
6
6
  export { RealtimeClientEvent, RealtimeServerEvent } from 'openai/resources/beta/realtime/realtime';
7
7
  export { ResponseStreamEvent } from 'openai/resources/responses/responses';
8
8
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{b as S}from"./chunk-K23AZPI4.js";import{a as _}from"./chunk-76BZLCGT.js";import{c as d,g as v,h as f,i as R,j as y,k as O,l as h,m as x,n as g,o as k,p as A,q as T}from"./chunk-6M5JK4YC.js";import{c as i,e as a}from"./chunk-7V2JKPIG.js";import{c as o}from"./chunk-YSFSRI3D.js";o();o();var p=0;function V(){return p+=1,`rt_${Date.now().toString(36)}_${p.toString(36)}`}var s=class{constructor(e,t={}){this.session=e;this.opts=t;this.transport=new a(e)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await d(this.session,this.opts.audioBackend),this.audio.onOutputAudio(e=>this.emit({type:"response.audio.delta",delta:e}))}on(e,t){return this.handlers.add(t),()=>this.handlers.delete(t)}emit(e){for(let t of this.handlers)t(e)}send(e){switch(e.type){case"conversation.item.create":{let t=(e.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:e.item?.role??"user",content:t});return}case"response.create":{let t=V();this.currentRequestId=t,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:e.response},this.conversation,t);for await(let E of r)this.emit(E)}catch(r){this.emit(i(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(e.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};o();var l=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],m=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function w(n){return l.includes(n)}function I(n){return m.includes(n)}export{R as RT_VIDEO_OUT_STREAM,l as SUPPORTED_REALTIME_CLIENT_EVENTS,m as SUPPORTED_RESPONSES_EVENTS,s as UrunRealtime,_ as UrunResponses,O as VIDEO_OUT_DEFAULT_CODEC,y as VIDEO_OUT_FRAMING,k as VIDEO_OUT_WS_FRAMING,T as consumeVideoOut,x as decodeVideoOutRecord,h as encodeVideoOutRecord,w as isSupportedClientEvent,I as isSupportedResponsesEvent,S as listModels,g as negotiateSessionVideoOutQuic,f as nodeAudioBackend,A as openSessionVideoOutLane,i as toErrorEvent,v as weriftAudioBackend};
1
+ import{b as S}from"./chunk-CAR4AEQJ.js";import{c as d,g as v,h as f,i as R,j as y,k as O,l as h,m as x,n as g,o as k,p as A,q as T}from"./chunk-6M5JK4YC.js";import{a as _}from"./chunk-GL7EWL3V.js";import{c as i,f as a}from"./chunk-NN6TQQUG.js";import{c as o}from"./chunk-YSFSRI3D.js";o();o();var p=0;function V(){return p+=1,`rt_${Date.now().toString(36)}_${p.toString(36)}`}var s=class{constructor(e,t={}){this.session=e;this.opts=t;this.transport=new a(e)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await d(this.session,this.opts.audioBackend),this.audio.onOutputAudio(e=>this.emit({type:"response.audio.delta",delta:e}))}on(e,t){return this.handlers.add(t),()=>this.handlers.delete(t)}emit(e){for(let t of this.handlers)t(e)}send(e){switch(e.type){case"conversation.item.create":{let t=(e.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:e.item?.role??"user",content:t});return}case"response.create":{let t=V();this.currentRequestId=t,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:e.response},this.conversation,t);for await(let E of r)this.emit(E)}catch(r){this.emit(i(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(e.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};o();var l=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],m=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function w(n){return l.includes(n)}function I(n){return m.includes(n)}export{R as RT_VIDEO_OUT_STREAM,l as SUPPORTED_REALTIME_CLIENT_EVENTS,m as SUPPORTED_RESPONSES_EVENTS,s as UrunRealtime,_ as UrunResponses,O as VIDEO_OUT_DEFAULT_CODEC,y as VIDEO_OUT_FRAMING,k as VIDEO_OUT_WS_FRAMING,T as consumeVideoOut,x as decodeVideoOutRecord,h as encodeVideoOutRecord,w as isSupportedClientEvent,I as isSupportedResponsesEvent,S as listModels,g as negotiateSessionVideoOutQuic,f as nodeAudioBackend,A as openSessionVideoOutLane,i as toErrorEvent,v as weriftAudioBackend};