@urun-sh/openai 0.6.44 → 0.6.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{chunk-BA3NCMS5.js → chunk-2AFSBZLN.js} +1 -1
  2. package/dist/{chunk-J3KCHTSA.js → chunk-CUO2JOW4.js} +5 -5
  3. package/dist/{chunk-Y774TOE7.js → chunk-MJGUEL2U.js} +1 -1
  4. package/dist/chunk-NCKEKCTI.js +4 -0
  5. package/dist/{chunk-G6AFKOVS.js → chunk-PXV7QBSD.js} +1 -1
  6. package/dist/{chunk-HB5KNEY5.js → chunk-Q3AIBMET.js} +1 -1
  7. package/dist/chunk-U6TUJPC3.js +66 -0
  8. package/dist/{chunk-FNAZ2XBE.js → chunk-UOQP3DBT.js} +6 -6
  9. package/dist/{chunk-MJSK6W3W.js → chunk-WWFK27D2.js} +1 -1
  10. package/dist/{composite-DNNAm0PY.d.ts → composite-D0ivH65M.d.ts} +14 -0
  11. package/dist/{composite-DM2sT1Sp.d.cts → composite-QilJ-Faj.d.cts} +57 -0
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +11 -0
  14. package/dist/gemini-live.d.ts +2 -0
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +47 -47
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +42 -42
  19. package/dist/hosted/index.d.cts +1 -1
  20. package/dist/hosted/index.d.ts +1 -1
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/pi-extension/index.cjs +7 -7
  25. package/dist/pi-extension/index.js +1 -1
  26. package/dist/pi-extension/standalone.cjs +54 -54
  27. package/dist/pooler/bin.cjs +5 -5
  28. package/dist/pooler/bin.js +1 -1
  29. package/dist/proxy/cli.cjs +52 -52
  30. package/dist/proxy/cli.js +1 -1
  31. package/dist/proxy/index.cjs +32 -32
  32. package/dist/proxy/index.d.cts +34 -3
  33. package/dist/proxy/index.d.ts +10 -3
  34. package/dist/proxy/index.js +1 -1
  35. package/package.json +2 -2
  36. package/dist/chunk-DMRZZTYI.js +0 -4
  37. package/dist/chunk-VQSCBUKT.js +0 -66
