@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.
Files changed (61) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
  3. package/dist/chunk-64VO62LW.js +1 -0
  4. package/dist/chunk-BA3NCMS5.js +6 -0
  5. package/dist/chunk-DMRZZTYI.js +4 -0
  6. package/dist/chunk-FNAZ2XBE.js +20 -0
  7. package/dist/chunk-G6AFKOVS.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-HB5KNEY5.js} +1 -1
  9. package/dist/chunk-J3KCHTSA.js +6 -0
  10. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  11. package/dist/chunk-VQSCBUKT.js +66 -0
  12. package/dist/{chunk-QTHFMDZY.js → chunk-X5BLQXHK.js} +1 -1
  13. package/dist/chunk-XNRPTMSL.js +1 -0
  14. package/dist/chunk-Y774TOE7.js +2 -0
  15. package/dist/{composite-B-F2J0NK.d.cts → composite-DM2sT1Sp.d.cts} +320 -4
  16. package/dist/{composite-B--rGI5m.d.ts → composite-DNNAm0PY.d.ts} +91 -4
  17. package/dist/gemini-live.cjs +2 -2
  18. package/dist/gemini-live.d.cts +4 -4
  19. package/dist/gemini-live.d.ts +4 -4
  20. package/dist/gemini-live.js +1 -1
  21. package/dist/hosted/bin.cjs +49 -47
  22. package/dist/hosted/bin.js +1 -1
  23. package/dist/hosted/index.cjs +45 -43
  24. package/dist/hosted/index.d.cts +54 -10
  25. package/dist/hosted/index.d.ts +11 -5
  26. package/dist/hosted/index.js +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.d.cts +4 -4
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.js +1 -1
  31. package/dist/pi-extension/index.cjs +7 -7
  32. package/dist/pi-extension/index.d.cts +2 -2
  33. package/dist/pi-extension/index.d.ts +2 -2
  34. package/dist/pi-extension/index.js +1 -1
  35. package/dist/pi-extension/standalone.cjs +55 -55
  36. package/dist/pooler/bin.cjs +40 -41
  37. package/dist/pooler/bin.js +39 -40
  38. package/dist/proxy/cli.cjs +55 -53
  39. package/dist/proxy/cli.js +1 -1
  40. package/dist/proxy/conformance-probe.cjs +1 -1
  41. package/dist/proxy/conformance-probe.js +1 -1
  42. package/dist/proxy/index.cjs +34 -32
  43. package/dist/proxy/index.d.cts +37 -214
  44. package/dist/proxy/index.d.ts +17 -65
  45. package/dist/proxy/index.js +1 -1
  46. package/dist/{translator-Dox25ky9.d.cts → translator-C6MpaZS-.d.cts} +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-CaOqL-V8.d.ts} +1 -1
  48. package/dist/{types-CHPtJx6d.d.cts → types-DiYzfHYN.d.cts} +2 -0
  49. package/dist/{types-CHPtJx6d.d.ts → types-DiYzfHYN.d.ts} +2 -0
  50. package/dist/{video-out-DnCKUUO2.d.cts → video-out-A8qMuI36.d.cts} +17 -3
  51. package/dist/{video-out-REmiQMBJ.d.ts → video-out-IoTqIbAw.d.ts} +6 -2
  52. package/package.json +2 -2
  53. package/dist/chunk-G7CSAISC.js +0 -1
  54. package/dist/chunk-GX243AIV.js +0 -1
  55. package/dist/chunk-HPUX2H65.js +0 -6
  56. package/dist/chunk-IFYB6QUQ.js +0 -64
  57. package/dist/chunk-KKCUIOL4.js +0 -1
  58. package/dist/chunk-OZ7HE3VG.js +0 -23
  59. package/dist/chunk-QNJKRB7Q.js +0 -2
  60. package/dist/chunk-XKCWX72M.js +0 -6
  61. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -0,0 +1 @@
