@urun-sh/openai 0.2.60 → 0.3.0

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.
@@ -1,67 +1,7 @@
1
- import { Server } from 'node:http';
2
- import { a as AudioBridge, V as VideoFrameLane } from '../media-DCHTX3Ez.js';
3
-
4
- interface ProxyIdentity {
5
- app: string;
6
- org: string;
7
- fn: string;
8
-
9
- base_url: string;
10
- proxy_version: string;
11
- }
12
-
13
- interface ResponsesCreateParams {
14
- model?: string;
15
- input: unknown;
16
- stream?: boolean;
17
- tools?: unknown;
18
- tool_choice?: unknown;
19
- temperature?: number;
20
- max_output_tokens?: number;
21
- top_p?: number;
22
- stop?: string[];
23
-
24
- reasoning_effort?: string;
25
- chat_template_kwargs?: Record<string, unknown>;
26
- }
27
-
28
- interface SessionEndInfo {
29
-
30
- timeLeftMs: number | null;
31
-
32
- reason: string;
33
- }
34
-
35
- interface ProxyClients {
36
-
37
- createResponse(params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
38
-
39
- listModels(): Promise<unknown>;
40
-
41
- openAudio?(model: string | undefined): Promise<ProxyAudioLane>;
42
-
43
- openVideo?(model: string | undefined): Promise<ProxyVideoLane>;
44
-
45
- sessionHandle(model: string | undefined): Promise<string>;
46
-
47
- createResponseOn(handle: string, params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
48
-
49
- onSessionEnd(handle: string, cb: (end: SessionEndInfo) => void): Promise<() => void>;
50
- }
51
-
52
- type ProxyAudioLane = Pick<AudioBridge, 'appendInputAudio' | 'onOutputAudio'>;
53
-
54
- type ProxyVideoLane = Pick<VideoFrameLane, 'sendInputFrame'>;
55
- interface OpenAIProxyOptions {
56
- clients: ProxyClients;
57
-
58
- apiKey?: string;
59
-
60
- identity?: ProxyIdentity;
61
- }
62
-
63
- declare function createOpenAIProxy(options: OpenAIProxyOptions): Server;
1
+ export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, c as createOpenAIProxy } from '../server-BBKNv7hV.js';
2
+ import 'node:http';
3
+ import '../media-DCHTX3Ez.js';
64
4
 
65
5
  declare const GEMINI_LIVE_PATH = "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
66
6
 
67
- export { GEMINI_LIVE_PATH, type OpenAIProxyOptions, type ProxyClients, type ProxyIdentity, createOpenAIProxy };
7
+ export { GEMINI_LIVE_PATH };
@@ -1 +1 @@
1
- import{a as r,b as e}from"../chunk-4FUBGLFN.js";import"../chunk-VFHQZ4OM.js";import"../chunk-VXTNG2TP.js";export{r as GEMINI_LIVE_PATH,e as createOpenAIProxy};
1
+ import{a as e,c as o}from"../chunk-VG3X2LVG.js";import"../chunk-35LB5OHI.js";import"../chunk-XHIIEA6Z.js";import{c as r}from"../chunk-YSFSRI3D.js";r();export{e as GEMINI_LIVE_PATH,o as createOpenAIProxy};
@@ -0,0 +1,78 @@
1
+ import { IncomingMessage, Server } from 'node:http';
2
+ import { a as AudioBridge, V as VideoFrameLane } from './media-DCHTX3Ez.js';
3
+
4
+ interface ProxyIdentity {
5
+ app: string;
6
+ org: string;
7
+ fn: string;
8
+
9
+ base_url: string;
10
+ proxy_version: string;
11
+ }
12
+
13
+ interface ResponsesCreateParams {
14
+ model?: string;
15
+ input: unknown;
16
+ stream?: boolean;
17
+ tools?: unknown;
18
+ tool_choice?: unknown;
19
+ temperature?: number;
20
+ max_output_tokens?: number;
21
+ top_p?: number;
22
+ stop?: string[];
23
+
24
+ reasoning_effort?: string;
25
+ chat_template_kwargs?: Record<string, unknown>;
26
+ }
27
+
28
+ interface SessionEndInfo {
29
+
30
+ timeLeftMs: number | null;
31
+
32
+ reason: string;
33
+ }
34
+
35
+ interface ProxyClients {
36
+
37
+ createResponse(params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
38
+
39
+ listModels(): Promise<unknown>;
40
+
41
+ openAudio?(model: string | undefined): Promise<ProxyAudioLane>;
42
+
43
+ openVideo?(model: string | undefined): Promise<ProxyVideoLane>;
44
+
45
+ sessionHandle(model: string | undefined): Promise<string>;
46
+
47
+ createResponseOn(handle: string, params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
48
+
49
+ onSessionEnd(handle: string, cb: (end: SessionEndInfo) => void): Promise<() => void>;
50
+ }
51
+
52
+ type ProxyAudioLane = Pick<AudioBridge, 'appendInputAudio' | 'onOutputAudio'>;
53
+
54
+ type ProxyVideoLane = Pick<VideoFrameLane, 'sendInputFrame'>;
55
+
56
+ type ProxyClientsFor = (req: IncomingMessage) => ProxyClients | Promise<ProxyClients>;
57
+ interface ProxyHandlerOptions {
58
+
59
+ clients: ProxyClients | ProxyClientsFor;
60
+
61
+ apiKey?: string;
62
+
63
+ identity?: ProxyIdentity;
64
+
65
+ statusOf?: (err: unknown) => {
66
+ status: number;
67
+ openaiType: string;
68
+ anthropicType: string;
69
+ } | null;
70
+ }
71
+
72
+ interface OpenAIProxyOptions extends ProxyHandlerOptions {
73
+ clients: ProxyClients;
74
+ }
75
+
76
+ declare function createOpenAIProxy(options: OpenAIProxyOptions): Server;
77
+
78
+ export { type OpenAIProxyOptions as O, type ProxyClients as P, type ProxyIdentity as a, createOpenAIProxy as c };
@@ -0,0 +1,182 @@
1
+ import { IncomingMessage, Server } from 'node:http';
2
+ import { a as AudioBridge, V as VideoFrameLane } from './media-DCHTX3Ez.cjs';
3
+
4
+ /**
5
+ * WHAT a proxy serves — the `identity` block on `GET /stats`. Reuse of a
6
+ * running proxy is allowed iff every field matches the launching invocation
7
+ * EXACTLY: a partial match (same app, different fn; same everything, older
8
+ * proxy_version) silently routes the agent at the wrong backend, which is
9
+ * worse than any error.
10
+ */
11
+ interface ProxyIdentity {
12
+ app: string;
13
+ org: string;
14
+ fn: string;
15
+ /**
16
+ * The control-plane URL the proxy's backhaul session opens against
17
+ * (URUN_BASE_URL verbatim — same org/app/fn on staging vs prod are
18
+ * DIFFERENT backends; review finding, #285). Compared exactly: a cosmetic
19
+ * difference (trailing slash) merely refuses reuse and spawns an ephemeral
20
+ * proxy — the safe direction.
21
+ */
22
+ base_url: string;
23
+ proxy_version: string;
24
+ }
25
+
26
+ /**
27
+ * The local OpenAI-compatible proxy — `npx @urun-sh/openai proxy`.
28
+ *
29
+ * A loopback HTTP server speaking the OpenAI REST surface (`/v1/models`,
30
+ * `/v1/responses`, `/v1/chat/completions`, SSE streaming included), so any
31
+ * OpenAI-env-var tool — coding agents first — integrates with uRun with ZERO
32
+ * code changes: point `OPENAI_BASE_URL` at it and keep making plain, local,
33
+ * "inefficient" HTTP requests. The proxy backhauls each request over the uRun
34
+ * session transport (the `@urun-sh/openai` Responses client → session doc
35
+ * lanes + streams — no public OpenAI-style HTTP leaves the machine), which is
36
+ * also where the delta-sync chat-state doc lane (urun-python
37
+ * `urun/serve/chat_state.py`) plugs in as the transport evolves.
38
+ *
39
+ * Local-trust model: binds 127.0.0.1 by default; `apiKey` (when set) must
40
+ * match the agent's `Authorization: Bearer` — otherwise any local bearer is
41
+ * accepted (the key the agent sends is NEVER forwarded upstream; uRun auth is
42
+ * the session's own).
43
+ */
44
+
45
+ /** The request envelope every Responses-shaped upstream call carries. */
46
+ interface ResponsesCreateParams {
47
+ model?: string;
48
+ input: unknown;
49
+ stream?: boolean;
50
+ tools?: unknown;
51
+ tool_choice?: unknown;
52
+ temperature?: number;
53
+ max_output_tokens?: number;
54
+ top_p?: number;
55
+ stop?: string[];
56
+ /**
57
+ * Reasoning controls (urun-python #1667): forwarded VERBATIM to the serve
58
+ * envelope — `chat_template_kwargs.enable_thinking:false` is the think-off
59
+ * switch. Absent -> absent (no default injection; server-side validation).
60
+ */
61
+ reasoning_effort?: string;
62
+ chat_template_kwargs?: Record<string, unknown>;
63
+ }
64
+ /** How one pinned session ended (the native phase machinery's terminal step). */
65
+ interface SessionEndInfo {
66
+ /**
67
+ * Milliseconds until the session's native deadline (`endsAt`), or null when
68
+ * the app declared no maximum session length. NOTE (missing primitive,
69
+ * called out in the PR): core exposes no PRE-expiry notice event — this
70
+ * callback fires AT terminal loss, so timeLeftMs is ~0 on expiry.
71
+ */
72
+ timeLeftMs: number | null;
73
+ /** The terminal reason (expired / ended / error), for the loud close. */
74
+ reason: string;
75
+ }
76
+ /** The upstream calls the proxy makes — injectable (tests; alt transports). */
77
+ interface ProxyClients {
78
+ /** `UrunResponses(session).responses.create` — an async iterable of Responses stream events. */
79
+ createResponse(params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
80
+ /** `listModels(...)` result (an OpenAI model list object). */
81
+ listModels(): Promise<unknown>;
82
+ /**
83
+ * Open (or reuse) the NATIVE audio lanes on the pooled session `model` routes
84
+ * to — the same first-party machinery as RealtimeClient.enableAudio
85
+ * (transport/media.ts `enableSessionAudio`: AudioBridge over the session's
86
+ * `rt-audio-in`/`rt-audio-out` stream lanes at 24 kHz). One lane per pooled
87
+ * session; repeat calls return the same lane. Optional at the seam because
88
+ * text-only embeddings exist — but a surface that RECEIVES audio while the
89
+ * embedder wired no `openAudio` must fail LOUD, never drop chunks.
90
+ */
91
+ openAudio?(model: string | undefined): Promise<ProxyAudioLane>;
92
+ /**
93
+ * Open (or reuse) the NATIVE video FRAME lane on the pooled session `model`
94
+ * routes to (transport/media.ts `enableSessionVideo`: discrete JPEG frames →
95
+ * `stream('rt-video-in').emit`, the §5 named-DATA image-bytes path — NOT the
96
+ * RTP media plane, which requires an already-H.264-encoded track). One lane
97
+ * per pooled session; repeat calls return the same lane. Optional at the seam
98
+ * because text-only embeddings exist — but a surface that RECEIVES video
99
+ * frames while the embedder wired no `openVideo` must fail LOUD, never drop
100
+ * frames.
101
+ */
102
+ openVideo?(model: string | undefined): Promise<ProxyVideoLane>;
103
+ /**
104
+ * SESSION-IDENTITY SEAM (ModelRouter.handleFor): the opaque stable handle
105
+ * for the pooled session currently serving `model`'s turns. Derived from
106
+ * native identity (app slug + uRun session id) — the same identity the
107
+ * serve-side session-affinity tag rides (urun-python#1556/#1582).
108
+ */
109
+ sessionHandle(model: string | undefined): Promise<string>;
110
+ /**
111
+ * createResponse PINNED to the exact session a handle names
112
+ * (ModelRouter.sessionForHandle). Throws SessionGoneError LOUDLY when that
113
+ * session is gone or was replaced — never silently opens a fresh session
114
+ * while claiming resume. Deliberately NO re-home on this path: re-homing
115
+ * would swap the pinned session out from under the caller.
116
+ */
117
+ createResponseOn(handle: string, params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
118
+ /**
119
+ * Subscribe to the pinned session's terminal end via core's NATIVE phase
120
+ * machinery (Session.onPhase → terminal 'expired'/'ended'/'error'). Fires
121
+ * `cb` once. Throws SessionGoneError if the handle's session is already
122
+ * gone — which doubles as the loud reattach check at resume time. Returns
123
+ * the unsubscribe.
124
+ */
125
+ onSessionEnd(handle: string, cb: (end: SessionEndInfo) => void): Promise<() => void>;
126
+ }
127
+ /**
128
+ * The audio lane handle `openAudio` returns — structurally the transport
129
+ * AudioBridge (media.ts): base64 PCM16 @24 kHz mono in both directions.
130
+ */
131
+ type ProxyAudioLane = Pick<AudioBridge, 'appendInputAudio' | 'onOutputAudio'>;
132
+ /**
133
+ * The video frame-lane handle `openVideo` returns — structurally the transport
134
+ * VideoFrameLane (media.ts): one raw encoded JPEG frame per call, input-only
135
+ * (Live-style protocols have no video OUT modality).
136
+ */
137
+ type ProxyVideoLane = Pick<VideoFrameLane, 'sendInputFrame'>;
138
+ /**
139
+ * Per-request `ProxyClients` resolution — the seam the HOSTED multi-tenant
140
+ * server (`src/hosted/`) plugs into so ONE handler implementation serves
141
+ * every org: the hosted server resolves the caller's org from its Bearer API
142
+ * key and returns THAT org's backhaul. The local CLI passes a fixed
143
+ * `ProxyClients` instead; both go through the identical handler body below.
144
+ *
145
+ * Throwing from here is the loud path: the thrown error surfaces in the
146
+ * lane's native error envelope (see {@link ProxyHandlerOptions.statusOf}).
147
+ */
148
+ type ProxyClientsFor = (req: IncomingMessage) => ProxyClients | Promise<ProxyClients>;
149
+ interface ProxyHandlerOptions {
150
+ /** A fixed backhaul (local CLI) or a per-request resolver (hosted server). */
151
+ clients: ProxyClients | ProxyClientsFor;
152
+ /** Optional bearer the local agent must present (never forwarded upstream). */
153
+ apiKey?: string;
154
+ /**
155
+ * WHAT this proxy serves (app/org/fn/base_url + proxy_version), surfaced as
156
+ * the `identity` block on `GET /stats` so a second `urun compat` invocation
157
+ * can reuse this proxy iff the identity matches its own exactly. Only the
158
+ * standalone `urun compat proxy` command sets it — a launch-mode proxy is
159
+ * child-owned (it dies with its child) and an embedder that omits it is
160
+ * simply never reused.
161
+ */
162
+ identity?: ProxyIdentity;
163
+ /**
164
+ * Map a thrown error onto an HTTP status + error `type` before the generic
165
+ * 500. The hosted server uses it to turn its auth/tenancy failures into a
166
+ * 401 in the OpenAI envelope. Returning null means "not mine" — the error
167
+ * takes the ordinary loud 500 path.
168
+ */
169
+ statusOf?: (err: unknown) => {
170
+ status: number;
171
+ openaiType: string;
172
+ anthropicType: string;
173
+ } | null;
174
+ }
175
+ /** The proxy server's own options: a FIXED backhaul (the local CLI lane). */
176
+ interface OpenAIProxyOptions extends ProxyHandlerOptions {
177
+ clients: ProxyClients;
178
+ }
179
+ /** Build (not listen) the proxy server — the caller owns listen/close. */
180
+ declare function createOpenAIProxy(options: OpenAIProxyOptions): Server;
181
+
182
+ export { type OpenAIProxyOptions as O, type ProxyClients as P, type ProxyIdentity as a, createOpenAIProxy as c };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.2.60",
3
+ "version": "0.3.0",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -27,6 +27,16 @@
27
27
  "default": "./dist/proxy/index.cjs"
28
28
  }
29
29
  },
30
+ "./hosted": {
31
+ "import": {
32
+ "types": "./dist/hosted/index.d.ts",
33
+ "default": "./dist/hosted/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/hosted/index.d.cts",
37
+ "default": "./dist/hosted/index.cjs"
38
+ }
39
+ },
30
40
  "./pi-extension": {
31
41
  "import": {
32
42
  "types": "./dist/pi-extension/index.d.ts",
@@ -50,7 +60,7 @@
50
60
  "build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
51
61
  },
52
62
  "peerDependencies": {
53
- "@urun-sh/core": "^0.2.53"
63
+ "@urun-sh/core": "^0.3.0"
54
64
  },
55
65
  "dependencies": {
56
66
  "openai": "4.104.0",
@@ -1,41 +0,0 @@
1
- import{b as V,c as me}from"./chunk-VXTNG2TP.js";var Ce="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",We=1007,Ee=1008,H=1011,ge=1008,i=class extends Error{constructor(e,o=We){super(e);this.closeCode=o}closeCode},x=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,ae=["setup","clientContent","realtimeInput","toolResponse"];function Te(t){let n;try{n=JSON.parse(t)}catch{throw new i("client message is not valid JSON")}let e=x(n);if(!e)throw new i("client message must be a JSON object");let o=ae.filter(u=>e[u]!==void 0),s=Object.keys(e).filter(u=>!ae.includes(u));if(s.length>0)throw new i(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${ae.join(", ")}`);if(o.length!==1)throw new i(`client message must contain exactly one of ${ae.join(", ")} (got ${o.length})`);let r=o[0],a=x(e[r]);if(!a)throw new i(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function Ne(t,n){if(typeof t=="string")return t;let e=x(t),o=e?e.parts:void 0;if(!Array.isArray(o))throw new i(`${n}: expected a Content with a parts array`);let s=[];for(let r of o){let a=x(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new i(`${n}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new i(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new i(`${n}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
2
- `)}var Xe={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Qe={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ze=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption"],Ie=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function et(t){let n=x(t);if(!n)throw new i("setup.realtimeInputConfig must be an object");for(let s of Object.keys(n))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new i(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let e=x(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!e)throw new i("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(e??{}))if(s!=="disabled")throw new i(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(e?.disabled!==!0)throw new i("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(n.activityHandling!==void 0){if(!Ie.includes(n.activityHandling))throw new i(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Ie.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var tt=["temperature","maxOutputTokens","responseModalities"];function Pe(t){for(let[c,g]of Object.entries(Qe))if(t[c]!==void 0)throw new i(g);for(let c of Object.keys(t))if(!Ze.includes(c))throw new i(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new i('setup.model is required (format "models/{model}")');let n=t.model.replace(/^models\//,""),e,o,s=!1,r=x(t.generationConfig);if(t.generationConfig!==void 0&&!r)throw new i("setup.generationConfig must be an object");if(r){for(let c of Object.keys(r))if(!tt.includes(c))throw new i(`unsupported generationConfig field "${c}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new i("generationConfig.temperature must be a number");e=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new i("generationConfig.maxOutputTokens must be a number");o=r.maxOutputTokens}if(r.responseModalities!==void 0){let c=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let g of c){let p=String(g).toUpperCase();if(p==="AUDIO"){s=!0;continue}if(p!=="TEXT")throw new i(`responseModalities ${JSON.stringify(g)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let a=[];t.systemInstruction!==void 0&&a.push({role:"system",content:Ne(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new i("setup.tools must be an array");u=[];for(let c of t.tools){let g=x(c);if(!g)throw new i("setup.tools entries must be objects");for(let p of Object.keys(g))if(p!=="functionDeclarations")throw new i(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new i("tool.functionDeclarations must be an array");for(let p of g.functionDeclarations){let h=x(p);if(!h||typeof h.name!="string")throw new i("functionDeclarations entries require a string name");u.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}u.length===0&&(u=void 0)}let f={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=x(t.sessionResumption);if(!c)throw new i("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(c))if(g!=="handle")throw new i(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new i("sessionResumption.handle must be a non-empty string when present");f={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=t.realtimeInputConfig===void 0?Xe:et(t.realtimeInputConfig);return{model:n,systemItems:a,tools:u,temperature:e,maxOutputTokens:o,audioModality:s,activity:d,sessionResumption:f}}function Me(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function $e(t){let n=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function Le(t){for(let o of Object.keys(t))if(o!=="turns"&&o!=="turnComplete")throw new i(`unsupported clientContent field "${o}"`);let n=t.turns===void 0?[]:t.turns;if(!Array.isArray(n))throw new i("clientContent.turns must be an array");let e=[];for(let o of n){let s=x(o);if(!s)throw new i("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new i(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);e.push({role:r==="model"?"assistant":"user",content:Ne(s,"clientContent.turns")})}return{items:e,turnComplete:t.turnComplete===!0}}var ue=16e3,Ue=24e3,nt=`audio/pcm;rate=${Ue}`,je=Buffer.alloc(960).toString("base64");function ot(t,n,e){if(n===e)return t;let o=Math.floor(t.length*e/n),s=new Int16Array(o),r=n/e,a=t.length-1;for(let u=0;u<o;u++){let f=u*r,d=Math.floor(f);if(d>=a){s[u]=t[a];continue}let c=f-d;s[u]=Math.round(t[d]+(t[d+1]-t[d])*c)}return s}function st(t){let n=x(t);if(!n)throw new i("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new i("realtimeInput.video.data must be non-empty base64");let e=Buffer.from(n.data,"base64");if(e.length<3||e[0]!==255||e[1]!==216)throw new i("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(e)}function rt(t){let n=x(t);if(!n)throw new i("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new i(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let e=/;\s*rate=(\d+)/.exec(n.mimeType);if(e&&Number(e[1])!==ue)throw new i(`realtimeInput.audio.mimeType declares rate=${e[1]} \u2014 the Live spec input format is ${ue} Hz (audio/pcm;rate=${ue})`);if(typeof n.data!="string"||n.data.length===0)throw new i("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.data,"base64");if(o.length===0||o.length%2!==0)throw new i(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let a=0;a<s.length;a++)s[a]=o.readInt16LE(a*2);let r=ot(s,ue,Ue);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Be(t){if(t.mediaChunks!==void 0)throw new i('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new i("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=t.activityStart!==void 0?"activityStart":"activityEnd",r=x(t[s]);if(!r||Object.keys(r).length!==0)throw new i(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(t))if(!n.includes(o))throw new i(`unsupported realtimeInput field "${o}"`);let e=n.filter(o=>t[o]!==void 0);if(e.length!==1)throw new i(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${e.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:rt(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:st(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new i("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new i("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function qe(t){for(let n of Object.keys(t))if(n!=="functionResponses")throw new i(`unsupported toolResponse field "${n}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new i("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(n=>{let e=x(n);if(!e||typeof e.id!="string"||e.id.length===0)throw new i("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:e.id,output:JSON.stringify(e.response??null)}})}function De(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Je(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:nt,data:t}}]}}}}function He(t){let n=x(t)??{},e=Array.isArray(n.output)?n.output:[],o=[],s=[],r=typeof n.output_text=="string"?n.output_text:"";if(!r)for(let d of e){let c=x(d);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let g of c.content){let p=x(g);p?.type==="output_text"&&typeof p.text=="string"&&(r+=p.text)}}r&&s.push({role:"assistant",content:r});for(let d of e){let c=x(d);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new i(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,H);let g=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(g)}catch{throw new i(`upstream function_call arguments are not valid JSON: ${g}`,H)}o.push({id:c.call_id,name:c.name,args:p}),s.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:g})}let a=[];o.length>0&&a.push({toolCall:{functionCalls:o}}),a.push({serverContent:{generationComplete:!0}});let u=x(n.usage),f={serverContent:{turnComplete:!0}};if(u){let d={};typeof u.input_tokens=="number"&&(d.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(d.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(d.totalTokenCount=u.total_tokens),Object.keys(d).length>0&&(f.usageMetadata=d)}return a.push(f),{messages:a,assistantItems:s}}import{createServer as ct}from"http";import{randomUUID as it}from"crypto";import{WebSocketServer as at}from"ws";var ut=256,he=class{snapshots=new Map;store(n,e){for(this.snapshots.set(n,e);this.snapshots.size>ut;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},ne=t=>t.slice(0,120),ye=class{constructor(n,e,o){this.ws=n;this.clients=e;this.registry=o;n.on("message",s=>this.onMessage(s)),n.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;video=null;activityOpen=!1;activeTurn=null;send(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof V){this.ws.close(Ee,ne(n.message));return}if(n instanceof me){this.ws.close(ge,ne(n.message));return}if(n instanceof i){this.ws.close(n.closeCode,ne(n.message));return}this.ws.close(H,ne(String(n instanceof Error?n.message:n)))}onMessage(n){try{let e=Te(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(e.kind==="setup"){this.handleSetup(e.setup).catch(s=>this.fail(s));return}if(!this.config)throw new i(`"${e.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(e.kind==="clientContent"){let{items:s,turnComplete:r}=Le(e.clientContent);this.transcript.push(...s),r&&this.enqueue(()=>this.runTurn());return}if(e.kind==="realtimeInput"){let s=Be(e.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:je);return}this.transcript.push(...qe(e.toolResponse)),this.enqueue(()=>this.runTurn())}catch(e){this.fail(e)}}async handleSetup(n){if(this.config)throw new i("setup may only be sent once, as the first client message");let e=Pe(n),o=e.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new i("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",ge);if(s.model!==e.model)throw new i(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${e.model}", per the Live API session-resumption contract)`);if(e.systemItems.length>0)throw new i("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r)))}else this.proxyHandle=await this.clients.sessionHandle(e.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...e.systemItems);this.config=e,this.send({setupComplete:{}}),e.audioModality&&this.ensureAudioLane(),e.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new i("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openAudio;if(!e)throw new i("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",H);return this.audio=(async()=>{let o=await e.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(s=>this.send(Je(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(e=>e.appendInputAudio(n)).catch(e=>this.fail(e))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new i("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let e=this.clients.openVideo;if(!e)throw new i("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",H);return this.video=Promise.resolve(e.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(e=>e.sendInputFrame(n)).catch(e=>this.fail(e))}onActivity(n,e){if(!e.activity.manualActivity)throw new i(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="activityStart"){if(this.activityOpen)throw new i("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,e.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new i("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(e=>this.fail(e))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let e=await this.clients.sessionHandle(n.model);this.proxyHandle=e;let o=it();this.registry.store(o,{model:n.model,proxyHandle:e,transcript:[...this.transcript]}),this.send(Me(o))}async handleUpstreamEnd(n){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let e=null;try{e=await this.clients.sessionHandle(this.config.model)}catch{}if(e!==null&&e!==this.proxyHandle){this.proxyHandle=e,this.unsubscribeEnd=await this.clients.onSessionEnd(e,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send($e(n.timeLeftMs)),this.ws.close(H,ne(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let e={interrupted:!1};this.activeTurn=e;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),s,r=!1;for await(let f of o){if(e.interrupted)break;let d=f;if(d.type==="error")throw new i(`upstream error: ${JSON.stringify(d)}`,H);if(d.type==="response.completed"){s=d.response,r=!0;continue}let c=De(d);c&&this.send(c)}if(e.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!r)throw new i("upstream produced no response.completed event",H);let{messages:a,assistantItems:u}=He(s);this.transcript.push(...u);for(let f of a)this.send(f);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},lt=(t,n)=>{let e=t.headers["x-goog-api-key"];if(typeof e=="string")return e;let o=t.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Fe(t,n){let e=new at({noServer:!0}),o=new he;t.on("upgrade",(s,r,a)=>{let u=new URL(s.url??"/","http://localhost");if(u.pathname!==Ce){r.write(`HTTP/1.1 404 Not Found\r
3
- Connection: close\r
4
- \r
5
- no WS route for ${u.pathname}`),r.destroy();return}if(n.apiKey&&lt(s,u)!==n.apiKey){r.write(`HTTP/1.1 401 Unauthorized\r
6
- Connection: close\r
7
- \r
8
- invalid local proxy api key`),r.destroy();return}e.handleUpgrade(s,r,a,f=>{new ye(f,n.clients,o)})})}var ke=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=o}modelEntry(n){let e=this.models[n];if(e)return e;let o=Object.keys(this.models).length>=dt?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let o=this,s=performance.now(),r=null,a=0;return(async function*(){for await(let f of n)f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(r===null&&(r=performance.now(),o.ttftMs.push(r-s),o.ttftMs.length>512&&o.ttftMs.shift()),a+=1,o.tokensOut+=1,o.charsOut+=f.delta.length,e!==void 0&&(o.modelEntry(e).tokens_out+=1)),yield f;let u=(performance.now()-(r??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((o,s)=>o-s);return e[Math.floor(e.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((e,o)=>e+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}};function xe(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function q(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function F(t,n,e,o="invalid_request_error"){q(t,n,{error:{message:e,type:o}})}function B(t,n,e,o){q(t,n,{type:"error",error:{type:e,message:o}})}function Re(t,n,e){if(n==="anthropic"){q(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}q(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var dt=256,pt=128;function Ae(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,pt)}var Ge=64*1024*1024,le=class extends Error{};async function ft(t){let n=[],e=0;for await(let s of t){if(e+=s.length,e>Ge)throw new le(`request body exceeds ${Ge} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function W(t,n,e,o){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:o}]}}var mt=256;function gt(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var ve=class{conversations=new Map;thread(n,e){let o=gt(e);if(n==null)return o;let s=this.conversations.get(String(n));if(!s)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(n,e,o){this.conversations.set(n,[...e,{role:"assistant",content:o}]);for(let s of this.conversations.keys()){if(this.conversations.size<=mt)break;this.conversations.delete(s)}}};function oe(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function z(t){return t.find(n=>n.type==="response.completed")?.response??null}function ce(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=e(n.input_tokens),s=e(n.output_tokens);if(o===0&&s===0)return null;let r=e(n.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:r}}function Ve(t){let n=ce(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Ke(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let s of o.content)s.type==="reasoning_text"&&(e+=String(s.text??""));return e}function se(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var K=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),o=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},ht=["<tool_call>","<function="];function yt(t){return ht.find(n=>t.includes(n))}function X(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Q(t,n,e){if(!(!t||n>0))return yt(e)}function _t(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var de=class extends Error{};function wt(t,n){return Array.isArray(n)?n.map(e=>{let o=e;if(o.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let s=o.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new de(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function kt(t){let n=[];for(let e of t){if(e.role==="tool"){n.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&n.push({role:"assistant",content:e.content});for(let o of e.tool_calls){let s=o.function??{};n.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}n.push({...e,content:wt(e.role,e.content)})}return n}function _e(t){return oe(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function ze(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function vt(t,n,e,o,s){let r=t.stream===!0,a;try{a=e.thread(t.previous_response_id,t.input)}catch(m){F(o,400,String(m instanceof Error?m.message:m));return}t.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(a))-Buffer.byteLength(JSON.stringify(t.input)));let u=`resp_${Math.random().toString(36).slice(2,14)}`,f=t.store!==!1,d=Ae(t);s.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await n.createResponse({model:t.model,input:a,stream:r,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(m){if(m instanceof V){Re(o,"openai",m);return}throw m}let p=[];if(r){xe(o);let m=y=>{o.write(`event: ${String(y.type??"message")}
9
- data: ${JSON.stringify(y)}
10
-
11
- `)},P=y=>y.response&&typeof y.response=="object"?{...y,response:{...y.response,id:u}}:y,S=`item_${u.slice(5)}`,M=`rs_${u.slice(5)}`,E=!1,$=!1,l=0,k=()=>{E||(E=!0,m({type:"response.created",response:{id:u,object:"response",status:"in_progress"}}))},U=!1,C=0,L="",j=()=>{U&&(U=!1,m({type:"response.reasoning_text.done",item_id:M,output_index:C,content_index:0,text:L}),m({type:"response.output_item.done",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:L}],status:"completed"}}))},T=!1,w=0,A="",D=y=>{T&&(T=!1,m({type:"response.output_text.done",item_id:S,output_index:w,content_index:0,text:A}),m({type:"response.content_part.done",item_id:S,output_index:w,content_index:0,part:{type:"output_text",text:A}}),m({type:"response.output_item.done",output_index:w,item:{id:S,type:"message",role:"assistant",status:y,content:[{type:"output_text",text:A}]}}))},J=new K,v=null,Y=-1,Z=y=>{if(!v)return;let R=v;v=null,m({type:"response.function_call_arguments.done",item_id:R.fcId,output_index:R.outputIndex,arguments:R.args}),m({type:"response.output_item.done",output_index:R.outputIndex,item:{id:R.fcId,type:"function_call",call_id:R.callId??R.fcId,name:R.name??"",arguments:R.args,status:y}})},ee=!1;for await(let y of s.track(g,d)){p.push(y);let R=String(y.type??"");if(R==="response.created"||R==="response.in_progress"){E=!0,m(P(y));continue}if(R==="response.output_item.added"){$=!0,m(P(y));continue}if(R==="response.reasoning_text.delta"&&!$){k(),U||(U=!0,C=l++,m({type:"response.output_item.added",output_index:C,item:{id:M,type:"reasoning",summary:[],content:[],status:"in_progress"}})),L+=String(y.delta??""),m({type:"response.reasoning_text.delta",item_id:M,output_index:C,content_index:0,delta:y.delta});continue}if(R==="response.output_text.delta"&&!$){k(),j(),T||(T=!0,w=l++,m({type:"response.output_item.added",output_index:w,item:{id:S,type:"message",role:"assistant",status:"in_progress",content:[]}}),m({type:"response.content_part.added",item_id:S,output_index:w,content_index:0,part:{type:"output_text",text:""}})),A+=String(y.delta??""),m({type:R,item_id:S,output_index:w,content_index:0,delta:y.delta});continue}let I=$?null:se(y);if(I){if(k(),j(),D("completed"),J.add(I),I.tool_index!==Y){Z("completed"),Y=I.tool_index;let _=l++;v={fcId:`fc_${u.slice(5)}_${I.tool_index}`,outputIndex:_,callId:I.call_id,name:I.name,args:""},m({type:"response.output_item.added",output_index:_,item:{id:v.fcId,type:"function_call",call_id:v.callId??v.fcId,name:v.name??"",arguments:"",status:"in_progress"}})}v&&(I.call_id&&(v.callId=I.call_id),I.name&&(v.name=I.name),v.args+=I.delta,m({type:"response.function_call_arguments.delta",item_id:v.fcId,output_index:v.outputIndex,delta:I.delta}));continue}if(R==="response.completed"&&!$){let _=oe(y.response),b=Q(c,J.size+_.length,A);if(b){ee=!0,m({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:X(d,b)}});break}j(),D("completed"),Z("completed"),J.size===0&&_.forEach(G=>{let te=l++,ie=G.id??G.call_id??`fc_${te}`,fe=G.arguments??"",Se={id:ie,type:"function_call",call_id:G.call_id??ie,name:G.name??""};m({type:"response.output_item.added",output_index:te,item:{...Se,arguments:"",status:"in_progress"}}),m({type:"response.function_call_arguments.delta",item_id:ie,output_index:te,delta:fe}),m({type:"response.function_call_arguments.done",item_id:ie,output_index:te,arguments:fe}),m({type:"response.output_item.done",output_index:te,item:{...Se,arguments:fe,status:"completed"}})}),m(P(y));continue}m(P(y))}j(),D("incomplete"),Z("incomplete"),f&&!ee&&e.remember(u,a,ze(p,z(p))),o.write(`data: [DONE]
12
-
13
- `),o.end();return}let h=null;for await(let m of s.track(g,d)){if(p.push(m),m.type==="error"){F(o,502,JSON.stringify(m),"upstream_error");return}m.type==="response.completed"&&(h=m.response)}if(h==null){F(o,502,"upstream produced no response.completed event","upstream_error");return}let O=ze(p,h),N=Q(c,oe(h).length,O);if(N){F(o,502,X(d,N),"upstream_error");return}f&&e.remember(u,a,O),q(o,200,{...h,id:u})}async function xt(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){F(e,400,"chat/completions requires a messages array");return}let r=String(t.model??"urun"),a=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,u;try{u=kt(s)}catch(l){if(l instanceof de){F(e,400,l.message);return}throw l}let f=Ae(t);o.model(f);let d=Array.isArray(t.tools)&&t.tools.length>0,c;try{c=await n.createResponse({model:t.model,input:u,stream:!0,tools:_t(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(l){if(l instanceof V){Re(e,"openai",l);return}throw l}if(t.stream===!0){xe(e);let l=[],k=new K,U="";e.write(`data: ${JSON.stringify(W(a,r,{role:"assistant"},null))}
14
-
15
- `);for await(let w of o.track(c,f)){l.push(w);let A=se(w);if(w.type==="response.output_text.delta"&&typeof w.delta=="string")U+=w.delta,e.write(`data: ${JSON.stringify(W(a,r,{content:w.delta},null))}
16
-
17
- `);else if(w.type==="response.reasoning_text.delta"&&typeof w.delta=="string")e.write(`data: ${JSON.stringify(W(a,r,{reasoning_content:w.delta},null))}
18
-
19
- `);else if(A){let{call:D,isNew:J}=k.add(A),v=J?{index:A.tool_index,id:D.id??`call_${A.tool_index}`,type:"function",function:{name:D.name??"",arguments:A.delta}}:{index:A.tool_index,function:{arguments:A.delta}};e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:[v]},null))}
20
-
21
- `)}else if(w.type==="error"){e.write(`data: ${JSON.stringify({error:w})}
22
-
23
- `),e.end();return}}let C=_e(z(l)),L=Q(d,k.size+C.length,U);if(L){e.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:X(f,L)}})}
24
-
25
- `),e.end();return}k.size===0&&C.length>0&&e.write(`data: ${JSON.stringify(W(a,r,{tool_calls:C},null))}
26
-
27
- `);let j=k.size>0||C.length>0;e.write(`data: ${JSON.stringify(W(a,r,{},j?"tool_calls":"stop"))}
28
-
29
- `),ce(z(l))&&e.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[],usage:Ve(z(l))})}
30
-
31
- `),e.write(`data: [DONE]
32
-
33
- `),e.end();return}let g="",p="",h=[],O=new K;for await(let l of o.track(c,f)){h.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(g+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(p+=l.delta);let k=se(l);if(k&&O.add(k),l.type==="error"){F(e,502,JSON.stringify(l),"upstream_error");return}}let N=z(h),m=_e(N),P=m.length>0?m:_e({output:O.items()}),S=Q(d,P.length,g);if(S){F(e,502,X(f,S),"upstream_error");return}let M=P.map(({index:l,...k})=>k),E={role:"assistant",content:g||null},$=p||Ke(N);$&&(E.reasoning_content=$),M.length>0&&(E.tool_calls=M),q(e,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,message:E,finish_reason:M.length>0?"tool_calls":"stop"}],usage:Ve(N)})}function Rt(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var re=class extends Error{};function pe(t){return new re(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function At(t){if(Array.isArray(t))return t.map(n=>{let e=n;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema}})}function St(t){if(t==null)return;let n=t.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:t.name};throw new re(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function It(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw pe(typeof t);let n="";for(let e of t){let o=String(e.type??"");if(o!=="text")throw pe(`tool_result > ${o}`);n+=String(e.text??"")}return n}function bt(t){let{role:n,content:e}=t;if(typeof e=="string")return[{role:n,content:e}];if(e==null)return[];if(!Array.isArray(e))throw pe(typeof e);let o=[],s="",r=()=>{s&&(o.push({role:n,content:s}),s="")};for(let a of e){let u=String(a.type??"");if(u==="text")s+=String(a.text??"");else if(u==="tool_use")r(),o.push({type:"function_call",call_id:a.id,name:a.name,arguments:JSON.stringify(a.input??{})});else if(u==="tool_result")r(),o.push({type:"function_call_output",call_id:a.tool_use_id,output:It(a.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw pe(u)}}return r(),o}function we(t){return oe(t).map((n,e)=>{let o;try{o=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${e}`,name:n.name??"",input:o}})}async function Ot(t,n,e,o){let s=t.messages;if(!Array.isArray(s)){B(e,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){B(e,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){B(e,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(l=>typeof l!="string"))){B(e,400,"invalid_request_error","stop_sequences must be an array of strings");return}let r=String(t.model??"urun"),a=`msg_${Math.random().toString(36).slice(2,14)}`,u=[],f;try{t.system&&u.push({role:"system",content:Rt(t.system)});for(let l of s)u.push(...bt(l));f=St(t.tool_choice)}catch(l){if(l instanceof re){B(e,400,"invalid_request_error",l.message);return}throw l}let d=Ae(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await n.createResponse({model:t.model,input:u,stream:!0,tools:At(t.tools),tool_choice:f,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences})}catch(l){if(l instanceof V){Re(e,"anthropic",l);return}throw l}let p=(l,k)=>{e.destroyed||e.write(`event: ${l}
34
- data: ${JSON.stringify({type:l,...k})}
35
-
36
- `)};if(t.stream===!0){let l=o.track(g,d);xe(e),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:r,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let k=0,U="",C=0,L="none",j=()=>L,T=-1,w=-1,A=new K,D=[],J=()=>{L!=="none"&&(L="none",p("content_block_stop",{index:T}))},v=(_,b)=>{J(),L=_,T=C++,p("content_block_start",{index:T,content_block:b})};for await(let _ of l){if(e.destroyed)break;D.push(_);let b=se(_);if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")j()!=="thinking"&&v("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:T,delta:{type:"thinking_delta",thinking:_.delta}});else if(_.type==="response.output_text.delta"&&typeof _.delta=="string")j()!=="text"&&v("text",{type:"text",text:""}),k+=1,U+=_.delta,p("content_block_delta",{index:T,delta:{type:"text_delta",text:_.delta}});else if(b){let{call:G}=A.add(b);(j()!=="tool"||b.tool_index!==w)&&(w=b.tool_index,v("tool",{type:"tool_use",id:G.id??`call_${b.tool_index}`,name:G.name??"",input:{}})),b.delta&&p("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:b.delta}})}else if(_.type==="error"){p("error",{error:{type:"api_error",message:JSON.stringify(_)}}),e.end();return}}if(e.destroyed)return;let Y=z(D),Z=oe(Y),ee=Q(c,A.size+Z.length,U);if(ee){p("error",{error:{type:"api_error",message:X(d,ee)}}),e.end();return}J();let y=[];if(A.size===0)try{y=we(Y)}catch(_){p("error",{error:{type:"api_error",message:String(_ instanceof Error?_.message:_)}}),e.end();return}C===0&&y.length===0&&(v("text",{type:"text",text:""}),J()),y.forEach(_=>{let b=C++;p("content_block_start",{index:b,content_block:{..._,input:{}}}),p("content_block_delta",{index:b,delta:{type:"input_json_delta",partial_json:JSON.stringify(_.input??{})}}),p("content_block_stop",{index:b})});let R=A.size>0||y.length>0,I=ce(Y);p("message_delta",{delta:{stop_reason:R?"tool_use":"end_turn"},usage:I?{input_tokens:I.input_tokens,output_tokens:I.output_tokens}:{output_tokens:k}}),p("message_stop",{}),e.end();return}let h="",O="",N=[],m=new K;for await(let l of o.track(g,d)){N.push(l),l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(h+=l.delta),l.type==="response.reasoning_text.delta"&&typeof l.delta=="string"&&(O+=l.delta);let k=se(l);if(k&&m.add(k),l.type==="error"){B(e,502,"api_error",JSON.stringify(l));return}if(e.destroyed)break}if(e.destroyed)return;let P=z(N),S;try{S=we(P),S.length===0&&m.size>0&&(S=we({output:m.items()}))}catch(l){B(e,502,"api_error",String(l instanceof Error?l.message:l));return}let M=Q(c,S.length,h);if(M){B(e,502,"api_error",X(d,M));return}let E=[],$=O||Ke(P);$&&E.push({type:"thinking",thinking:$}),(h||S.length===0)&&E.push({type:"text",text:h}),E.push(...S),q(e,200,{id:a,type:"message",role:"assistant",content:E,model:r,stop_reason:S.length>0?"tool_use":"end_turn",usage:ce(P)??{input_tokens:0,output_tokens:0}})}function Dt(t){let{clients:n,apiKey:e,identity:o}=t,s=new ve,r=new ke,a=ct((u,f)=>{let d=new URL(u.url??"/","http://localhost"),c=d.pathname==="/v1/messages"||d.pathname.startsWith("/v1/messages/"),g=(p,h,O,N)=>c?B(f,p,N,h):F(f,p,h,O);(async()=>{if(u.method==="GET"&&d.pathname==="/healthz"){q(f,200,{ok:!0});return}if(u.method==="GET"&&d.pathname==="/stats"){q(f,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(e&&(u.headers.authorization??"")!==`Bearer ${e}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}if(u.method==="GET"&&d.pathname==="/v1/models"){q(f,200,await n.listModels());return}if(u.method!=="POST"){g(404,`no route for ${u.method} ${d.pathname}`,"invalid_request_error","not_found_error");return}let p;try{p=await ft(u)}catch(O){if(O instanceof le){g(413,O.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let h=Buffer.byteLength(JSON.stringify(p));if(d.pathname==="/v1/responses"){r.request("responses",h,h),await vt(p,n,s,f,r);return}if(d.pathname==="/v1/chat/completions"){r.request("chat_completions",h,h),await xt(p,n,f,r);return}if(d.pathname==="/v1/messages"){r.request("messages",h,h),await Ot(p,n,f,r);return}if(d.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",h,h),B(f,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}g(404,`no route for POST ${d.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let h=String(p instanceof Error?p.message:p);if(!f.headersSent){g(500,h,"proxy_error","api_error");return}f.destroyed||(c?f.write(`event: error
37
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
38
-
39
- `):f.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
40
-
41
- `)),f.end()})});return Fe(a,{clients:n,apiKey:e}),a}export{Ce as a,Dt as b};
@@ -1 +0,0 @@
1
- async function a(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}async function i(t){return{object:"list",data:(await a(t)).map(e=>({id:`${e.model_id}:${e.variant}`,object:"model",created:0,owned_by:"urun"}))}}export{a,i as b};
@@ -1 +0,0 @@
1
- function g(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let n=e,r=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:r.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}function _(e,n,r,t){let o=e.response??{},i={request_id:r,consumer_id:t,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function f(e,n,r){let t={request_id:n,consumer_id:r,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(t.model=e.model),e.tools!==void 0&&(t.tools=e.tools),e.tool_choice!==void 0&&(t.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(t.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(t.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(t.chat_template_kwargs=e.chat_template_kwargs),t}var w="llm-resp";async function*d(e,n){let r=`${w}:${n}`,t=`resp_${n}`;yield{type:"response.created",response:{id:t,status:"in_progress"}};let o=new Map;for await(let i of e.stream(r).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:t,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:t,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let p=typeof a.index=="number"?a.index:0,u=o.get(p)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(p,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${p}`,tool_index:p,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:t,status:"completed",...s.body}};return}else if(s.t==="error"){yield g(s);return}}}var b="llm",m=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(b).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,r){let t=f(n,r,this.consumerId);return this.write(t),d(this.session,r)}sendResponseCreate(n,r,t){let o=_(n,r,t,this.consumerId);return this.write(o),d(this.session,t)}};var y=0;function h(){return y+=1,`req_${Date.now().toString(36)}_${y.toString(36)}`}var k=class{transport;constructor(n){this.transport=new m(n)}responses={create:async n=>{let r=h(),t=this.transport.sendResponses(n,r);return Object.assign((async function*(){yield*t})(),{requestId:r})}}};export{g as a,m as b,k as c};
@@ -1 +0,0 @@
1
- var l=class{constructor(n,e){this.backend=n;this.opts=e}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let e=Buffer.from(n,"base64"),t=Math.floor(e.byteLength/2),a=new Int16Array(t);for(let o=0;o<t;o++)a[o]=e.readInt16LE(o*2);this.source.onData(a)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=e=>{let t=Buffer.from(e.samples.buffer,e.samples.byteOffset,e.samples.byteLength).toString("base64");for(let a of this.outHandlers)a(t)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function R(r,n,e=1e4){let t=new l(n,{sampleRate:24e3}),a=await t.startOutbound();await r.stream("rt-audio-in").attach(a);let o=await h(r,e);return await t.startInbound(o),t}function h(r,n){let e=r.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((t,a)=>{let o,i=setTimeout(()=>{o?.(),a(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),u=s=>{s!=null&&(clearTimeout(i),o?.(),t(s))};o=e.on?.("track",u),e.track!=null&&u(e.track)})}var m="rt-video-in",p=256e3;function E(r){let n=r.stream(m),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${m}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async t=>{if(t.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(t.byteLength>p)throw new Error(`enableSessionVideo: frame is ${t.byteLength} bytes \u2014 over the ${p}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await e.call(n,t)}}}var S=24e3,d=480,y=111;async function v(){let r=await import("opusscript"),n=r.default??r;return new n(S,1,2048)}async function g(){let r=await import("werift"),n=await v();return{createSource:()=>{let e=new r.MediaStreamTrack({kind:"audio"}),t=Math.random()*4294967295>>>0,a=Math.random()*65535&65535,o=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:e,onData:u=>{let s=new Int16Array(i.length+u.length);s.set(i,0),s.set(u,i.length);let c=0;for(;s.length-c>=d;){let f=s.subarray(c,c+d);c+=d;let k=Buffer.from(f.buffer,f.byteOffset,f.byteLength),w=n.encode(k,d);a=a+1&65535,o=o+d>>>0;let A=new r.RtpHeader({version:2,payloadType:y,sequenceNumber:a,timestamp:o,ssrc:t,marker:!1}),b=new r.RtpPacket(A,w);e.writeRtp(b)}i=s.slice(c)}}},createSink:e=>{let t={onframe:null};return e.onReceiveRtp.subscribe(o=>{let i;try{i=n.decode(o.payload)}catch{return}let u=new Int16Array(i.length/2);for(let s=0;s<u.length;s++)u[s]=i.readInt16LE(s*2);t.onframe?.({samples:u})}),t}}}async function P(){let r=await import("@roamhq/wrtc");return{createSource:()=>{let n=new r.nonstandard.RTCAudioSource;return{track:n.createTrack(),onData:t=>n.onData({samples:t,sampleRate:24e3})}},createSink:n=>{let e={onframe:null},t=new r.nonstandard.RTCAudioSink(n);return t.ondata=a=>{e.onframe?.(a)},e}}}export{R as a,E as b,g as c,P as d};
@@ -1 +0,0 @@
1
- var v="https://api.urun.sh/v1";function c(o){return o.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var a=class extends Error{},p=class extends Error{},u="urs1.";function f(o,e){return u+Buffer.from(JSON.stringify([o,e]),"utf8").toString("base64url")}function g(o){if(!o.startsWith(u))return null;try{let e=JSON.parse(Buffer.from(o.slice(u.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function A(o){let e=o.fetchImpl??fetch,t=`${o.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(t,{headers:{Authorization:`Bearer ${o.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${s.status}`);let i=await s.json();if(!Array.isArray(i.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(i.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${i.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return i.apps}var y=6e4,h=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??y;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let t=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:t},t}servable(e){return e.filter(t=>t.function_name===this.opts.fnName&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=new Set([this.opts.defaultApp]);if(this.opts.listApps)for(let t of this.servable(await this.deployedApps()))e.add(t);for(let t of this.pool.keys())e.add(t);return[this.opts.defaultApp,...[...e].filter(t=>t!==this.opts.defaultApp).sort()]}async resolveApp(e){let t=(e??"").trim();if(!t||t==="urun")return this.opts.defaultApp;let s=c(t);if(s===this.opts.defaultApp)return this.opts.defaultApp;if(this.pool.has(s))return s;if(this.opts.listApps){let i=await this.deployedApps(),r=this.servable(i);if(r.includes(s))return s;let n=r.filter(d=>d.startsWith(`${s}-`));if(n.length===1)return n[0];if(n.length>1)throw new a(`model "${t}" is ambiguous across deployed apps ${n.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===s||d.app_slug.startsWith(`${s}-`));if(l)throw new a(`model "${t}" maps to app "${l.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let r=(await this.opts.listCatalog()).find(n=>t===n.model_id||t===`${n.model_id}:${n.variant}`||s===c(n.model_id)||s===c(`${n.model_id}-${n.variant}`));if(r)throw new a(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${r.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return this.opts.defaultApp}async sessionFor(e){let t=await this.resolveApp(e),s=this.pool.get(t);return s||(s=Promise.resolve(this.opts.openSession(t)),this.pool.set(t,s),s.catch(()=>this.pool.delete(t))),{app:t,entry:await s}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let s=t(e);if(typeof s!="string"||s.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return s}async handleFor(e){let{app:t,entry:s}=await this.sessionFor(e);return{app:t,handle:f(t,this.keyOf(s))}}async sessionForHandle(e){let t=g(e);if(!t)throw new p(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:s,key:i}=t,r=this.pool.get(s),n=r?await r.then(l=>l,()=>null):null;if(n===null)throw new p(`the session behind this handle (app "${s}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(n)!==i)throw new p(`the session behind this handle (app "${s}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:s,entry:n}}async evict(e,t){let s=this.pool.get(e);!s||await s.then(r=>r,()=>null)!==t||this.pool.get(e)!==s||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(t=>({id:t,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let e=[...this.pool.values()];this.pool.clear();let t=[];if(await Promise.all(e.map(async s=>{try{await this.opts.closeSession(await s)}catch(i){t.push(String(i instanceof Error?i.message:i))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{v as a,a as b,p as c,A as d,h as e};