diff --git a/.changeset/retell-execution-tracing.md b/.changeset/retell-execution-tracing.md new file mode 100644 index 000000000..2c7670c78 --- /dev/null +++ b/.changeset/retell-execution-tracing.md @@ -0,0 +1,5 @@ +--- +"braintrust": minor +--- + +Add Retell SDK call and chat execution tracing, automatic instrumentation, and the `wrapRetell` helper. Preserve lazy response helpers and omit web-call credentials from trace payloads. diff --git a/js/README.md b/js/README.md index 18b88b51d..1a504acb4 100644 --- a/js/README.md +++ b/js/README.md @@ -150,6 +150,32 @@ BRAINTRUST_DISABLE_INSTRUMENTATION=langsmith node --import braintrust/hook.mjs a When Braintrust LangChain/LangGraph instrumentation is enabled, LangSmith runs serialized by LangChain are ignored to avoid duplicate spans. Set `langchain: false` (and use LangSmith instrumentation) when LangSmith should be the source for those runs instead. +### Retell AI + +Retell SDK `>=6.2.22 <7` is supported by the Node.js hook and bundler plugins. +For explicit instrumentation, wrap a client: + +```typescript +import Retell from "retell-sdk"; +import { wrapRetell } from "braintrust"; + +const client = wrapRetell(new Retell()); +``` + +This traces `call.createPhoneCall`, `call.createWebCall`, `call.retrieve`, +`chat.create`, and `chat.createChatCompletion`. Call creation and retrieval are +task spans measuring the API request, not the lifetime of the voice conversation. +Chat completion records returned text messages. Retrieved call transcripts record +text; recordings are not downloaded. Tokens, transport credentials, phone numbers, +request options and arbitrary metadata are omitted. + +The original SDK promise is retained. Its response helpers wait for tracing to +read a cloned body before parsing or returning the application's response, as in +the TypeSafe integration. `.asResponse()` retains an unread response body. + +Disable with `configureInstrumentation({ integrations: { retell: false } })` +before registration, or `BRAINTRUST_DISABLE_INSTRUMENTATION=retell`. + ## Migration Guides ### Upgrading from 3.x to 4.x diff --git a/js/src/auto-instrumentations/configs/all.ts b/js/src/auto-instrumentations/configs/all.ts index 2e1b59609..c70ce88f6 100644 --- a/js/src/auto-instrumentations/configs/all.ts +++ b/js/src/auto-instrumentations/configs/all.ts @@ -36,6 +36,7 @@ import { piCodingAgentConfigs } from "./pi-coding-agent"; import { strandsAgentSDKConfigs } from "./strands-agent-sdk"; import { deepgramConfigs } from "./deepgram"; import { falConfigs } from "./fal"; +import { retellConfigs } from "./retell"; import { elevenLabsConfigs } from "./elevenlabs"; import { voyageAIConfigs } from "./voyageai"; import { mcpConfigs } from "./mcp"; @@ -50,6 +51,7 @@ interface InstrumentationConfigGroup { const defaultInstrumentationConfigGroups: readonly InstrumentationConfigGroup[] = [ + { integrations: ["retell"], configs: retellConfigs }, { integrations: ["openai"], configs: openaiConfigs }, { integrations: ["openaiCodexSDK"], diff --git a/js/src/auto-instrumentations/configs/retell.ts b/js/src/auto-instrumentations/configs/retell.ts new file mode 100644 index 000000000..7feabfd2b --- /dev/null +++ b/js/src/auto-instrumentations/configs/retell.ts @@ -0,0 +1,28 @@ +import type { InstrumentationConfig } from "../orchestrion-js"; +import { retellChannels } from "../../instrumentation/providers/retell-interceptors"; + +export const retellConfigs: InstrumentationConfig[] = ["js", "mjs"].flatMap( + (extension) => + ( + [ + ["call", "Call", "createPhoneCall", retellChannels.createPhoneCall], + ["call", "Call", "createWebCall", retellChannels.createWebCall], + ["call", "Call", "retrieve", retellChannels.retrieveCall], + ["chat", "Chat", "create", retellChannels.createChat], + [ + "chat", + "Chat", + "createChatCompletion", + retellChannels.createChatCompletion, + ], + ] as const + ).map(([resource, className, methodName, hook]) => ({ + channelName: hook.channelName, + module: { + name: "retell-sdk", + versionRange: ">=6.2.22 <7.0.0", + filePath: `resources/${resource}.${extension}`, + }, + functionQuery: { className, methodName }, + })), +); diff --git a/js/src/exports.ts b/js/src/exports.ts index 5760310e6..7dfea1450 100644 --- a/js/src/exports.ts +++ b/js/src/exports.ts @@ -166,3 +166,4 @@ export { wrapDeepgram } from "./wrappers/deepgram"; export { wrapElevenLabs } from "./wrappers/elevenlabs"; export { wrapFal } from "./wrappers/fal"; +export { wrapRetell } from "./wrappers/retell"; diff --git a/js/src/instrumentation/config.ts b/js/src/instrumentation/config.ts index 0e11588ef..32ddee5f1 100644 --- a/js/src/instrumentation/config.ts +++ b/js/src/instrumentation/config.ts @@ -61,6 +61,7 @@ export interface InstrumentationIntegrationsConfig { deepgram?: boolean; fal?: boolean; elevenlabs?: boolean; + retell?: boolean; /** Set to false to disable, or pass options; options keep LiveKit enabled. */ livekit?: boolean | LiveKitIntegrationConfig; /** Set to false to disable, or pass options; options keep MCP enabled. */ @@ -264,6 +265,8 @@ const envIntegrationAliases: Record< fal: "fal", "@fal-ai/client": "fal", elevenlabs: "elevenlabs", + retell: "retell", + "retell-sdk": "retell", "@elevenlabs/elevenlabs-js": "elevenlabs", livekit: "livekit", "@livekit/agents": "livekit", diff --git a/js/src/instrumentation/instrumentation-consumers.test.ts b/js/src/instrumentation/instrumentation-consumers.test.ts index cacdc7b08..64db32571 100644 --- a/js/src/instrumentation/instrumentation-consumers.test.ts +++ b/js/src/instrumentation/instrumentation-consumers.test.ts @@ -13,6 +13,7 @@ const registrations = vi.hoisted(() => ({ cloudflareThink: vi.fn(), cohere: vi.fn(), fal: vi.fn(), + retell: vi.fn(), cursorSDK: vi.fn(), genkit: vi.fn(), gitHubCopilot: vi.fn(), @@ -59,6 +60,9 @@ vi.mock("./providers/cloudflare-think-instrumentation", () => ({ vi.mock("./providers/fal-instrumentation", () => ({ registerFalInstrumentation: registrations.fal, })); +vi.mock("./providers/retell-instrumentation", () => ({ + registerRetellInstrumentation: registrations.retell, +})); vi.mock("./providers/cohere-instrumentation", () => ({ registerCohereInstrumentation: registrations.cohere, })); @@ -141,6 +145,7 @@ const integrationCases: Array< ["cloudflareThink", [registrations.cloudflareThink]], ["cohere", [registrations.cohere]], ["fal", [registrations.fal]], + ["retell", [registrations.retell]], ["cursorSDK", [registrations.cursorSDK]], ["genkit", [registrations.genkit]], ["gitHubCopilot", [registrations.gitHubCopilot]], diff --git a/js/src/instrumentation/instrumentation-consumers.ts b/js/src/instrumentation/instrumentation-consumers.ts index 30877b391..acff96362 100644 --- a/js/src/instrumentation/instrumentation-consumers.ts +++ b/js/src/instrumentation/instrumentation-consumers.ts @@ -1,4 +1,5 @@ import { registerInstrumentation as fal } from "./registrations/fal"; +import { registerInstrumentation as retell } from "./registrations/retell"; import { registerInstrumentation as mcpHandler } from "./registrations/mcpHandler"; import { registerInstrumentation as fastmcp } from "./registrations/fastmcp"; import { registerInstrumentation as mcp } from "./registrations/mcp"; @@ -40,6 +41,7 @@ import { registerInstrumentation as mastra } from "./registrations/mastra"; /** Register every enabled provider. Only explicit auto setup imports this module. */ export function registerInstrumentationConsumers(): void { + retell(); mcp(); mcpHandler(); fastmcp(); diff --git a/js/src/instrumentation/providers/retell-instrumentation.test.ts b/js/src/instrumentation/providers/retell-instrumentation.test.ts new file mode 100644 index 000000000..2f9c7d6e2 --- /dev/null +++ b/js/src/instrumentation/providers/retell-instrumentation.test.ts @@ -0,0 +1,246 @@ +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vite-plus/test"; +import { _exportsForTestingOnly } from "../../logger/testing"; +import { currentSpan, initLogger, traced } from "../../logger/core"; +import { configureNode } from "../../node/config"; +import { wrapRetell } from "../../wrappers/retell"; +import { retellChannels } from "./retell-interceptors"; + +configureNode(); + +describe("Retell execution instrumentation", () => { + let logger: ReturnType; + beforeAll(async () => { + await _exportsForTestingOnly.simulateLoginForTests(); + }); + beforeEach(() => { + logger = _exportsForTestingOnly.useTestBackgroundLogger(); + initLogger({ projectName: "tmp-retell", projectId: "test-project-id" }); + }); + afterEach(() => { + _exportsForTestingOnly.clearTestBackgroundLogger(); + }); + + it.each([ + ["call", "createPhoneCall"], + ["call", "createWebCall"], + ["call", "retrieve"], + ["chat", "create"], + ["chat", "createChatCompletion"], + ] as const)( + "preserves %s.%s calls, promises and errors", + async (resource, method) => { + const request = { agent_id: "agent", chat_id: "chat", content: "Hello" }; + const options = { headers: { Authorization: "sentinel-auth-secret" } }; + const output = { + call_id: "call", + messages: [{ role: "agent", content: "Hi" }], + }; + const promise = Object.assign(Promise.resolve(output), { + asResponse: () => "helper", + }); + const error = new Error("provider failure"); + let mode = "success"; + const target = { + [method]: vi.fn(function ( + this: unknown, + input: unknown, + opts?: unknown, + ) { + expect(this).toBe(target); + expect(input).toBe(request); + expect(opts).toBe(options); + expect(currentSpan().id).toBeTruthy(); + if (mode === "throw") throw error; + if (mode === "reject") return Promise.reject(error); + return promise; + }), + }; + const raw = { + call: {}, + chat: {}, + agent: { untouched: true }, + [resource]: target, + }; + const wrapped = wrapRetell(raw); + expect(wrapRetell(raw)).toBe(wrapped); + expect(wrapRetell(wrapped)).toBe(wrapped); + expect(wrapped.agent).toBe(raw.agent); + const invoke = () => + (wrapped[resource] as typeof target)[method](request, options); + expect(invoke()).toBe(promise); + expect(promise.asResponse()).toBe("helper"); + expect(await promise).toBe(output); + mode = "throw"; + expect(invoke).toThrow(error); + mode = "reject"; + await expect(invoke()).rejects.toBe(error); + expect(target[method]).toHaveBeenCalledTimes(3); + const rows = await logger.drain(); + expect(rows).toHaveLength(3); + expect(JSON.stringify(rows)).not.toContain("sentinel-auth-secret"); + for (const row of rows) + expect(row).toMatchObject({ metrics: { end: expect.any(Number) } }); + }, + ); + + it("omits web-call credentials without changing the response", async () => { + const response = Object.freeze({ + call_id: "call", + agent_id: "agent", + access_token: "sentinel-access-token", + ice_servers: [{ credential: "sentinel-ice-password" }], + metadata: { api_key: "sentinel-metadata-secret" }, + }); + const raw = { + call: { createWebCall: async (_: unknown) => response }, + chat: {}, + }; + const wrapped = wrapRetell(raw); + expect( + await wrapped.call.createWebCall({ + agent_id: "agent", + api_key: "sentinel-request-secret", + }), + ).toBe(response); + const rows = await logger.drain(); + expect(rows).toMatchObject([ + { + input: { agent_id: "agent" }, + output: { call_id: "call", agent_id: "agent" }, + }, + ]); + expect(JSON.stringify(rows)).not.toContain("sentinel-"); + expect(response.access_token).toBe("sentinel-access-token"); + }); + + it("captures completed-call transcript text without recording URLs or phone numbers", async () => { + const response = { + call_id: "call", + call_status: "ended", + transcript_object: [ + { role: "agent", content: "Hello", words: [{ word: "Hello" }] }, + ], + recording_url: "sentinel-signed-recording-url", + to_number: "sentinel-phone-number", + }; + const wrapped = wrapRetell({ + call: { retrieve: async (_: string) => response }, + chat: {}, + }); + await wrapped.call.retrieve("call"); + const rows = await logger.drain(); + expect(rows).toMatchObject([ + { + input: { call_id: "call" }, + output: { + call_id: "call", + call_status: "ended", + messages: [{ role: "assistant", content: "Hello" }], + }, + span_attributes: { name: "retell.call.retrieve", type: "task" }, + }, + ]); + expect(JSON.stringify(rows)).not.toContain("sentinel-"); + }); + + it("parents API spans to the current trace and avoids manual/auto duplication", async () => { + const response = { call_id: "call" }; + const raw = { + call: { + createWebCall(request: unknown) { + return retellChannels.createWebCall.invoke( + async () => response, + this, + [request], + {}, + ); + }, + }, + chat: {}, + }; + await traced( + async () => wrapRetell(raw).call.createWebCall({ agent_id: "agent" }), + { name: "parent" }, + ); + const rows = (await logger.drain()) as Record[]; + expect(rows).toHaveLength(2); + const parent = rows.find((row) => row.span_attributes?.name === "parent"); + const child = rows.find( + (row) => row.span_attributes?.name === "retell.call.createWebCall", + ); + expect(child).toMatchObject({ span_parents: [parent?.span_id] }); + }); + + it("retains resource receivers for uninstrumented methods", () => { + class Calls { + #value = "private"; + untouched() { + return this.#value; + } + } + const raw = { call: new Calls(), chat: {} }; + expect(wrapRetell(raw).call.untouched()).toBe("private"); + }); + + it.each(["await", "withResponse", "asResponse"])( + "preserves lazy SDK response parsing for %s consumers", + async (mode) => { + const response = new Response( + JSON.stringify({ call_id: "call", access_token: "sentinel-token" }), + { headers: { "content-type": "application/json" } }, + ); + let parsed: Promise | undefined; + const parse = () => (parsed ??= response.json()); + const promise = { + then: Promise.resolve(undefined).then, + asResponse: () => Promise.resolve(response), + withResponse: async () => ({ data: await parse(), response }), + }; + for (const key of ["then", "catch", "finally"] as const) { + Object.defineProperty(promise, key, { + configurable: true, + writable: true, + value: (...args: unknown[]) => + Reflect.apply(parse()[key], parse(), args), + }); + } + const client = wrapRetell({ + call: { createWebCall: () => promise }, + chat: {}, + }); + const result = client.call.createWebCall(); + expect(result).toBe(promise); + if (mode === "asResponse") { + const raw = await result.asResponse(); + expect(raw.bodyUsed).toBe(false); + expect(await raw.json()).toEqual({ + call_id: "call", + access_token: "sentinel-token", + }); + } else if (mode === "withResponse") { + expect((await result.withResponse()).data).toEqual({ + call_id: "call", + access_token: "sentinel-token", + }); + } else { + expect(await result).toEqual({ + call_id: "call", + access_token: "sentinel-token", + }); + } + const rows = await logger.drain(); + expect(rows).toMatchObject([ + { output: { call_id: "call" }, metrics: { end: expect.any(Number) } }, + ]); + expect(JSON.stringify(rows)).not.toContain("sentinel-token"); + }, + ); +}); diff --git a/js/src/instrumentation/providers/retell-instrumentation.ts b/js/src/instrumentation/providers/retell-instrumentation.ts new file mode 100644 index 000000000..120541994 --- /dev/null +++ b/js/src/instrumentation/providers/retell-instrumentation.ts @@ -0,0 +1,110 @@ +import { isObject } from "../../../util"; +import { INSTRUMENTATION_NAMES } from "../../span-origin"; +import { traceAsyncCall } from "../core/tracing"; +import { runInstrumentation } from "../core/observe-result"; +import { + isAutoInstrumentationSuppressed, + runWithAutoInstrumentationSuppressed, +} from "../auto-instrumentation-suppression"; +import { retellChannels } from "./retell-interceptors"; +import { observeRetellResponse } from "../../wrappers/retell-promise"; + +function pick( + value: unknown, + keys: readonly string[], +): Record { + if (!isObject(value)) return {}; + return Object.fromEntries( + keys.flatMap((key) => { + const field = value[key]; + return typeof field === "string" || + typeof field === "number" || + typeof field === "boolean" + ? [[key, field]] + : []; + }), + ); +} + +function messages(value: unknown): unknown[] | undefined { + if (!Array.isArray(value)) return undefined; + return value.filter(isObject).flatMap((message) => + typeof message.content === "string" && typeof message.role === "string" + ? [ + { + role: message.role === "agent" ? "assistant" : message.role, + content: message.content, + }, + ] + : [], + ); +} + +export function registerRetellInstrumentation(): void { + for (const [key, name] of [ + ["createPhoneCall", "call.createPhoneCall"], + ["createWebCall", "call.createWebCall"], + ["retrieveCall", "call.retrieve"], + ["createChat", "chat.create"], + ["createChatCompletion", "chat.createChatCompletion"], + ] as const) { + const hook = retellChannels[key]; + hook.intercept((target, self, args, additional) => { + if (isAutoInstrumentationSuppressed()) + return Reflect.apply(target, self, args); + let result: PromiseLike; + traceAsyncCall( + () => { + result = runWithAutoInstrumentationSuppressed(() => + Reflect.apply(target, self, args), + ); + return ( + runInstrumentation(() => observeRetellResponse(result)) ?? + Promise.resolve(undefined) + ); + }, + { ...additional, arguments: args, self }, + { + name: `retell.${name}`, + instrumentationName: INSTRUMENTATION_NAMES.RETELL, + // Session creation and retrieval measure API work, not a voice conversation. + type: key === "createChatCompletion" ? "llm" : "task", + extractInput: ([request]) => ({ + input: + typeof request === "string" + ? { call_id: request } + : pick(request, [ + "agent_id", + "agent_version", + "chat_id", + "content", + ]), + metadata: { provider: "retell" }, + }), + extractOutput: (result) => { + if (!isObject(result)) return undefined; + if (key === "createChatCompletion") + return messages(result.messages); + const output = pick(result, [ + "call_id", + "chat_id", + "agent_id", + "agent_version", + "call_type", + "call_status", + "chat_status", + ]); + if (key === "retrieveCall") { + const transcript = messages(result.transcript_object); + if (transcript) output.messages = transcript; + } + // In particular, web-call access tokens and transport credentials stay out. + return output; + }, + extractMetrics: () => ({}), + }, + ); + return result!; + }); + } +} diff --git a/js/src/instrumentation/providers/retell-interceptors.ts b/js/src/instrumentation/providers/retell-interceptors.ts new file mode 100644 index 000000000..9dcb112e1 --- /dev/null +++ b/js/src/instrumentation/providers/retell-interceptors.ts @@ -0,0 +1,20 @@ +import { channel, defineInterceptor } from "../core/interceptor-definitions"; +import type { RetellArgs } from "../../vendor-sdk-types/retell"; + +export const retellChannels = defineInterceptor("retell-sdk", { + createPhoneCall: channel>({ + channelName: "call.createPhoneCall", + }), + createWebCall: channel>({ + channelName: "call.createWebCall", + }), + retrieveCall: channel>({ + channelName: "call.retrieve", + }), + createChat: channel>({ + channelName: "chat.create", + }), + createChatCompletion: channel>({ + channelName: "chat.createChatCompletion", + }), +}); diff --git a/js/src/instrumentation/registrations/retell.ts b/js/src/instrumentation/registrations/retell.ts new file mode 100644 index 000000000..da0da7925 --- /dev/null +++ b/js/src/instrumentation/registrations/retell.ts @@ -0,0 +1,6 @@ +import { registerRetellInstrumentation } from "../providers/retell-instrumentation"; +import { registry } from "../registry"; + +export function registerInstrumentation(): void { + registry.register("retell", registerRetellInstrumentation); +} diff --git a/js/src/span-origin.ts b/js/src/span-origin.ts index 9c1063512..ab46ffb42 100644 --- a/js/src/span-origin.ts +++ b/js/src/span-origin.ts @@ -52,6 +52,7 @@ export const INSTRUMENTATION_NAMES = { DEEPGRAM: "deepgram", FAL: "fal", ELEVENLABS: "elevenlabs", + RETELL: "retell", } as const; export type SpanInstrumentationName = @@ -93,9 +94,7 @@ export function getSpanInstrumentationName( if (typeof args !== "object" || args === null) { return undefined; } - const value = (args as InternalSpanInstrumentationName)[ - INTERNAL_SPAN_INSTRUMENTATION_NAME - ]; + const value: unknown = Reflect.get(args, INTERNAL_SPAN_INSTRUMENTATION_NAME); return isSpanInstrumentationName(value) ? value : undefined; } diff --git a/js/src/vendor-sdk-types/retell.ts b/js/src/vendor-sdk-types/retell.ts new file mode 100644 index 000000000..45f09274d --- /dev/null +++ b/js/src/vendor-sdk-types/retell.ts @@ -0,0 +1 @@ +export type RetellArgs = [request: unknown, options?: unknown]; diff --git a/js/src/wrappers/retell-promise.ts b/js/src/wrappers/retell-promise.ts new file mode 100644 index 000000000..c2140198e --- /dev/null +++ b/js/src/wrappers/retell-promise.ts @@ -0,0 +1,56 @@ +import { isObject } from "../../util"; + +/** Observe Retell's raw response without consuming the caller's body. */ +export function observeRetellResponse( + result: PromiseLike, +): PromiseLike { + if ( + !isObject(result) || + typeof result.asResponse !== "function" || + typeof result.withResponse !== "function" + ) + return result; + const helpers = new Map unknown>(); + for (const key of [ + "then", + "catch", + "finally", + "asResponse", + "withResponse", + ]) { + const method = Reflect.get(result, key); + if (typeof method !== "function") return Promise.resolve(undefined); + helpers.set(key, (...args: unknown[]) => + Reflect.apply(method, result, args), + ); + } + const captured = Promise.resolve( + Reflect.apply(helpers.get("asResponse")!, result, []), + ).then((response: unknown) => { + if (!(response instanceof Response)) return undefined; + try { + return response + .clone() + .json() + .catch(() => undefined); + } catch { + return undefined; + } + }); + // As in the TypeSafe integration, wait before the SDK parses the original + // body. Raw-response callers can then read it, and flush sees the completed + // trace. Keep the SDK promise itself and every original helper result/error. + const settled = captured.then( + () => undefined, + () => undefined, + ); + for (const [key, method] of helpers) { + Object.defineProperty(result, key, { + configurable: true, + writable: true, + value: (...args: unknown[]) => + settled.then(() => Reflect.apply(method, result, args)), + }); + } + return captured; +} diff --git a/js/src/wrappers/retell.ts b/js/src/wrappers/retell.ts new file mode 100644 index 000000000..137273ac4 --- /dev/null +++ b/js/src/wrappers/retell.ts @@ -0,0 +1,59 @@ +import { isObject } from "../../util"; +import { debugLogger } from "../debug-logger"; +import { retellChannels } from "../instrumentation/providers/retell-interceptors"; +import { registerInstrumentation } from "../instrumentation/registrations/retell"; +import type { RetellArgs } from "../vendor-sdk-types/retell"; + +const clients = new WeakMap(); + +/** Trace Retell SDK 6.2.22+ call and chat execution requests. */ +export function wrapRetell(client: T): T; +export function wrapRetell(client: unknown): unknown { + registerInstrumentation(); + if (!isObject(client) || !isObject(client.call) || !isObject(client.chat)) { + debugLogger.notice.warn("Unsupported Retell client. Not wrapping."); + return client; + } + const cached = clients.get(client); + if (cached) return cached; + const wrapResource = ( + resource: Record, + kind: "call" | "chat", + ) => + new Proxy(resource, { + get(target, key) { + const value = Reflect.get(target, key, target); + if (typeof value !== "function") return value; + const hook = + kind === "call" + ? key === "createPhoneCall" + ? retellChannels.createPhoneCall + : key === "createWebCall" + ? retellChannels.createWebCall + : key === "retrieve" + ? retellChannels.retrieveCall + : undefined + : key === "create" + ? retellChannels.createChat + : key === "createChatCompletion" + ? retellChannels.createChatCompletion + : undefined; + return hook + ? (...args: RetellArgs) => hook.invoke(value, target, args, {}) + : value.bind(target); + }, + }); + const call = wrapResource(client.call, "call"); + const chat = wrapResource(client.chat, "chat"); + const wrapped = new Proxy(client, { + get(target, key) { + if (key === "call") return call; + if (key === "chat") return chat; + const value = Reflect.get(target, key, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + clients.set(client, wrapped); + clients.set(wrapped, wrapped); + return wrapped; +}