1
+ import{c as x}from"./chunk-YSFSRI3D.js";x();import{createHmac as y,randomUUID as A,timingSafeEqual as S}from"crypto";var k=["sfu","urun-doc"],I="runtime:lease",O="lane:join",D="urun-runtime-key-v1";function p(r,t){if(!r)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!t)throw new Error("deriveOrgRuntimeKey requires an orgId");return y("sha256",r).update(`${D}|${t}`).digest("base64url")}var T=120;function N(r){return Buffer.from(r).toString("base64url")}function $(r,t,i){let s=N(JSON.stringify(r)),e=N(JSON.stringify(t)),o=y("sha256",i).update(`${s}.${e}`).digest("base64url");return`${s}.${e}.${o}`}function J(r,t,i=T,s=O,e){let o=e?p(t,e):t;return _(r,o,i,s,e)}function U(r,t,i,s=T,e=O){return _(r,i,s,e,t)}function _(r,t,i,s,e){let o=Math.floor(Date.now()/1e3);return $({alg:"HS256",typ:"JWT"},{session_id:r,aud:"sfu",sub:r,scope:s,...e?{tenant:e}:{},iat:o,exp:o+i,jti:A()},t)}function j(r,t,i,s=Math.floor(Date.now()/1e3),e){let o=r.split(".");if(o.length!==3)return null;let[m,h,L]=o,E,n;try{E=JSON.parse(Buffer.from(m,"base64url").toString()),n=JSON.parse(Buffer.from(h,"base64url").toString())}catch{return null}if(E.alg!=="HS256")return null;let d;try{d=Buffer.from(L,"base64url")}catch{return null}let f=typeof n.tenant=="string"&&n.tenant!==""?n.tenant:void 0,u=[];if(f!==void 0?(u.push(p(i,f)),e&&u.push(p(e,f))):(u.push(i),e&&u.push(e)),!u.some(g=>{let b=y("sha256",g).update(`${m}.${h}`).digest();return d.length===b.length&&S(d,b)}))return null;let l=n.exp;if(typeof l!="number"||l<=s)return null;let a=typeof n.aud=="string"||Array.isArray(n.aud)?n.aud:void 0;if(!(a!==void 0&&k.some(g=>g===a||Array.isArray(a)&&a.includes(g))))return null;let c=n.session_id??n.sub;return typeof c!="string"||c!==t?null:{sessionId:c,aud:a,scope:typeof n.scope=="string"?n.scope:void 0,tenant:f,app:typeof n.app=="string"?n.app:void 0,fn:typeof n.fn=="string"?n.fn:void 0,exp:l}}export{I as a,T as b,J as c,U as d,j as e};
@@ -0,0 +1,2 @@
1
+ import{c as D}from"./chunk-BA3NCMS5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
2
+ `)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
@@ -1,6 +1,6 @@
1
1
  import { C as CatalogRow } from './models-D7F0bLJ3.cjs';
2
- import { IncomingMessage } from 'node:http';
3
- import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-DnCKUUO2.cjs';
2
+ import { IncomingMessage, Server } from 'node:http';
3
+ import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-A8qMuI36.cjs';
4
4
 
5
5
  /**
6
6
  * THE BILLING CORRELATION SEAM — one uuid per `/v1` request, returned as the
@@ -133,6 +133,15 @@ interface InferenceRecord {
133
133
  readonly output_minutes: number | null;
134
134
  /** THE OUTPUT-SECONDS METER — see {@link InferenceTurn.outputSeconds}. */
135
135
  readonly output_seconds: number | null;
136
+ /**
137
+ * THE LIVE SESSION-TIME METER (DDR addendum) — the CONNECTED SESSION
138
+ * SECONDS a realtime (`/v1/realtime`, Gemini Live) stream was up, measured
139
+ * by the realtime lane at teardown. NULL for every HTTP lane (the quantity
140
+ * does not exist there) and for a realtime dial that never connected —
141
+ * never zero of it. On the record rather than read separately by the ledger
142
+ * writer for the reason the record exists at all: one object, every sink.
143
+ */
144
+ readonly session_seconds: number | null;
136
145
  /**
137
146
  * THE INSTANCE that served this request — see
138
147
  * {@link InferenceTurn.sessionId}. On the log line as well as the ledger,
@@ -209,6 +218,267 @@ interface SessionTurnLaneEvent {
209
218
  startMs?: number;
210
219
  }
211
220
 
221
+ /**
222
+ * `attachOpenAIRealtime(server, options)` — the WS upgrade hook for the OpenAI
223
+ * Realtime surface (GA protocol subset; see protocol.ts for the event subset).
224
+ *
225
+ * Contract (Main-owned composition; this lane claims ONLY `/v1/realtime`):
226
+ * - Upgrades on any other path are passed through UNTOUCHED — a plain
227
+ * `next()` listener, so sibling lanes (Gemini Live, Responses WS) and the
228
+ * hosted composition keep their own upgrade hooks.
229
+ * - Clients are resolved/authenticated ASYNCHRONOUSLY BEFORE the upgrade is
230
+ * accepted: no 101 is written until `resolver.resolve(req, signal)`
231
+ * settles. A thrown error maps `err.status` (default 502) to the HTTP
232
+ * reject; 401/403 keep their status.
233
+ * - THE CLIENT SOCKET'S OWN CLOSE is the cancellation signal for the wait:
234
+ * a `close`/`error` on the raw pre-upgrade socket aborts the signal the
235
+ * resolver rides. A resolver that settles AFTER the client vanished never
236
+ * upgrades — its binding is released through the binding's own `release`
237
+ * seam (the native detach; a still-queued admission ticket is cancelled
238
+ * underneath it by the backhaul's abort path). A client that closes after
239
+ * admission tears down through the connection's own ws-close wiring.
240
+ * - ONE structured log line per upgrade lifecycle event (`realtime_upgrade`:
241
+ * accept → admit → close, with the binding's session id and the client
242
+ * close reason) — the lane was previously invisible in the process log.
243
+ * - The resolved binding carries a PRIVATE native uRun session (fresh or
244
+ * explicitly-resumed) and, iff voice, a PRIVATE audio bridge — never the
245
+ * pooled tenant lane. The connection's cross-caller claim is invariant
246
+ * validation, not capacity policy.
247
+ * - Returns an async close function: waits for every touched socket to
248
+ * settle, then closes the internal WebSocketServer. It does NOT end the
249
+ * native uRun sessions (detach ≠ session death — resume is Main-owned;
250
+ * the binding seam decides lifetime).
251
+ */
252
+
253
+ declare const OPENAI_REALTIME_PATH = "/v1/realtime";
254
+ /**
255
+ * The resolver seam — the ONLY credential, modality, and session-allocation
256
+ * authority this adapter recognizes. Implemented by Main's composition (and
257
+ * by tests with an injected fake). Accepted in EITHER form: a bare
258
+ * `(req, signal) => Promise<binding>` (the {@link ProxyClientsFor}-style
259
+ * convention) or a `{ resolve(req, signal) }` object. `signal` aborts when
260
+ * the CLIENT SOCKET closes/errors before the upgrade is accepted — the
261
+ * resolver SHOULD abandon its admission wait on it (the backhaul's
262
+ * `openAudioOn` rides the same signal into core `whenLive`'s own abort
263
+ * support); a resolver that ignores it still cannot admit an upgrade to a
264
+ * vanished client: the settled binding is released, never upgraded.
265
+ */
266
+ /**
267
+ * One ADMISSION WAITING-STATUS update the resolver reports while the dial
268
+ * waits for a seat (owner semantics: a dedicated realtime dial that cannot
269
+ * get a seat is NEVER refused and NEVER hangs blindly — the client sees a
270
+ * WAITING/QUEUED status and gets served when capacity appears). The `status`
271
+ * word rides the gateway's own vocabulary (core `SessionGatewayStatus`):
272
+ * `queued`, `pending`, `waiting_for_capacity` — a WAITING word, never a
273
+ * terminal one. Surfaced to the client as a `urun.admission` frame on the
274
+ * ALREADY-UPGRADED socket (see {@link RealtimeAdmissionNotifier}).
275
+ */
276
+ interface RealtimeAdmissionStatus {
277
+ status: string;
278
+ reason?: string;
279
+ queue?: {
280
+ position: number;
281
+ depth: number;
282
+ };
283
+ }
284
+ /**
285
+ * The resolver's admission-reporting callback. The FIRST call completes the
286
+ * WS upgrade IMMEDIATELY and sends the waiting frame — the client's dial
287
+ * resolves instead of hanging on a pending handshake — and every later call
288
+ * rides the SAME open socket. Frames the client sends between the upgrade
289
+ * and the binding's resolution (its open-time `session.update`) are buffered
290
+ * and replayed into the connection when the resolver settles. A resolver
291
+ * that never calls it keeps the byte-identical pre-upgrade behavior.
292
+ */
293
+ type RealtimeAdmissionNotifier = (update: RealtimeAdmissionStatus) => void;
294
+ type OpenAIRealtimeResolver<S = unknown> = ((req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier) => Promise<RealtimeBinding<S>>) | {
295
+ resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<S>>;
296
+ };
297
+ interface RealtimeBinding<S = unknown> {
298
+ /**
299
+ * The PRIVATE native uRun session serving this conversation (the shared
300
+ * per-conversation factory in hosted/tenants.ts allocates it; reuse/multi-
301
+ * attach is sanctioned ONLY for the SAME authorized conversation on an
302
+ * explicit resume — two different conversations MUST NOT receive one
303
+ * session). The upstream turn seam is EITHER form:
304
+ * - `session.sendResponseCreate(params, input, requestId)` (the direct
305
+ * SdkTransport-style seam), or
306
+ * - `clients.createResponse(params)` — the canonical ProxyClients seam
307
+ * shape (`input` rides inside `params`). The shared binding composition
308
+ * (binding.ts, ENG-446) hands out a PINNED view of it: the call dials
309
+ * `createResponseOn(handle, …)` on the ONE pooled session the binding
310
+ * resolved with the audio bridge, so no turn on the connection can
311
+ * reach a second pooled session behind the bridge's back.
312
+ * A binding with neither is rejected at upgrade time, LOUD.
313
+ */
314
+ session?: S & {
315
+ sendResponseCreate?(params: unknown, input: unknown[], requestId: string): Promise<AsyncIterable<unknown>>;
316
+ };
317
+ clients?: Pick<ProxyClients, 'createResponse'>;
318
+ /**
319
+ * Authoritative modality verdict from the resolver. A function NAME proves
320
+ * nothing — without `voice: true`, audio events are refused and no audio
321
+ * primitive is ever opened on the session.
322
+ */
323
+ voice: boolean;
324
+ /** The PRIVATE audio bridge for THIS conversation (required iff `voice`). */
325
+ audioSession?: {
326
+ audio: {
327
+ appendInputAudio(base64Pcm16: string, captureWallMs?: number): void;
328
+ onOutputAudio(handler: (b64: string) => void): () => void;
329
+ /**
330
+ * The pooled uRun session this lane rides (backhaul `openAudioOn`
331
+ * reports core `Session.id`), when the backhaul knows it — the field the
332
+ * `realtime_upgrade` log line puts on every lifecycle event so an
333
+ * orphaned session is traceable from the proxy log alone. Null is the
334
+ * honest absence (an id-less session reports no id); sessionIdOf
335
+ * normalizes it to the omitted field below.
336
+ */
337
+ sessionId?: string | null;
338
+ };
339
+ /** Cross-caller reuse registry (invariant validation; see connection.ts). */
340
+ openaiRealtimeClaims?: Set<RealtimeBinding['audioSession']>;
341
+ };
342
+ /** `model` the binding names for this conversation (overrides session config default). */
343
+ model?: string;
344
+ /**
345
+ * THE DIAL-TIME BILLING IDENTITY (session-time billing) — the catalog
346
+ * identity the session dial resolved, captured at resolution time by the
347
+ * shared binding composition and carried here for the teardown hook's
348
+ * ledger row. Absent (no oracle wired, or the composite lane) ⇒ the
349
+ * ledger row is skipped LOUD (`model_unresolved`), never guessed.
350
+ */
351
+ catalog?: TurnCatalogIdentity;
352
+ /**
353
+ * The NATIVE video frame lane (the §5 `rt-video-in` named-DATA path —
354
+ * enableSessionVideo on a pooled session, the lane stream relay's
355
+ * `rt-video-in` channel on a proxy-hosted lane), resolved on the SAME
356
+ * pooled session identity the voice binding rides. LAZY: the lane opens on
357
+ * the first `conversation.item.create` `input_image` frame, never at
358
+ * binding time. Optional at the seam: an absent opener means the embedder
359
+ * wired no video seam — the connection answers image frames with the LOUD
360
+ * error event, never a silent drop.
361
+ */
362
+ video?: () => Promise<ProxyVideoLane>;
363
+ /**
364
+ * The GA transcription-session intent (`?intent=transcription`): this
365
+ * connection is a TRANSCRIPTION session — transcription events flow
366
+ * without the client opting in, and `response.create` answers the loud
367
+ * `unsupported` error (the connection stays open) because there are no
368
+ * model turns to create. Set by the shared binding composition (binding.ts)
369
+ * only when the resolver's URL carried the intent AND the model's catalog
370
+ * row vouches stt (the binding carries `turns`). Absent = the realtime
371
+ * (voice) session, today's behaviour.
372
+ */
373
+ intent?: 'transcription';
374
+ /** True when `session` is a resumed authorized session (vs a fresh private one). */
375
+ resumed?: boolean;
376
+ /**
377
+ * The backend's OWN turn/transcript lane — the §5 `stt` named stream
378
+ * (urun.serve.transcribe_bridge wire shape: `t` = delta/final/turn_start/
379
+ * turn_end/turn_eager_end/turn_resumed, `delta` text, additive `start_ms`
380
+ * and semantic-VAD `confidence`). The resolver maps `session.stream('stt')
381
+ * .messages()` onto this. Its `turn_end` IS the native commit and
382
+ * `turn_start` IS the native barge-in — the adapter drives server-VAD
383
+ * emulation, real transcription events, and model-visible committed audio
384
+ * from it. Absent = the backend wired no turn lane: manual mode only.
385
+ *
386
+ * The CONSUMER passes its own lifecycle `signal` (the realtime connection's
387
+ * turn-lane controller): the lane must END its stream subscription when it
388
+ * aborts — the transport races its pulls against it — so the subscription
389
+ * never outlives the consumer. A consumer that passes none gets an
390
+ * un-raced lane (its own teardown is then its own problem).
391
+ */
392
+ turns?: (signal?: AbortSignal) => AsyncIterable<{
393
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
394
+ text?: string;
395
+ confidence?: number;
396
+ startMs?: number;
397
+ }>;
398
+ /**
399
+ * THE COMPOSITE LANE (ENG-451, openai-realtime/composite.ts): this binding
400
+ * composes THREE pinned sessions — the `stt` leg behind `turns` and the
401
+ * composed bridge's IN side, the bound chat row behind
402
+ * `clients.createResponse`, and the `tts` leg behind the bridge's OUT side
403
+ * and the per-sentence synthesis turns. The connection keys its
404
+ * live-transcription-in semantics on this marker: appends stream to the
405
+ * stt leg live, the client's commits own turn boundaries, a committed
406
+ * item's pending transcript gates the model turn (and is written into the
407
+ * item — it is the chat leg's input), and `turn_detection: null` is the
408
+ * only accepted mode. A dead leg's failure is a `SessionGoneError` NAMING
409
+ * the leg — the loud `session_gone` close carries the name.
410
+ */
411
+ composite?: true;
412
+ /**
413
+ * THE COMPOSITE TURN'S PROMPT CANCEL (ENG-451): stop the ACTIVE turn's
414
+ * legs beyond the turn seam — the composite binding aborts its per-turn
415
+ * controller, which unwinds the tts leg's in-flight synthesis read and
416
+ * drops its queued sentence chunks NOW. The connection calls it from
417
+ * `response.cancel` and from teardown; the for-await `break` alone only
418
+ * unwinds at the turn stream's NEXT event, which is too late for legs
419
+ * that keep consuming GPU on their own. Absent (every one-session
420
+ * binding) = nothing to stop beyond the stream, exactly as before.
421
+ */
422
+ cancelActiveTurn?: () => void;
423
+ /**
424
+ * Release THIS attachment when the socket closes (the hosted
425
+ * conversation-factory seam — the twin of the Gemini Live binding's
426
+ * `release`): per-attachment release, native detach underneath, the named
427
+ * session itself stays live. Absent (the local fixed-clients lane) = the
428
+ * pooled sessions are the process's own and outlive the socket.
429
+ */
430
+ release?: () => Promise<void> | void;
431
+ }
432
+ interface OpenAIRealtimeOptions<S = unknown> {
433
+ resolver: OpenAIRealtimeResolver<S>;
434
+ /**
435
+ * Where the per-upgrade structured `realtime_upgrade` lines go (ONE
436
+ * newline-terminated JSON object per lifecycle event: accept → admit →
437
+ * close). Absent, the line goes to this process's stdout through the repo's
438
+ * canonical guarded write — the hosted container's collected log stream.
439
+ * Emitted unconditionally, never behind a verbosity flag: this lane's
440
+ * lifecycle was previously invisible in the process log, which is exactly
441
+ * why an orphaned queued admission could only be diagnosed from the
442
+ * session-server side.
443
+ */
444
+ log?: (line: string) => void;
445
+ /**
446
+ * Where the caller-message boundary's WITHHOLD receipts go (ENG-538): every
447
+ * time a realtime event keeps raw error text off the wire, the raw text is
448
+ * owed here — one newline-terminated line per withheld failure, carrying the
449
+ * connection/session ids for correlation. Absent, the receipt goes to
450
+ * `console.error` of THIS process; the hosted proxy passes its canonical
451
+ * operator sink so nothing is ever dropped on the floor.
452
+ */
453
+ operatorLog?: (line: string) => void;
454
+ /**
455
+ * THE LIVE-SESSION LEDGER HOOK (session-time billing, DDR addendum):
456
+ * called ONCE per ADMITTED connection at teardown — the moment the live
457
+ * stream ended — with the connected window this adapter measured
458
+ * (acceptBinding → onClosed, wall-clock). The hosted composition turns it
459
+ * into the `task='realtime'` ledger row priced from
460
+ * `session_seconds = connected_ms / 1000`; see hosted/server.ts. NEVER
461
+ * called for a dial that was still queued when its client vanished (no
462
+ * connected stream, no row — an allocated-but-never-connected segment is
463
+ * not delivered product, the DDR principle verbatim).
464
+ */
465
+ onSessionEnded?: (info: {
466
+ /** The ORIGINAL upgrade request (the bearer the ledger write rides). */
467
+ req: IncomingMessage;
468
+ /** The binding that served the live stream. */
469
+ binding: RealtimeBinding<S>;
470
+ /** CONNECTED SESSION TIME in whole milliseconds (admit → close). */
471
+ connected_ms: number;
472
+ /** The close reason the connection itself reported. */
473
+ reason: string;
474
+ }) => void;
475
+ }
476
+ /**
477
+ * Attach the OpenAI Realtime WS endpoint to `server`. Upgrades on any other
478
+ * path pass through untouched. Returns an async close function.
479
+ */
480
+ declare function attachOpenAIRealtime<S = unknown>(server: Server, options: OpenAIRealtimeOptions<S>): () => Promise<void>;
481
+
212
482
  /**
213
483
  * WHAT a proxy serves — the `identity` block on `GET /stats`. Reuse of a
214
484
  * running proxy is allowed iff every field matches the launching invocation
@@ -1027,6 +1297,21 @@ declare class ModelRouter<S> {
1027
1297
  * opens NOTHING.
1028
1298
  */
1029
1299
  resolveTargetFor(model: string | undefined): Promise<RouteTarget>;
1300
+ /**
1301
+ * THE REALTIME LANE'S BILLING IDENTITY (session-time billing, DDR
1302
+ * addendum): the {@link TurnCatalogIdentity} the model's dial resolves —
1303
+ * the SAME {@link resolveTarget} answer the session dial's acquisition
1304
+ * uses. The realtime resolver calls this ONCE at resolution time (the same
1305
+ * handler tick as the session dial, so the capture rides the dial's own
1306
+ * cache window) and the answer rides the binding to the connection's
1307
+ * teardown, where the ledger row is built — never a re-resolution after
1308
+ * the session closed, the drift the per-request ledger's own docs warn
1309
+ * against. A catalog identity is ALWAYS returned here: an undeployed
1310
+ * model throws {@link UnknownModelError} (the lane's loud 404), and a
1311
+ * caller-org app target carries its slug flavour — the same two flavours
1312
+ * {@link billingIdentityOf} travels.
1313
+ */
1314
+ realtimeBillingIdentityFor(model: string | undefined): Promise<TurnCatalogIdentity>;
1030
1315
  /**
1031
1316
  * The SPEECH lane's pooled session for a model — the SAME resolution and
1032
1317
  * acquisition as {@link sessionFor}, stored under a LANE-SCOPED pool key
@@ -1804,6 +2089,16 @@ interface LedgerWrite {
1804
2089
  * still relays the seconds (the weights stay null).
1805
2090
  */
1806
2091
  output_seconds: number | null;
2092
+ /**
2093
+ * THE LIVE SESSION-TIME METER (DDR addendum) — the CONNECTED SESSION
2094
+ * SECONDS a realtime (`/v1/realtime`, Gemini Live) stream was up, measured
2095
+ * by the realtime lane at teardown (admit → close). The control plane
2096
+ * prices a `per_session_second` task from THIS field (`task_billing_units`
2097
+ * declares `realtime` exactly so, urun-infra 20271266000000). NULL = the
2098
+ * lane is not a live session (every HTTP lane) or never connected — never
2099
+ * zero of it, and never coerced: an unmeasured window prices nothing.
2100
+ */
2101
+ session_seconds: number | null;
1807
2102
  /**
1808
2103
  * THE WEIGHT (ENG-417) — the serve runtime's own residency in whole
1809
2104
  * milliseconds. An allocation input, never GPU time and never a cost. NULL
@@ -2436,8 +2731,15 @@ interface ProxyClients {
2436
2731
  * client-gone wait rides the SAME per-entry refcount as {@link openAudio}:
2437
2732
  * one of several waiters aborting rejects only that caller's open, the
2438
2733
  * queued admission going back only at the LAST waiter's abort.
2734
+ *
2735
+ * `onAdmission` is the WAITING-STATUS surface (the dedicated realtime
2736
+ * dial's `urun.admission` frame, attach.ts): called once when the handle's
2737
+ * session is not yet live — the dial's admission is pending — with the
2738
+ * gateway-vocabulary waiting word (`queued` / `pending` /
2739
+ * `waiting_for_capacity`). Absent ⇒ no status surface (the speech lane
2740
+ * passes none; a live session never triggers a call).
2439
2741
  */
2440
- openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string): Promise<PinnedAudioLane>;
2742
+ openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<PinnedAudioLane>;
2441
2743
  /**
2442
2744
  * The HANDLE-ADDRESSED video frame lane open (the realtime binding's
2443
2745
  * `input_image` camera frames): the SAME native rt-video-in frame path
@@ -2538,6 +2840,20 @@ interface ProxyClients {
2538
2840
  * compat proxy and existing test doubles are untouched.
2539
2841
  */
2540
2842
  dedicatedSessionHandle?(model: string | undefined): Promise<string>;
2843
+ /**
2844
+ * THE REALTIME LANE'S BILLING IDENTITY (session-time billing, DDR
2845
+ * addendum): the {@link TurnCatalogIdentity} the model's dial resolves,
2846
+ * captured AT RESOLUTION TIME — the same handler tick the session dial
2847
+ * runs in, so the capture rides the dial's own cache window and the ledger
2848
+ * row names the catalog row that actually vouched the session. The realtime
2849
+ * binding is PINNED to its one session for the connection's whole life
2850
+ * (ENG-446 — no mid-session re-home), so a dial-time capture is correct for
2851
+ * the session's entire connected window; the per-request re-pin discipline
2852
+ * (`repinOnDial`) has no realtime analog because there is no second dial.
2853
+ * Optional at the seam: absent ⇒ the binding carries no identity and the
2854
+ * ledger row is skipped LOUD (`model_unresolved`), never guessed.
2855
+ */
2856
+ realtimeBillingIdentityFor?(model: string | undefined): Promise<TurnCatalogIdentity>;
2541
2857
  /**
2542
2858
  * THE SPEECH LANE'S OWN HANDLE (greptile urun-ts#500): the opaque handle
2543
2859
  * for the SPEECH-SCOPED pooled session (`speech:<pool key>` — routing.ts
@@ -2806,4 +3122,4 @@ interface RealtimeCompanions {
2806
3122
  */
2807
3123
  type RealtimeCompanionsFor = (model: string | undefined) => Promise<RealtimeCompanions | null>;
2808
3124
 
2809
- export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type ProxyVideoLane as h, type ProxyVideoOutLane as i, type RouteTarget as j, type UsageRowReporter as k, billingIdentityOf as l };
3125
+ export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, OPENAI_REALTIME_PATH as O, type ProxyClients as P, type RealtimeAdmissionNotifier as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type OpenAIRealtimeOptions as f, type OpenAIRealtimeResolver as g, type ProxyHandlerOptions as h, type ProxyIdentity as i, type ProxyVideoOutLane as j, type RealtimeBinding as k, type RealtimeCompanionsFor as l, type RouteTarget as m, type UsageRowReporter as n, attachOpenAIRealtime as o, billingIdentityOf as p };
@@ -1,6 +1,6 @@
1
1
  import { C as CatalogRow } from './models-D7F0bLJ3.js';
2
- import { IncomingMessage } from 'node:http';
3
- import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-REmiQMBJ.js';
2
+ import { IncomingMessage, Server } from 'node:http';
3
+ import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-IoTqIbAw.js';
4
4
 
5
5
  type TurnCatalogIdentity = {
6
6
  kind: 'catalog';
@@ -46,6 +46,8 @@ interface InferenceRecord {
46
46
 
47
47
  readonly output_seconds: number | null;
48
48
 
49
+ readonly session_seconds: number | null;
50
+
49
51
  readonly session_id: string | null;
50
52
 
51
53
  readonly queue_ms: number | null;
@@ -71,6 +73,85 @@ interface SessionTurnLaneEvent {
71
73
  startMs?: number;
72
74
  }
73
75
 
76
+ declare const OPENAI_REALTIME_PATH = "/v1/realtime";
77
+
78
+ interface RealtimeAdmissionStatus {
79
+ status: string;
80
+ reason?: string;
81
+ queue?: {
82
+ position: number;
83
+ depth: number;
84
+ };
85
+ }
86
+
87
+ type RealtimeAdmissionNotifier = (update: RealtimeAdmissionStatus) => void;
88
+ type OpenAIRealtimeResolver<S = unknown> = ((req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier) => Promise<RealtimeBinding<S>>) | {
89
+ resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<S>>;
90
+ };
91
+ interface RealtimeBinding<S = unknown> {
92
+
93
+ session?: S & {
94
+ sendResponseCreate?(params: unknown, input: unknown[], requestId: string): Promise<AsyncIterable<unknown>>;
95
+ };
96
+ clients?: Pick<ProxyClients, 'createResponse'>;
97
+
98
+ voice: boolean;
99
+
100
+ audioSession?: {
101
+ audio: {
102
+ appendInputAudio(base64Pcm16: string, captureWallMs?: number): void;
103
+ onOutputAudio(handler: (b64: string) => void): () => void;
104
+
105
+ sessionId?: string | null;
106
+ };
107
+
108
+ openaiRealtimeClaims?: Set<RealtimeBinding['audioSession']>;
109
+ };
110
+
111
+ model?: string;
112
+
113
+ catalog?: TurnCatalogIdentity;
114
+
115
+ video?: () => Promise<ProxyVideoLane>;
116
+
117
+ intent?: 'transcription';
118
+
119
+ resumed?: boolean;
120
+
121
+ turns?: (signal?: AbortSignal) => AsyncIterable<{
122
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
123
+ text?: string;
124
+ confidence?: number;
125
+ startMs?: number;
126
+ }>;
127
+
128
+ composite?: true;
129
+
130
+ cancelActiveTurn?: () => void;
131
+
132
+ release?: () => Promise<void> | void;
133
+ }
134
+ interface OpenAIRealtimeOptions<S = unknown> {
135
+ resolver: OpenAIRealtimeResolver<S>;
136
+
137
+ log?: (line: string) => void;
138
+
139
+ operatorLog?: (line: string) => void;
140
+
141
+ onSessionEnded?: (info: {
142
+
143
+ req: IncomingMessage;
144
+
145
+ binding: RealtimeBinding<S>;
146
+
147
+ connected_ms: number;
148
+
149
+ reason: string;
150
+ }) => void;
151
+ }
152
+
153
+ declare function attachOpenAIRealtime<S = unknown>(server: Server, options: OpenAIRealtimeOptions<S>): () => Promise<void>;
154
+
74
155
  interface ProxyIdentity {
75
156
  app: string;
76
157
  org: string;
@@ -304,6 +385,8 @@ declare class ModelRouter<S> {
304
385
 
305
386
  resolveTargetFor(model: string | undefined): Promise<RouteTarget>;
306
387
 
388
+ realtimeBillingIdentityFor(model: string | undefined): Promise<TurnCatalogIdentity>;
389
+
307
390
  speechSessionFor(model: string | undefined): Promise<{
308
391
  app: string;
309
392
  entry: S;
@@ -471,6 +554,8 @@ interface LedgerWrite {
471
554
 
472
555
  output_seconds: number | null;
473
556
 
557
+ session_seconds: number | null;
558
+
474
559
  queue_ms: number | null;
475
560
  prefill_ms: number | null;
476
561
  decode_ms: number | null;
@@ -600,7 +685,7 @@ interface ProxyClients {
600
685
 
601
686
  openAudio?(model: string | undefined, signal?: AbortSignal): Promise<ProxyAudioLane>;
602
687
 
603
- openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string): Promise<PinnedAudioLane>;
688
+ openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<PinnedAudioLane>;
604
689
 
605
690
  openVideoOn?(handle: string, signal?: AbortSignal): Promise<ProxyVideoLane>;
606
691
 
@@ -618,6 +703,8 @@ interface ProxyClients {
618
703
 
619
704
  dedicatedSessionHandle?(model: string | undefined): Promise<string>;
620
705
 
706
+ realtimeBillingIdentityFor?(model: string | undefined): Promise<TurnCatalogIdentity>;
707
+
621
708
  speechSessionHandle?(model: string | undefined): Promise<string>;
622
709
 
623
710
  evictSpeechSession?(handle: string): Promise<void>;
@@ -679,4 +766,4 @@ interface RealtimeCompanions {
679
766
 
680
767
  type RealtimeCompanionsFor = (model: string | undefined) => Promise<RealtimeCompanions | null>;
681
768
 
682
- export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type ProxyVideoLane as h, type ProxyVideoOutLane as i, type RouteTarget as j, type UsageRowReporter as k, billingIdentityOf as l };
769
+ export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, OPENAI_REALTIME_PATH as O, type ProxyClients as P, type RealtimeAdmissionNotifier as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type OpenAIRealtimeOptions as f, type OpenAIRealtimeResolver as g, type ProxyHandlerOptions as h, type ProxyIdentity as i, type ProxyVideoOutLane as j, type RealtimeBinding as k, type RealtimeCompanionsFor as l, type RouteTarget as m, type UsageRowReporter as n, attachOpenAIRealtime as o, billingIdentityOf as p };