@urun-sh/openai 0.6.49 → 0.6.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-3JZAWWVV.js → chunk-6WTMEJZS.js} +1 -1
- package/dist/chunk-OZVX4WPP.js +4 -0
- package/dist/chunk-PL4MNBET.js +20 -0
- package/dist/{chunk-X23WP5HQ.js → chunk-V6WQRPUO.js} +4 -4
- package/dist/{chunk-2KMMXZLV.js → chunk-XKKQ2NEZ.js} +1 -1
- package/dist/{composite-QilJ-Faj.d.cts → composite-D7icObdD.d.cts} +25 -0
- package/dist/{composite-D0ivH65M.d.ts → composite-DyRe-KRu.d.ts} +8 -0
- package/dist/hosted/bin.cjs +46 -46
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +44 -44
- package/dist/hosted/index.d.cts +10 -1
- package/dist/hosted/index.d.ts +5 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +52 -52
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +44 -44
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +3 -3
- package/dist/proxy/index.d.cts +3 -3
- package/dist/proxy/index.d.ts +3 -3
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-ELH2AYM6.js +0 -20
- package/dist/chunk-NZ5EWOMJ.js +0 -4
package/dist/proxy/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-
|
|
2
|
+
import{c as J,d as q,e as H,f as Y,g as V}from"../chunk-OZVX4WPP.js";import"../chunk-CAR4AEQJ.js";import{F as K}from"../chunk-V6WQRPUO.js";import"../chunk-X5BLQXHK.js";import{g as R}from"../chunk-64VO62LW.js";import"../chunk-XGAF2NDT.js";import{d as v,e as $,f as C,g as U,h as I,i as L,j as N,k as O,l as x,m as _,n as g,p as G,q as P,r as D,s as M,t as A,u as W,v as b,w as B,x as j,y as F}from"../chunk-6WTMEJZS.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{c as h}from"../chunk-YSFSRI3D.js";h();import{spawn as ee}from"child_process";import{appendFileSync as T,createWriteStream as de,existsSync as pe,mkdirSync as ne}from"fs";import re from"path";import n from"process";h();import{ensureNodeWebRTC as ae,nodeWebRTCUnavailableReason as le}from"@urun-sh/core/internal";var ue={ensureWebRTC:ae,webrtcUnavailableReason:le,audioBackend:R};async function z(e=ue){try{await e.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function fe(e,i){let t=(e.URUN_CATALOG_URL??"").trim(),l=t?G(t,"URUN_CATALOG_URL"):"",s=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!s?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
|
|
3
3
|
`),null):{catalogUrl:l,anonKey:s}}function me(e){let i={baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:fe(n.env,l=>n.stderr.write(l)),decisionPool:J(n.env,n.env.HOSTNAME)??void 0},t=H(i);return{router:t,decision:i.decisionPool?Y(i,t):null}}async function Q(e,i,t){let l=ee(e,i,{stdio:"inherit",env:t});return new Promise(s=>{l.once("exit",r=>s(r??1)),l.once("error",r=>{n.stderr.write(`failed to launch ${e}: ${String(r)}
|
|
4
4
|
`),s(127)})})}function X(){return N(n.env,import.meta.url,pe)}function te(e){for(let[i,t]of Object.entries($(e)))n.stdout.write(`export ${i}=${t}
|
|
5
5
|
`)}async function Z(e,i){let t=g(n.env),l=i?P(t):void 0,{router:s,decision:r}=me(t);r&&(r.boot().then(()=>r.reap()).catch(u=>n.stderr.write(`[decision-pool] boot FAILED: ${String(u instanceof Error?u.message:u)}
|
package/dist/proxy/index.cjs
CHANGED
|
@@ -10,15 +10,15 @@ Connection: close\r
|
|
|
10
10
|
Content-Type: text/plain; charset=utf-8\r
|
|
11
11
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
12
12
|
\r
|
|
13
|
-
${o}`)}function Ir(t,e){let n=new Te.WebSocketServer({noServer:!0,maxPayload:Ei}),r=new Me,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,p,c)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Bt(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>s.delete(p)),f.pathname!==Ai){s.add(p);return}i.add(p);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Bt(p,401,"invalid local proxy api key");return}let S;try{S=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Bt(p,_?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(m=!0,n.handleUpgrade(d,p,c,k=>{i.delete(p),o.add(k),k.on("close",()=>o.delete(k));try{new wn(k,S,r,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!p.destroyed&&Bt(p,500,"responses websocket upgrade failed")}).finally(()=>i.delete(p))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:p}=vn();if(u)return p(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let c=setTimeout(()=>{for(let f of o)f.readyState!==Te.WebSocket.CLOSED&&f.terminate()},2e3);return c.unref?.(),n.close(()=>{clearTimeout(c),p()}),d}}}var Tn=require("@urun-sh/core");var Tr=require("@urun-sh/core"),$i={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Mi={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ht(t,e){let n=Mi[t.code];return e?`${n} (${e})`:n}function qt(t){if(t==null)return null;let e=$i[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function jt(t){if(t.kind==="create-failed")return qt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Tr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return qt(e?"cold_start_exceeded":"queue_timeout")}var Li=Kn(require("os"),1),Ni=Kn(require("path"),1),Ui=require("url"),Di=require("util");var Fi=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bi(t){let e=t?.code;return typeof e=="string"&&Fi.has(e)}function Fe(t,e){try{return t.write(e),!0}catch(n){if(Bi(n))return!1;throw n}}var yt=require("ws");var $r=require("@urun-sh/core");var Pr=require("crypto");function E(t){return`${t}_${(0,Pr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Ht=4*1024*1024,bn=8*1024*1024,Sn=512,Jt=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ae(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:E("event"),error:t}}function kn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},qi={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},ji={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Hi={format:!0,voice:!0,speed:!0};function Ji(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function tt(t,e){if(!Array.isArray(t)||t.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Or(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Gi=10;function xn(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Gi})}function gt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new T("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in qi));if(i.length>0)throw new T(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=tt(o.modalities,"modalities"),u=tt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new T('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new T(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=tt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new T('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ji(u))throw new T(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new T("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");s.instructions=xn(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!n.voice)throw new T("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new T(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new T("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new T(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new T("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new T("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new T("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let p=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[c,f]of Object.entries(l))if(!(c==="type"||c==="create_response"||c==="interrupt_response")){if(!(c in p))throw new T(`turn_detection.${c} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${c}`,"unsupported_field");if(f!=null&&f!==p[c])throw new T(`turn_detection.${c} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${c}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new T("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new T("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new T(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new T(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new T("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.input must be an object","audio.input");for(let p of Object.keys(d))if(!(p in ji))throw new T(`audio.input field not supported by this backend: ${p}`,`audio.input.${p}`,"unsupported_field");if(d.format!==void 0&&Or(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let p=gt({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=p.inputAudioTranscription}if(d.turn_detection!==void 0){let p=gt({turn_detection:d.turn_detection},s,n,r);s.turnDetection=p.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.output must be an object","audio.output");for(let p of Object.keys(d))if(!(p in Hi))throw new T(`audio.output field not supported by this backend: ${p}`,`audio.output.${p}`,"unsupported_field");if(d.format!==void 0&&Or(d.format,"audio.output.format"),d.speed!==void 0)throw new T("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new T("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new T("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Gt(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Rn(t,e){let n=t;if(!n||typeof n!="object")throw new T("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:E("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new T("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new T("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new T(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new T("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new T("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new T("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new T("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new T("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new T(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:E("item"),type:"message",role:r,content:o}}throw new T(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Vt(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Vi=1001,Wi=1011,Ki=15e3,zi=3e5;var Wt=class extends Error{},Kt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Be=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},An=t=>t.slice(0,120),Yi=/^[A-Za-z0-9+/=]*$/,Xi=2;function Qi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Xi)return!1;return!0}var qe=class{id=E("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=kn();sessionId=E("sess");conversationId=E("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Ki,this.responseDeadlineMs=e.responseDeadlineMs??zi,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===pn&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:E("event"),session:Gt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(V(Ae("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:E("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:E("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:E("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=E("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Ht){this.fail(Q("frame_too_large",`frame exceeds the ${Ht}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(V({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(o instanceof Wt){this.fail(Ae(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
14
|
-
${o?.stack??fe(o)}`),this.send(V(Ae(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(V(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:E("event"),session:Gt(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Rn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(i=>i.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:E("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(V(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:E("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(V(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Yi.test(e.audio)){this.send(V(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Jt){this.send(V(Q("buffer_full",`uncommitted input audio exceeds the ${Jt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(V(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(V(Q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(Q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,An("session ended by client"))}catch{}});return}default:this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Wt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let i;if(o||this.turnStallMs<=0){o=!1;let s=n.next();s.catch(()=>{}),i=r?await Promise.race([s,r]):await s}else{let s,a=new Promise((d,p)=>{s=setTimeout(()=>p(new Kt),this.turnStallMs)}),u=n.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(s))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(V(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?tt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?tt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new T("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(V(Q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let s=()=>{},a=new Promise((R,x)=>{s=()=>x(new Be)});this.turnCancelled=a,this.wakeTurnCancelled=()=>s(),a.catch(()=>{});let u=()=>{},l=new Promise((R,x)=>{u=()=>x(new Be)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=E("req"),c=`resp_${p}`;this.activeResponseId=c,this.activeRequestId=p;let f=this.binding.composite===!0,m=f?0:this.items.length,S=f?null:Vt(this.items),k=xn(typeof n.instructions=="string"?n.instructions:this.config.instructions),_=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=n.tools!==void 0?n.tools:this.config.tools,L=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,C={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...L!==void 0?{tool_choice:L}:{}};if(!(f&&!this.ensureVoice())){for(let{audio:R,captureWallMs:x}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R,x);this.inFlight=(async()=>{let R=[],x=$=>{this.responseFlushed?this.send($):R.push($)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(c,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(c,"in_progress")});for(let $ of R)this.send($);R.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,A=()=>{this.closeOpenItems(c,h,m),I(),this.send({type:"response.done",event_id:E("event"),response:this.responseObject(c,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(f){if(this.pendingTranscriptItemId!==null&&(await new Promise(P=>{this.pendingTranscriptSettled=P}),this.cancelled||this.closed))throw new Be;m=this.items.length,S=Vt(this.items)}let{input:$,sawAudioOnlyItem:j}=S??{input:[],sawAudioOnlyItem:!1},H={...C,input:$,...f?this.compositeTurnAsk(n):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let M;try{let P=this.upstreamStream(H,p);Promise.resolve(P).catch(U=>{U instanceof X&&this.failSessionGone(U)}),M=await Promise.race([P,l])}catch(P){if(P instanceof Be){this.deadlineFired&&!this.closed&&A();return}this.upstreamTurnFault(P,c);return}I();try{for await(let P of this.stallBoundedTurn(M)){if(this.cancelled)break;let U=P;if(U.type==="error"){let B=this.upstreamErrorBody(U);h.contentFlowed?this.send(V(B)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(c,B)});return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(c,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&x({type:"response.output_text.delta",event_id:E("event"),item_id:`${c}_msg_0`,response_id:c,output_index:0,content_index:0,delta:U.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,x({type:"response.output_audio_transcript.delta",event_id:E("event"),item_id:`${c}_msg_0`,response_id:c,output_index:0,content_index:0,delta:U.delta})),h.messageText+=U.delta;continue}if(U.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let B=typeof U.delta=="string"?U.delta:"",z=typeof U.call_id=="string"&&U.call_id.length>0?U.call_id:`${c}_fc_${h.nextOutputIndex}`,O=h.tools.get(z);if(!O){let F=typeof U.name=="string"&&U.name.length>0?U.name:void 0;O={outputIndex:h.nextOutputIndex++,name:F,args:""},h.tools.set(z,O);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:F??"",arguments:"",status:"in_progress"};x({type:"response.output_item.added",event_id:E("event"),response_id:c,output_index:O.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof U.name=="string"&&U.name.length>0&&(O.name=U.name),O.args+=B,x({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:z,response_id:c,output_index:O.outputIndex,call_id:z,name:O.name??"",delta:B});continue}if(U.type==="response.completed"){v=U.response??null;continue}}}catch(P){if(this.closed)return;if(P instanceof Be){this.deadlineFired&&A();return}if(this.cancelled)return;if(P instanceof Kt)this.operatorLog(`[realtime] turn ${c} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(P,c);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&A();return}this.closeOpenItems(c,h,m),I(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(c,m,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Qi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:E("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Se(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??_e(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Ae(fn,"the organization is out of credits \u2014 top up to continue"),fn))}failSessionGone(e){if(e instanceof X&&e.reason===pn){this.failInsufficientCredits();return}let n=e instanceof Error&&ye(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${fe(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Ae("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof $r.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ae(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:E("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Sn&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(V(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>mn){this.send(V(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${mn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(V(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(V(Ae(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>bn){this.ws.close(Vi,An("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=le(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${fe(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Wi,An(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Cr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Cr(this.id,e)}},En=[];function Cr(t,e){En.push({id:t,reason:e}),En.length>256&&En.shift()}var _t="/v1/realtime",Mr="urun.admission",Lr=t=>t.slice(0,120);function Zi(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
13
|
+
${o}`)}function Ir(t,e){let n=new Te.WebSocketServer({noServer:!0,maxPayload:Ei}),r=new Me,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,p,c)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Bt(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>s.delete(p)),f.pathname!==Ai){s.add(p);return}i.add(p);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Bt(p,401,"invalid local proxy api key");return}let S;try{S=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Bt(p,_?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(m=!0,n.handleUpgrade(d,p,c,k=>{i.delete(p),o.add(k),k.on("close",()=>o.delete(k));try{new wn(k,S,r,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!p.destroyed&&Bt(p,500,"responses websocket upgrade failed")}).finally(()=>i.delete(p))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:p}=vn();if(u)return p(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let c=setTimeout(()=>{for(let f of o)f.readyState!==Te.WebSocket.CLOSED&&f.terminate()},2e3);return c.unref?.(),n.close(()=>{clearTimeout(c),p()}),d}}}var Tn=require("@urun-sh/core");var Tr=require("@urun-sh/core"),$i={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Mi={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ht(t,e){let n=Mi[t.code];return e?`${n} (${e})`:n}function qt(t){if(t==null)return null;let e=$i[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function jt(t){if(t.kind==="create-failed")return qt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Tr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return qt(e?"cold_start_exceeded":"queue_timeout")}var Li=Kn(require("os"),1),Ni=Kn(require("path"),1),Ui=require("url"),Di=require("util");var Fi=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bi(t){let e=t?.code;return typeof e=="string"&&Fi.has(e)}function Fe(t,e){try{return t.write(e),!0}catch(n){if(Bi(n))return!1;throw n}}var yt=require("ws");var $r=require("@urun-sh/core");var Pr=require("crypto");function E(t){return`${t}_${(0,Pr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Ht=4*1024*1024,bn=8*1024*1024,Sn=512,Jt=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ae(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:E("event"),error:t}}function kn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},qi={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},ji={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Hi={format:!0,voice:!0,speed:!0};function Ji(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function tt(t,e){if(!Array.isArray(t)||t.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Or(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Gi=10;function xn(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Gi})}function gt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new T("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in qi));if(i.length>0)throw new T(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=tt(o.modalities,"modalities"),u=tt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new T('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new T(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=tt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new T('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ji(u))throw new T(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new T("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");s.instructions=xn(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!n.voice)throw new T("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new T(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new T("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new T(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new T("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new T("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new T("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let p=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[c,f]of Object.entries(l))if(!(c==="type"||c==="create_response"||c==="interrupt_response")){if(!(c in p))throw new T(`turn_detection.${c} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${c}`,"unsupported_field");if(f!=null&&f!==p[c])throw new T(`turn_detection.${c} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${c}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new T("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new T("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new T(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new T(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new T("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new T("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.input must be an object","audio.input");for(let p of Object.keys(d))if(!(p in ji))throw new T(`audio.input field not supported by this backend: ${p}`,`audio.input.${p}`,"unsupported_field");if(d.format!==void 0&&Or(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let p=gt({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=p.inputAudioTranscription}if(d.turn_detection!==void 0){let p=gt({turn_detection:d.turn_detection},s,n,r);s.turnDetection=p.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new T("audio.output must be an object","audio.output");for(let p of Object.keys(d))if(!(p in Hi))throw new T(`audio.output field not supported by this backend: ${p}`,`audio.output.${p}`,"unsupported_field");if(d.format!==void 0&&Or(d.format,"audio.output.format"),d.speed!==void 0)throw new T("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new T("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new T("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Gt(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Rn(t,e){let n=t;if(!n||typeof n!="object")throw new T("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:E("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new T("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new T("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new T(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new T("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new T("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new T("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new T("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new T("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new T(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:E("item"),type:"message",role:r,content:o}}throw new T(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Vt(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Vi=1001,Wi=1011,Ki=6e4,zi=3e5;var Wt=class extends Error{},Kt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Be=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},An=t=>t.slice(0,120),Yi=/^[A-Za-z0-9+/=]*$/,Xi=2;function Qi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Xi)return!1;return!0}var qe=class{id=E("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=kn();sessionId=E("sess");conversationId=E("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Ki,this.responseDeadlineMs=e.responseDeadlineMs??zi,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===pn&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:E("event"),session:Gt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(V(Ae("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:E("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:E("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:E("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=E("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Ht){this.fail(Q("frame_too_large",`frame exceeds the ${Ht}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(V({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(o instanceof Wt){this.fail(Ae(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
14
|
+
${o?.stack??fe(o)}`),this.send(V(Ae(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(V(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:E("event"),session:Gt(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Rn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(i=>i.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:E("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(V(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(V(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:E("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(V(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Yi.test(e.audio)){this.send(V(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Jt){this.send(V(Q("buffer_full",`uncommitted input audio exceeds the ${Jt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(V(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(V(Q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(Q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,An("session ended by client"))}catch{}});return}case"ping":return;default:this.send(V(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Wt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let i;if(o||this.turnStallMs<=0){o=!1;let s=n.next();s.catch(()=>{}),i=r?await Promise.race([s,r]):await s}else{let s,a=new Promise((d,p)=>{s=setTimeout(()=>p(new Kt),this.turnStallMs)}),u=n.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(s))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(V(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?tt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?tt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new T("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(V(Q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let s=()=>{},a=new Promise((R,x)=>{s=()=>x(new Be)});this.turnCancelled=a,this.wakeTurnCancelled=()=>s(),a.catch(()=>{});let u=()=>{},l=new Promise((R,x)=>{u=()=>x(new Be)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=E("req"),c=`resp_${p}`;this.activeResponseId=c,this.activeRequestId=p;let f=this.binding.composite===!0,m=f?0:this.items.length,S=f?null:Vt(this.items),k=xn(typeof n.instructions=="string"?n.instructions:this.config.instructions),_=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=n.tools!==void 0?n.tools:this.config.tools,L=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,C={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...L!==void 0?{tool_choice:L}:{}};if(!(f&&!this.ensureVoice())){for(let{audio:R,captureWallMs:x}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R,x);this.inFlight=(async()=>{let R=[],x=$=>{this.responseFlushed?this.send($):R.push($)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(c,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(c,"in_progress")});for(let $ of R)this.send($);R.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,A=()=>{this.closeOpenItems(c,h,m),I(),this.send({type:"response.done",event_id:E("event"),response:this.responseObject(c,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(f){if(this.pendingTranscriptItemId!==null&&(await new Promise(P=>{this.pendingTranscriptSettled=P}),this.cancelled||this.closed))throw new Be;m=this.items.length,S=Vt(this.items)}let{input:$,sawAudioOnlyItem:j}=S??{input:[],sawAudioOnlyItem:!1},H={...C,input:$,...f?this.compositeTurnAsk(n):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let M;try{let P=this.upstreamStream(H,p);Promise.resolve(P).catch(U=>{U instanceof X&&this.failSessionGone(U)}),M=await Promise.race([P,l])}catch(P){if(P instanceof Be){this.deadlineFired&&!this.closed&&A();return}this.upstreamTurnFault(P,c);return}I();try{for await(let P of this.stallBoundedTurn(M)){if(this.cancelled)break;let U=P;if(U.type==="error"){let B=this.upstreamErrorBody(U);h.contentFlowed?this.send(V(B)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(c,B)});return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(c,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&x({type:"response.output_text.delta",event_id:E("event"),item_id:`${c}_msg_0`,response_id:c,output_index:0,content_index:0,delta:U.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,x({type:"response.output_audio_transcript.delta",event_id:E("event"),item_id:`${c}_msg_0`,response_id:c,output_index:0,content_index:0,delta:U.delta})),h.messageText+=U.delta;continue}if(U.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let B=typeof U.delta=="string"?U.delta:"",z=typeof U.call_id=="string"&&U.call_id.length>0?U.call_id:`${c}_fc_${h.nextOutputIndex}`,O=h.tools.get(z);if(!O){let F=typeof U.name=="string"&&U.name.length>0?U.name:void 0;O={outputIndex:h.nextOutputIndex++,name:F,args:""},h.tools.set(z,O);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:F??"",arguments:"",status:"in_progress"};x({type:"response.output_item.added",event_id:E("event"),response_id:c,output_index:O.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof U.name=="string"&&U.name.length>0&&(O.name=U.name),O.args+=B,x({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:z,response_id:c,output_index:O.outputIndex,call_id:z,name:O.name??"",delta:B});continue}if(U.type==="response.completed"){v=U.response??null;continue}}}catch(P){if(this.closed)return;if(P instanceof Be){this.deadlineFired&&A();return}if(this.cancelled)return;if(P instanceof Kt)this.operatorLog(`[realtime] turn ${c} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(P,c);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&A();return}this.closeOpenItems(c,h,m),I(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(c,m,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Qi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:E("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:E("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:E("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Se(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??_e(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Ae(fn,"the organization is out of credits \u2014 top up to continue"),fn))}failSessionGone(e){if(e instanceof X&&e.reason===pn){this.failInsufficientCredits();return}let n=e instanceof Error&&ye(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${fe(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Ae("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof $r.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ae(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:E("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Sn&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(V(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>mn){this.send(V(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${mn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(V(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(V(Ae(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>bn){this.ws.close(Vi,An("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=le(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${fe(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Wi,An(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Cr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Cr(this.id,e)}},En=[];function Cr(t,e){En.push({id:t,reason:e}),En.length>256&&En.shift()}var _t="/v1/realtime",Mr="urun.admission",Lr=t=>t.slice(0,120);function Zi(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
15
15
|
Connection: close\r
|
|
16
16
|
Content-Type: text/plain\r
|
|
17
17
|
\r
|
|
18
18
|
${Lr(n)}\r
|
|
19
19
|
`),t.destroy()}function es(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
20
20
|
`}function ts(t){Fe(process.stdout,t)}function ns(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function In(t){return t.audioSession?.audio.sessionId??void 0}function wt(t,e){let n=new yt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==_t)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=E("rtup"),l=ns(o),d=h=>{(e.log??ts)(es(h))};d({stage:"accept",conn:u,model:l}),i.resume();let p=new AbortController,c=null,f=h=>{c??=h,p.abort(new Error(c))},m=()=>f("client socket closed"),S=()=>f("client socket closed (half-close)"),k=h=>f(`client socket error: ${h.message}`);i.once("close",m),i.once("end",S),i.once("error",k);let _=()=>{i.removeListener("close",m),i.removeListener("end",S),i.removeListener("error",k)},y=h=>{d({stage:"close",conn:u,model:l,...h})},g=null,w=!1,L=null,C=h=>JSON.stringify({type:Mr,event_id:E("event"),...h}),R=h=>{if(g!==null){g.readyState===yt.WebSocket.OPEN&&g.send(C(h));return}w||(w=!0,n.handleUpgrade(o,i,s,v=>{g=v,L=[],v.on("message",A=>{L?.push(String(A))}),d({stage:"waiting",conn:u,model:l,status:h.status}),v.send(C(h))}))},x=h=>{let v=h,A=v.session!=null&&typeof v.session.sendResponseCreate=="function",$=v.clients!=null&&typeof v.clients.createResponse=="function";if(!A&&!$)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((j,H)=>{let M=(P,U)=>{try{let B=Date.now();new qe({ws:P,binding:h,operatorLog:e.operatorLog,...U.length>0?{replayFrames:U}:{},onClosed:(z,O)=>{y({while:"live",reason:O.reason});try{e.onSessionEnded?.({req:o,binding:h,connected_ms:Math.max(0,Date.now()-B),reason:O.reason})}catch(F){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${F instanceof Error?F.message:String(F)}
|
|
21
|
-
`)}}}),d({stage:"admit",conn:u,model:l,...In(h)===void 0?{}:{session:In(h)}}),j()}catch(B){H(B)}};if(g!==null){let P=L??[];L=null,M(g,P);return}n.handleUpgrade(o,i,s,P=>M(P,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal,R).then(async h=>{if(p.signal.aborted){_();let v=In(h);try{await h.release?.()}catch(A){y({while:"queued",...v===void 0?{}:{session:v},reason:c??"client socket closed",release_failed:A instanceof Error?A.message:String(A)});return}y({while:"queued",...v===void 0?{}:{session:v},reason:c??"client socket closed",released:!0}),i.destroy();return}_(),await x(h)}).catch(h=>{let v=h instanceof Tn.SessionFailedError?jt(h):null,A=null;if(h!==null&&typeof h=="object"&&"status"in h){let M=h.status;typeof M=="number"&&(A=M)}let $=A??v?.status??502,j=h instanceof Error?h.message:String(h),H=A!==null?j:v!==null?ht(v,h instanceof Tn.SessionFailedError&&h.status.sessionId?`session ${h.status.sessionId}`:void 0):le(h).message;if(y({while:"queued",...p.signal.aborted?{reason:c??"client socket closed"}:{reason:j,status:$}}),g!==null&&!p.signal.aborted){let M=JSON.stringify({type:Mr,event_id:E("event"),status:$<500?"rejected":"failed",reason:H});g.readyState===yt.WebSocket.OPEN&&g.send(M),g.close(1011,Lr(H));return}i.destroyed||Zi(i,$,H)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var Br=require("crypto");var Pn="x-urun-profile",vt="voice";var ae=class extends Error{status=400},rs=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,os=/\s/;function is(t){return rs.test(t)}function On(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ae(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Nr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ae(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ae(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ae(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Ur(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ae(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new ae(`the ${Pn} header is empty \u2014 the only profile this lane accepts is "${vt}" (omit the header for the ordinary lane)`);if(l!==vt)throw new ae(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${vt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==vt)throw new ae(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${vt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ae("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ae("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Nr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Nr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:On(u,"sentence_flush",!0),includeReasoning:On(u,"include_reasoning",!1),metadata:On(u,"metadata",!1)}}var nt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&is(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(os.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ee=(t,e)=>Object.assign(new Error(e),{status:t}),us='"transcription" (a transcription session), or no intent at all (the realtime voice session)',$n=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Cn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof G?Ee(404,n.message):n}};async function Dr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ee(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${us}`);if(o==="transcription")throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let c;try{c=await t.supportsTranscription(n.stt)}catch(f){throw f instanceof G?Ee(404,f.message):f}if(!c)throw Ee(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let c;try{c=await t.transcriptStreamFor(n.stt)}catch(f){throw f instanceof G?Ee(404,f.message):f}if(c!=="stt")throw Ee(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Cn(t,n.stt),s=await Cn(t,e),a=await Cn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,p={clients:{createResponse:c=>{let f=new AbortController;return d=f,ls({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},c,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let c=d;d=null,c?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:c=>{u.appendInputAudio(c)},onOutputAudio:c=>l.onOutputAudio(c),sessionId:l.sessionId}},turns:async function*(c){try{yield*t.openTurnsOn(i,c)}catch(f){throw f instanceof X?$n("stt",n.stt,f):f}},composite:!0};return e!==void 0&&(p.model=e),p}function Fr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var bt=class extends Error{};async function*ls(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,p=e.output_modalities,c=!Array.isArray(p)||p.includes("audio"),f=!1,m=null,S=null,k=[],_=null,y=new Promise((v,A)=>{n&&n.addEventListener("abort",()=>A(new bt),{once:!0})}),g=()=>f||n?.aborted===!0,w=async v=>{if(g())return;let A;try{A=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:v}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(j){throw j instanceof X?$n("tts",u.tts,j):j}let $=A[Symbol.asyncIterator]();S=$;try{for(;;){let j=$.next(),H;try{H=await Promise.race([j,y])}catch(P){if(j.catch(()=>{}),P instanceof bt)return;throw P}if(H.done)return;let M=H.value;if(M.type==="error"){let P=M.error&&typeof M.error.message=="string"?M.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${P}`)}if(M.type==="response.completed")return}}finally{S===$&&(S=null)}},L=async()=>{for(;k.length>0&&!g();){let v=k.shift();await w(v)}},C=v=>{if(v===""||g()||(k.push(v),_!==null))return;let A=L();_=A,A.then(()=>{_===A&&(_=null)},$=>{_===A&&(_=null),m??=$})},R=()=>{f=!0,k.length=0;let v=S;if(S=null,v){let A=v.return?.();A&&A.catch(()=>{})}},x=async()=>{for(;k.length>0||_!==null;){let v=_;if(v===null){await w(k.shift());continue}await v}},I=c?new nt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},v=>C(v)):null,h=null;try{let v;try{v=await o.createResponseOn(i,d)}catch($){throw $ instanceof X?$n("chat",a,$):$}let A=v[Symbol.asyncIterator]();try{for(;;){let $=A.next(),j;try{j=await Promise.race([$,y])}catch(P){if($.catch(()=>{}),P instanceof bt)break;throw P}if(j.done)break;let H=j.value;if(g())return;let M=H;if(M.type==="error"){yield H;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield H,I?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){I?.flush(),yield H;continue}if(M.type==="response.completed"){h=H.response;continue}}}finally{Promise.resolve(A.return?.()).catch(()=>{})}I?.flush(),I?.dispose(),c&&await x(),h!==null&&(yield{type:"response.completed",response:h})}finally{I?.dispose(),R();try{if(m instanceof X)throw m}finally{r?.()}}}var de=(t,e)=>Object.assign(new Error(e),{status:t});function Mn(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ds(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var cs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Ln(t,e,n,r,o){if(!t.supportsAudio)throw de(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await t.supportsAudio(e)}catch(f){throw f instanceof G?de(404,f.message):f}if(!i){let f=null;if(t.realtimeCompanionsFor)try{f=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof G?de(404,m.message):m}if(f!==null)return await Dr(t,e,f,n,r);throw de(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw de(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(f){throw f instanceof G?de(404,f.message):f}if(s&&!t.openTurnsOn)throw de(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(e)}catch(m){throw m instanceof G?de(404,m.message):m}if(f!=="stt")throw de(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw de(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${cs}`);if(r==="transcription"&&!s)throw de(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(f){throw f instanceof ue?de(503,f.message):f}let u=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Br.randomUUID)()}`,p={audio:await t.openAudioOn(a,n,l,o).catch(f=>{throw t.releaseSessionHandle?.(a),f})},c={clients:{createResponse:async f=>await t.createResponseOn(a,f,l)},voice:i,audioSession:p};return t.openVideoOn&&(c.video=()=>t.openVideoOn(a,n)),s&&(c.turns=f=>t.openTurnsOn(a,f)),r==="transcription"&&(c.intent="transcription"),t.releaseSessionHandle&&(c.release=()=>t.releaseSessionHandle(a)),t.endDedicatedSession&&(c.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(c.onSessionEnd=f=>t.onSessionEnd(a,f)),e!==void 0&&(c.model=e),u!==null&&(c.catalog=u),c}function zt(t,e,n){let r=Fr(t,n);return{resolve:async(o,i,s)=>{if(e!==void 0){let a=o.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw de(401,"invalid local proxy api key")}return Ln(r,Mn(o),i,ds(o),s)}}}var N=class extends Error{},me=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function rt(t,e){if(t!=null)throw new N(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Nn(t){let e=Yt(t);return e!==null&&e<=1?e:null}function qr(t,e){if(!ne(t))throw new N("decisions requires a JSON object body");rt(t.prompt_cache_key,"prompt_cache_key"),rt(t.prompt_cache_options,"prompt_cache_options"),rt(t.safety_identifier,"safety_identifier");let n=[],r=ps(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new N("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:p}=gs(o[l],l,o.length,n);if(a.has(p.key))throw new N(`duplicate question name "${p.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(p.key),i[p.key]=d,s.push(p)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function ps(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new N("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ms(o,r,e);return fs(r)}function fs(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
21
|
+
`)}}}),d({stage:"admit",conn:u,model:l,...In(h)===void 0?{}:{session:In(h)}}),j()}catch(B){H(B)}};if(g!==null){let P=L??[];L=null,M(g,P);return}n.handleUpgrade(o,i,s,P=>M(P,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal,R).then(async h=>{if(p.signal.aborted){_();let v=In(h);try{await h.release?.()}catch(A){y({while:"queued",...v===void 0?{}:{session:v},reason:c??"client socket closed",release_failed:A instanceof Error?A.message:String(A)});return}y({while:"queued",...v===void 0?{}:{session:v},reason:c??"client socket closed",released:!0}),i.destroy();return}_(),await x(h)}).catch(h=>{let v=h instanceof Tn.SessionFailedError?jt(h):null,A=null;if(h!==null&&typeof h=="object"&&"status"in h){let M=h.status;typeof M=="number"&&(A=M)}let $=A??v?.status??502,j=h instanceof Error?h.message:String(h),H=A!==null?j:v!==null?ht(v,h instanceof Tn.SessionFailedError&&h.status.sessionId?`session ${h.status.sessionId}`:void 0):le(h).message;if(y({while:"queued",...p.signal.aborted?{reason:c??"client socket closed"}:{reason:j,status:$}}),g!==null&&!p.signal.aborted){let M=JSON.stringify({type:Mr,event_id:E("event"),status:$<500?"rejected":"failed",reason:H});g.readyState===yt.WebSocket.OPEN&&g.send(M),g.close(1011,Lr(H));return}i.destroyed||Zi(i,$,H)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var Br=require("crypto");var Pn="x-urun-profile",vt="voice";var ae=class extends Error{status=400},rs=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,os=/\s/;function is(t){return rs.test(t)}function On(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ae(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Nr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ae(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ae(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ae(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Ur(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ae(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new ae(`the ${Pn} header is empty \u2014 the only profile this lane accepts is "${vt}" (omit the header for the ordinary lane)`);if(l!==vt)throw new ae(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${vt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==vt)throw new ae(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${vt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ae("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ae("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Nr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Nr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:On(u,"sentence_flush",!0),includeReasoning:On(u,"include_reasoning",!1),metadata:On(u,"metadata",!1)}}var nt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&is(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(os.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ee=(t,e)=>Object.assign(new Error(e),{status:t}),us='"transcription" (a transcription session), or no intent at all (the realtime voice session)',$n=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Cn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof G?Ee(404,n.message):n}};async function Dr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ee(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${us}`);if(o==="transcription")throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let c;try{c=await t.supportsTranscription(n.stt)}catch(f){throw f instanceof G?Ee(404,f.message):f}if(!c)throw Ee(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let c;try{c=await t.transcriptStreamFor(n.stt)}catch(f){throw f instanceof G?Ee(404,f.message):f}if(c!=="stt")throw Ee(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Cn(t,n.stt),s=await Cn(t,e),a=await Cn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,p={clients:{createResponse:c=>{let f=new AbortController;return d=f,ls({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},c,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let c=d;d=null,c?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:c=>{u.appendInputAudio(c)},onOutputAudio:c=>l.onOutputAudio(c),sessionId:l.sessionId}},turns:async function*(c){try{yield*t.openTurnsOn(i,c)}catch(f){throw f instanceof X?$n("stt",n.stt,f):f}},composite:!0};return e!==void 0&&(p.model=e),p}function Fr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var bt=class extends Error{};async function*ls(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,p=e.output_modalities,c=!Array.isArray(p)||p.includes("audio"),f=!1,m=null,S=null,k=[],_=null,y=new Promise((v,A)=>{n&&n.addEventListener("abort",()=>A(new bt),{once:!0})}),g=()=>f||n?.aborted===!0,w=async v=>{if(g())return;let A;try{A=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:v}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(j){throw j instanceof X?$n("tts",u.tts,j):j}let $=A[Symbol.asyncIterator]();S=$;try{for(;;){let j=$.next(),H;try{H=await Promise.race([j,y])}catch(P){if(j.catch(()=>{}),P instanceof bt)return;throw P}if(H.done)return;let M=H.value;if(M.type==="error"){let P=M.error&&typeof M.error.message=="string"?M.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${P}`)}if(M.type==="response.completed")return}}finally{S===$&&(S=null)}},L=async()=>{for(;k.length>0&&!g();){let v=k.shift();await w(v)}},C=v=>{if(v===""||g()||(k.push(v),_!==null))return;let A=L();_=A,A.then(()=>{_===A&&(_=null)},$=>{_===A&&(_=null),m??=$})},R=()=>{f=!0,k.length=0;let v=S;if(S=null,v){let A=v.return?.();A&&A.catch(()=>{})}},x=async()=>{for(;k.length>0||_!==null;){let v=_;if(v===null){await w(k.shift());continue}await v}},I=c?new nt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},v=>C(v)):null,h=null;try{let v;try{v=await o.createResponseOn(i,d)}catch($){throw $ instanceof X?$n("chat",a,$):$}let A=v[Symbol.asyncIterator]();try{for(;;){let $=A.next(),j;try{j=await Promise.race([$,y])}catch(P){if($.catch(()=>{}),P instanceof bt)break;throw P}if(j.done)break;let H=j.value;if(g())return;let M=H;if(M.type==="error"){yield H;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield H,I?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){I?.flush(),yield H;continue}if(M.type==="response.completed"){h=H.response;continue}}}finally{Promise.resolve(A.return?.()).catch(()=>{})}I?.flush(),I?.dispose(),c&&await x(),h!==null&&(yield{type:"response.completed",response:h})}finally{I?.dispose(),R();try{if(m instanceof X)throw m}finally{r?.()}}}var de=(t,e)=>Object.assign(new Error(e),{status:t});function Mn(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ds(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var cs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Ln(t,e,n,r,o){if(!t.supportsAudio)throw de(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await t.supportsAudio(e)}catch(f){throw f instanceof G?de(404,f.message):f}if(!i){let f=null;if(t.realtimeCompanionsFor)try{f=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof G?de(404,m.message):m}if(f!==null)return await Dr(t,e,f,n,r);throw de(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw de(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(f){throw f instanceof G?de(404,f.message):f}if(s&&!t.openTurnsOn)throw de(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(e)}catch(m){throw m instanceof G?de(404,m.message):m}if(f!=="stt")throw de(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw de(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${cs}`);if(r==="transcription"&&!s)throw de(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(f){throw f instanceof ue?de(503,f.message):f}let u=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Br.randomUUID)()}`,p={audio:await t.openAudioOn(a,n,l,o).catch(f=>{throw t.releaseSessionHandle?.(a),f})},c={clients:{createResponse:async f=>await t.createResponseOn(a,f,l)},voice:i,audioSession:p};return t.openVideoOn&&(c.video=()=>t.openVideoOn(a,n)),s&&(c.turns=f=>t.openTurnsOn(a,f)),r==="transcription"&&(c.intent="transcription"),t.releaseSessionHandle&&(c.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(c.presence={touch:f=>t.touchSessionPresence?.(a,f),detach:f=>t.detachSessionPresence?.(a,f)}),t.endDedicatedSession&&(c.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(c.onSessionEnd=f=>t.onSessionEnd(a,f)),e!==void 0&&(c.model=e),u!==null&&(c.catalog=u),c}function zt(t,e,n){let r=Fr(t,n);return{resolve:async(o,i,s)=>{if(e!==void 0){let a=o.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw de(401,"invalid local proxy api key")}return Ln(r,Mn(o),i,ds(o),s)}}}var N=class extends Error{},me=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function rt(t,e){if(t!=null)throw new N(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Nn(t){let e=Yt(t);return e!==null&&e<=1?e:null}function qr(t,e){if(!ne(t))throw new N("decisions requires a JSON object body");rt(t.prompt_cache_key,"prompt_cache_key"),rt(t.prompt_cache_options,"prompt_cache_options"),rt(t.safety_identifier,"safety_identifier");let n=[],r=ps(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new N("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:p}=gs(o[l],l,o.length,n);if(a.has(p.key))throw new N(`duplicate question name "${p.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(p.key),i[p.key]=d,s.push(p)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function ps(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new N("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ms(o,r,e);return fs(r)}function fs(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
22
22
|
|
|
23
23
|
`)}function ms(t,e,n){if(!ne(t))throw new N("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){hs(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=t.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){jr(i,e,n,void 0,!1);return}throw new N(`${o} output must be a string or an array of parts`)}default:throw new N(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function hs(t,e,n,r){e==="assistant"&&rt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new N(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of o){if(!ne(i))throw new N("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")n.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")n.push({role:e,text:`[refusal] ${i.refusal}`});else throw new N(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}jr(o,n,r,e)}function jr(t,e,n,r,o=!0){for(let i of t){if(!ne(i))throw new N("decisions content parts must be JSON objects");switch(rt(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new N("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!o)throw new N("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new N("input_json data must be an object or an array of objects");e.push({role:r,json:s});break}case"input_image":{n.push(Hr(i));break}default:throw new N(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Hr(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new N("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new N("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new N("input_image data URL carries no image data");let i=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(i?o.length%4!==0:o.length%4===1))throw new N("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let s=t.detail;if(s!=null&&s!=="low"&&s!=="high"&&s!=="auto"&&s!=="original")throw new N("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(s==="low"||s==="high")&&(a.detail=s),a}function gs(t,e,n,r){if(!ne(t))throw new N(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new N(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let i=t.name;if(i!==void 0&&typeof i!="string")throw new N(`questions[${e}] name must be a string`);let s=i??null,a=s??`q${e}`,u=ys(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:s}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new N(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],p=new Set,c=[];for(let S of l){if(!ne(S))throw new N(`questions[${e}] choices must be JSON objects`);let k=S.value;if(typeof k!="string"&&typeof k!="boolean")throw new N(`questions[${e}] choice value must be a string or boolean`);let _=String(k);if(p.has(_))throw new N(`questions[${e}] has duplicate choice value ${JSON.stringify(_)} (choices must be unique)`);p.add(_);let y=S.description;if(y!==void 0&&typeof y!="string")throw new N(`questions[${e}] choice description must be a string`);d.push(k),c.push(y)}let f=l.map((S,k)=>({name:String(d[k]),description:c[k]??String(d[k])}));return{entry:{kind:"choice",prompt:u,options:f},spec:{type:o,key:a,name:s,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new N(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],p=[];for(let f of l){if(!ne(f)||typeof f.label!="string")throw new N(`questions[${e}] score levels must carry a string label`);if(d.includes(f.label))throw new N(`questions[${e}] has duplicate level label ${JSON.stringify(f.label)}`);d.push(f.label);let m=f.description;if(m!==void 0&&typeof m!="string")throw new N(`questions[${e}] score level description must be a string`);let S=m!==void 0?`${f.label}: ${m}`:f.label;if(p.includes(S))throw new N(`questions[${e}] has duplicate score criterion ${JSON.stringify(S)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);p.push(S)}return{entry:{kind:"score",prompt:u,criteria:p},spec:{type:o,key:a,name:s,levelLabels:d}}}}}function ys(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new N(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let i of t){if(!ne(i))throw new N(`questions[${e}] instruction parts must be JSON objects`);switch(rt(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new N(`questions[${e}] input_text requires a string text`);o.push(i.text);break}case"input_image":{if(n>1)throw new N(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Hr(i));break}case"input_json":{let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new N(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(s));break}default:throw new N(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return o.join(`
|
|
24
24
|
|
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
-
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-
|
|
3
|
-
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-
|
|
2
|
+
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-D7icObdD.cjs';
|
|
3
|
+
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-D7icObdD.cjs';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-C6MpaZS-.cjs';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.cjs';
|
|
@@ -789,7 +789,7 @@ declare function realtimeModelOf(req: IncomingMessage): string | undefined;
|
|
|
789
789
|
* and the bridge opens — a refused upgrade admits nothing. On an stt row
|
|
790
790
|
* the intent is recorded on the binding (a transcription session).
|
|
791
791
|
*/
|
|
792
|
-
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'endDedicatedSession' | 'onSessionEnd' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
792
|
+
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'endDedicatedSession' | 'onSessionEnd' | 'realtimeBillingIdentityFor' | 'touchSessionPresence' | 'detachSessionPresence'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
793
793
|
/**
|
|
794
794
|
* The LOCAL lane resolver: fixed pooled clients, optional fixed apiKey (the
|
|
795
795
|
* same shared-secret rule the local Gemini Live lane applies — a mismatched
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server, IncomingMessage } from 'node:http';
|
|
2
|
-
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-
|
|
3
|
-
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-
|
|
2
|
+
import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-DyRe-KRu.js';
|
|
3
|
+
export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-DyRe-KRu.js';
|
|
4
4
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CaOqL-V8.js';
|
|
5
5
|
import { WebSocket } from 'ws';
|
|
6
6
|
import '../models-D7F0bLJ3.js';
|
|
@@ -210,7 +210,7 @@ declare class OpenAIRealtimeConnection<S = unknown> {
|
|
|
210
210
|
|
|
211
211
|
declare function realtimeModelOf(req: IncomingMessage): string | undefined;
|
|
212
212
|
|
|
213
|
-
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'endDedicatedSession' | 'onSessionEnd' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
213
|
+
declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'endDedicatedSession' | 'onSessionEnd' | 'realtimeBillingIdentityFor' | 'touchSessionPresence' | 'detachSessionPresence'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
|
214
214
|
|
|
215
215
|
declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
|
|
216
216
|
resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-
|
|
1
|
+
import{F as I,a as n,b as p,c as m,k as l,l as a,m as x,o as s,r as O,s as f}from"../chunk-V6WQRPUO.js";import{a as o,h as t}from"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-6WTMEJZS.js";import{i as r,j as i}from"../chunk-C452ZIU5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.50",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.6.
|
|
73
|
+
"@urun-sh/core": "^0.6.50"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"@prometheus-io/client": "^0.16.1",
|