@@ -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-DM2sT1Sp.cjs';
3
- export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-DM2sT1Sp.cjs';
2
+ import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-QilJ-Faj.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-QilJ-Faj.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';
@@ -319,6 +319,19 @@ declare class OpenAIRealtimeConnection<S = unknown> {
319
319
  private frozenAudio;
320
320
  private inFlight;
321
321
  private activeResponseId;
322
+ /** The active turn's upstream request id (`req_…`) — the engine tombstone key. */
323
+ private activeRequestId;
324
+ /**
325
+ * THE PER-TURN CANCEL GATE (the sense wedge, prod 2026-11-15): resolved
326
+ * by `response.cancel` so the turn's stream waits stop waiting on the
327
+ * upstream's pleasure. A turn whose source never yields again (the
328
+ * engine's reply parked behind a media backlog, or lost) must still
329
+ * settle the moment the client cancels — `response.cancelled` out, the
330
+ * slot free for the next turn on the SAME connection. Fresh per turn
331
+ * (a stale resolved gate would end every later turn instantly).
332
+ */
333
+ private turnCancelled;
334
+ private wakeTurnCancelled;
322
335
  /** Output events already flowed for the active response (post-flush faults → error event, pre-flush → response.failed). */
323
336
  private responseFlushed;
324
337
  private cancelled;
@@ -580,6 +593,19 @@ declare class OpenAIRealtimeConnection<S = unknown> {
580
593
  * the turn is never retried on another session behind the bridge's back —
581
594
  * the only honest moves are to say why and close.
582
595
  */
596
+ /**
597
+ * THE CREDITS CUTOFF TERMINAL CLOSE (2026-11): ONE `error` event naming
598
+ * `insufficient_credits` with the authored caller line, then the 1011
599
+ * close carrying the SAME code as its reason — the wire contract
600
+ * (error-event + close + teardown, the established session-gone shape).
601
+ * The sense SDKs treat this code as TERMINAL: no reconnect, no re-dial —
602
+ * the org is drained, and the redial storm against a drained org (the
603
+ * generic `session_gone` death the DB cut used to surface) is the defect
604
+ * this replaces. No reacquire happens on this connection: the binding's
605
+ * pinned session IS the one that was parked, and nothing re-picks a lane
606
+ * behind the bridge's back.
607
+ */
608
+ private failInsufficientCredits;
583
609
  private failSessionGone;
584
610
  /**
585
611
  * Classify ONE upstream turn failure (the dial throwing, or the stream
@@ -591,6 +617,11 @@ declare class OpenAIRealtimeConnection<S = unknown> {
591
617
  * LOUDLY, pre- or post-content alike — and post-CANCEL alike: the
592
618
  * bridge is orphaned either way, and a cancelled turn must never mute
593
619
  * a dead pinned session (round-1 review, CodeRabbit + Greptile);
620
+ * the ONE special case is the CREDITS CAUSE (the structured park
621
+ * reason `credits_exhausted`, threaded from core Session.onPhase —
622
+ * the platform's own word): the terminal {@link failInsufficientCredits}
623
+ * close, so the client never sees a generic death it would redial
624
+ * into;
594
625
  * - a CANCELLED turn suppresses every OTHER late fault (round-1 review):
595
626
  * `response.cancel` does not abort a pending dial, and the dial's
596
627
  * rejection settles AFTER `cancelled` was set — the lane's pre-#511
@@ -727,7 +758,7 @@ declare function realtimeModelOf(req: IncomingMessage): string | undefined;
727
758
  * and the bridge opens — a refused upgrade admits nothing. On an stt row
728
759
  * the intent is recorded on the binding (a transcription session).
729
760
  */
730
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
761
+ 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>>;
731
762
  /**
732
763
  * The LOCAL lane resolver: fixed pooled clients, optional fixed apiKey (the
733
764
  * same shared-secret rule the local Gemini Live lane applies — a mismatched
@@ -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-DNNAm0PY.js';
3
- export { D as DialObserver, a as DialReport, O as OPENAI_REALTIME_PATH, f as OpenAIRealtimeOptions, g as OpenAIRealtimeResolver, i as ProxyIdentity, j as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError, o as attachOpenAIRealtime } from '../composite-DNNAm0PY.js';
2
+ import { h as ProxyHandlerOptions, P as ProxyClients, l as RealtimeCompanionsFor, k as RealtimeBinding, R as RealtimeAdmissionNotifier } from '../composite-D0ivH65M.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-D0ivH65M.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';
@@ -79,6 +79,11 @@ declare class OpenAIRealtimeConnection<S = unknown> {
79
79
  private inFlight;
80
80
  private activeResponseId;
81
81
 
82
+ private activeRequestId;
83
+
84
+ private turnCancelled;
85
+ private wakeTurnCancelled;
86
+
82
87
  private responseFlushed;
83
88
  private cancelled;
84
89
 
@@ -172,6 +177,8 @@ declare class OpenAIRealtimeConnection<S = unknown> {
172
177
  private doneResponse;
173
178
  private upstreamErrorBody;
174
179
 
180
+
181
+ private failInsufficientCredits;
175
182
  private failSessionGone;
176
183
 
177
184
  private upstreamTurnFault;
@@ -192,7 +199,7 @@ declare class OpenAIRealtimeConnection<S = unknown> {
192
199
 
193
200
  declare function realtimeModelOf(req: IncomingMessage): string | undefined;
194
201
 
195
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'openVideoOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle' | 'realtimeBillingIdentityFor'>>, model: string | undefined, signal?: AbortSignal, intent?: string, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
202
+ 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>>;
196
203
 
197
204
  declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
198
205
  resolve(req: IncomingMessage, signal?: AbortSignal, onAdmission?: RealtimeAdmissionNotifier): Promise<RealtimeBinding<ProxyClients>>;
@@ -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-VQSCBUKT.js";import{a as o,h as t}from"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-BA3NCMS5.js";import{i as r,j as i}from"../chunk-J3KCHTSA.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
1
+ 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-U6TUJPC3.js";import{a as o,h as t}from"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-2AFSBZLN.js";import{i as r,j as i}from"../chunk-CUO2JOW4.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.44",
3
+ "version": "0.6.46",
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.43"
73
+ "@urun-sh/core": "^0.6.46"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",
@@ -1,4 +0,0 @@
1
- import{a as ne}from"./chunk-CAR4AEQJ.js";import{e as ue,f as B,g as pe,h as fe}from"./chunk-VQSCBUKT.js";import{c as Z,f as $,g as ee,p as oe}from"./chunk-64VO62LW.js";import{a as me,b as W}from"./chunk-MJSK6W3W.js";import{c as le}from"./chunk-BA3NCMS5.js";import{a as j}from"./chunk-HB5KNEY5.js";import{b as Y,d as U}from"./chunk-G6AFKOVS.js";import{b as te,c as se,d as re,g as ie,j as T,k as V,l as R,m as ae,p as H,q as I,r as ce,s as de}from"./chunk-J3KCHTSA.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as He,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as Be,SessionFailedError as K}from"@urun-sh/core";v();import{SessionFailedError as Ie}from"@urun-sh/core";var G=2;function _e(e){let o=e?.type;return o==="response.created"||o==="response.in_progress"}function Le(e){let o=e?.type;return o==="response.completed"||o==="error"}function ge(e){return async function(t,i){let a=await e.sessionFor(t.model);return(async function*(){for(let l=1;l<=G;l++){let{app:g,entry:y,identity:h}=l===1?a:await e.sessionFor(t.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:h});let d=!1,p=!1;try{let f=await e.createStream(y,t);for await(let m of f){if(Le(m)&&(d=!0),_e(m)){if(l>1)continue}else p=!0;yield m}}catch(f){if(f instanceof Ie&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<G&&!p){await e.evict(g,y);continue}throw f}if(d)return;if(l<G&&!p){await e.evict(g,y);continue}return}})()}}import{randomUUID as ve}from"crypto";v();import{request as Te}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(t,i,a,c){super(a);this.status=t;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Fe=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let o=e.messages?.find(t=>t.role==="system"||t.role==="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content)},Ne=e=>{let o=e.messages?.find(t=>t.role!=="system"&&t.role!=="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let t=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(t===void 0)return;if(typeof t=="string")return t;if(t!==null&&typeof t=="object"&&"content"in t){let i=t.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(t)}},we=e=>new Promise((o,t)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>o(Buffer.concat(i).toString("utf8"))),e.on("error",t)}),Me=async e=>{let o="pooler_error",t=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await we(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(o=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(t=a.message)}}catch{}return new k(e.status,o,t,e.retryAfterSeconds)};async function De(e,o,t,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:t,streaming:a,payload:o,affinity:{systemPrompt:Fe(o),firstMessage:Ne(o)}});return new Promise((g,y)=>{let h=Te({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},d=>{let p=Number(d.headers["retry-after"]??"");g({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(p)?p:void 0,body:d})});h.on("error",d=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),h.end(l)})}var ye=e=>{if(!e.startsWith("data: "))return null;let o=e.slice(6).trim();if(o===""||o==="[DONE]")return null;let t;try{t=JSON.parse(o)}catch{return null}if(t===null||typeof t!="object")return null;let i=t;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*xe(e){let o="";for await(let i of e.body)for(o+=String(i);;){let a=o.indexOf(`
2
-
3
- `);if(a===-1)break;let c=o.slice(0,a);o=o.slice(a+2);let l=ye(c);l!==null&&(yield l)}let t=ye(o);t!==null&&(yield t)}async function on(e,o,t,i){let a=Y(o,t,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await De(e,a,t,c,o.stream===!0);if(l.status>=400)throw await Me(l);let g=o.stream===!0?U(t,xe(l)):await Ce(l,t);return(async function*(){yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}},yield*g})()}async function Ce(e,o){let t=await we(e.body),i=null;try{let c=JSON.parse(t);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return U(o,(async function*(){yield a})())}v();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Ue="audio";function Se(e){let o=e.streamEndpoint(Ue);return{sessionId:e.id,appendInputAudio(t,i){let a=Buffer.from(t,"base64");if(a.byteLength!==0){if(i===void 0){o.send(he(new Uint8Array(a)));return}o.send(he({pcm16:t,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}v();import{encodeStreamEnvelope as $e}from"@urun-sh/core";var je="rt-video-in";function Pe(e){let o=e.streamEndpoint(je);return{sendInputFrame:async t=>{o.send($e(t))}}}var We=0,Ge=4,Je=4;function Tn(e,o){let t=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let h=Number.parseInt(y,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):We;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=t("URUN_DECISION_POOL_MAX",Math.max(a,Ge));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:t("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||o||"proxy"}}function Rn(e){let o=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!o)return B;let t=Number.parseInt(o,10);if(!Number.isInteger(t)||t<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return t*1e3}function q(e,o,t,i){let a=e[t];if(typeof a!="function")throw new Error(`app "${o}" has no function "${t}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${o}" function "${t}" returned a session without end()`);return c}function Ae(e,o,t,i){let{baseUrl:a,orgId:c,auth:l}=e,g=o.fnName??e.fnName,y=e.sessionStartOptions?.(t),h=i||y||o.sharedApp?{...o.sharedApp?{sharedApp:!0}:{},...y,...i}:void 0,d=w=>({session:w,responses:new j(w),gone:me(w,t)});if(l.lane==="jwt"){let w=J(o.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return d(q(w,o.appSlug,g,h))}if(l.lane==="machine"||l.lane==="user"){let w=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:x}=l,_=(typeof e.subject=="function"?e.subject():e.subject)??ve(),L=J(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(w,{baseUrl:x,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:_,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(q(L,o.appSlug,g,h))}let{apiKey:p,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??ve(),S=J(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(p,{baseUrl:f,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:m,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(q(S,o.appSlug,g,h))}function ke(e){let o=e.session.id;if(typeof o!="string"||o.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return o}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let o=e.status.error?.httpStatus,t=e.status.error?.code;return o===410||o===409&&(t==="cancelled"||t==="expired")?!0:t==="client_ended"}var qe=new Set(["error","paused"]);function Fn(e){let{auth:o,catalog:t}=e,i=null,a=(l,g)=>{let y=Ae(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new de({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:o.lane==="api-key"?()=>ae({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,listCatalog:e.catalogRows??(t?()=>ne(t):null),listPrices:t?()=>re(t):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return te(l)}:o.lane==="api-key"?()=>se({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,sessionKey:ke});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},I({appSlug:e.defaultApp}))),c}function Nn(e,o){let t=e.decisionPool;if(!t)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=t.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=d=>{process.stderr.write(`[decision-pool] ${d}
4
- `)},y=(d,p)=>{let f=a.get(p);if(f)return f;let m=new ue({min:t.min,max:t.max,idleGraceMs:t.idleGraceMs,inFlightCap:t.inFlightCap,replicaId:i,openSlot:async S=>{let w=Ae(e,d,p,{concurrencyKey:S.concurrencyKey});return w.gone.onGone(()=>m.markSessionDead(w)),await D(w.session),g(`slot attached pool=${p} slot=${S.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async S=>{S.gone.dispose(),S.audioDispose?.(),await S.session.end()},onDetach:(S,w)=>g(`slot detached pool=${p} slot=${S.concurrencyKey} reason=${w}`),terminalOpenFailure:S=>S instanceof K&&X(S)});return c.set(p,{target:d,env:t}),a.set(p,m),m},h=async(d,p)=>{let f=c.get(p);if(f)try{let m=await o.poolTuningFor(d);y(d,p).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){g(`pool tuning refresh failed pool=${p} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let d={appSlug:e.defaultApp};await y(d,I(d)).boot()},async sessionFor(d){let p=await o.resolveTargetFor(d),f=I(p),m=y(p,f);await h(p,f);let S=await m.acquire({timeoutMs:m.requestWaitMs}),w=l.get(S.entry)??[];return w.push(S),l.set(S.entry,w),{app:f,entry:S.entry,identity:ce(p)}},async warmFor(d){let p=await o.resolveTargetFor(d);await y(p,I(p)).boot()},end(d){let p=l.get(d)?.shift();p&&(l.get(d)?.length===0&&l.delete(d),p.release())},evict(d){for(let p of a.values())p.evict(d)},markSessionDead(d){for(let p of a.values())p.markSessionDead(d)},reap(){for(let[d,{target:p}]of c)h(p,d).then(()=>{let f=a.get(d);f&&f.reap()})},async pingReady(d){for(let p of a.values())if(await p.pingReady(d))return!0;return!1},stats(){return[...a.entries()].map(([d,p])=>({poolKey:d,...p.stats()}))},async drain(d){await Promise.all([...a.values()].map(p=>p.drain({timeoutMs:d})))},async close(){await Promise.all([...a.values()].map(d=>d.close()))}}}function Ke(e){return Be(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:He:be}async function D(e,o){let t=e.whenLive;if(typeof t!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await t.call(e,{timeout:Ke(e.phase),signal:o})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Oe(e){let o=e.phase?.name;if(o==="live"||o==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function M(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Mn(e,o=ee,t,i,a=B,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,h=new WeakMap,d=new WeakMap,p=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},f="lane",m=n=>{let s=R(n);if(!c||!s||s.app!==f)return null;let r=c.entryFor(s.key);if(!r)throw new T(`the lane behind this handle (${s.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:s.key,entry:r}},S=async n=>m(n)?.entry??(await e.sessionForHandle(n)).entry,w=n=>{let s=l.get(n);if(!s){let r={waiting:0,gone:new AbortController};d.set(n,r),s=(async()=>{if(await D(n.session,r.gone.signal),r.gone.signal.aborted)throw M(r.gone.signal);d.get(n)===r&&d.delete(n);let u=await Z(n.session,await o());return Object.assign(u,{sessionId:n.session.id})})(),l.set(n,s),s.then(u=>{l.get(n)===s&&(n.audioDispose=()=>u.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{d.get(n)===r&&d.delete(n)},()=>{d.get(n)===r&&d.delete(n)})}return s},x=n=>{let s=h.get(n);return s||(s=(async()=>{let r=await w(n);return{appendInputAudio:(u,E)=>r.appendInputAudio(u,E),onOutputAudio:u=>r.onOutputAudio(u),sessionId:p(n)}})(),h.set(n,s),s.catch(()=>{h.get(n)===s&&h.delete(n)})),s},_=async(n,s,r,u=!1)=>{let E=()=>u?Oe(n.session):Xe(n.session);if(r?.aborted){let O=d.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await E().catch(()=>{}),M(r)}let b=s(n),P=d.get(n);return P!==void 0&&P.waiting++,r===void 0?b:new Promise((O,A)=>{let z=()=>{P!==void 0&&--P.waiting===0&&d.get(n)===P&&(P.gone.abort(),d.delete(n),l.delete(n),h.delete(n),E().catch(()=>{})),A(M(r))};r.addEventListener("abort",z,{once:!0});let Q=()=>r.removeEventListener("abort",z);b.then(C=>{Q(),O(C)},C=>{Q(),A(C)})})},L=async(n,s,r)=>{try{return await r}catch(u){throw(u instanceof T||u instanceof K&&X(u))&&(e.evict(n,s),u instanceof K&&t?.(n,u.kind==="never-live"?"never-live":"create-failed")),u}};return{createResponse:ge({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let r=await c.sessionFor(n,s);return{app:r.app,entry:r.entry,identity:r.identity}}catch(r){if(r instanceof le)return i?i.sessionFor(n):e.sessionFor(n);if(r instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${r.name} ${r.code}: ${r.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw r}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>p(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,r)=>{X(r)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),t?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await D(n.session);let r=pe(W(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return r;let u=n;return(async function*(){try{yield*r}catch(b){throw fe(b)&&(c&&c.owns(u)?c.evict(u):i&&(b instanceof T?i.markSessionDead(u):i.evict(u))),b}finally{c&&c.owns(u)?c.release(u):i?.end(u)}})()}catch(r){throw c&&c.owns(n)?c.release(n):i&&i.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{app:r,entry:u}=await e.sessionFor(n);return await L(r,u,_(u,w,s))},openAudioOn:async(n,s,r,u)=>{let E=m(n);if(E){let A=E.entry.session;return Se(A)}let{app:b,entry:P}=await e.sessionForHandle(n);if(u&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;u({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=R(n)?.app.startsWith(H)??!1;return await L(b,P,_(P,x,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw M(s);let r=await S(n);yield*ie(r.session,s)},openVideoOn:async n=>{let s=m(n);if(s)return Pe(s.entry.session);let{entry:r}=await e.sessionForHandle(n),u=g.get(r);return u||(u=$(r.session),g.set(r,u)),u},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),r=g.get(s);return r||(r=$(s.session),g.set(s,r)),r},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),r=y.get(s);return r||(r=oe(s.session),y.set(s,r)),r},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let r=await c.sessionFor(n,s),u=p(r.entry);if(u===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return V(f,u)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:r,entry:u}=await e.dedicatedSessionFor(n);return V(r,ke(u))},releaseSessionHandle:n=>{let s=R(n);if(!s)return;if(s.app.startsWith(H)){(async()=>{let u=null;try{u=(await e.sessionForHandle(n)).entry}catch{return}await Oe(u.session).catch(()=>{}),await e.evict(s.app,u)})();return}if(!c||s.app!==f)return;let r=c.entryFor(s.key);r&&c.release(r)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:r}=await e.sessionForHandle(n);await e.evict(s,r)},createResponseOn:async(n,s,r)=>{let u=await S(n);await D(u.session);let E=r!==void 0&&m(n)?new j({...u.session,consumerId:r},{sessionTag:r}):u.responses;return W(await E.responses.create(s),u.gone)},onSessionEnd:async(n,s)=>{let r=m(n);if(r)return r.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:u}=await e.sessionForHandle(n),E=u.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return E.onPhase(P=>{if(b||!qe.has(P.name))return;b=!0;let O=E.endsAt??null;s({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Tn as c,Rn as d,Fn as e,Nn as f,Mn as g};