Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/retell-execution-tracing.md
Original file line number Diff line number Diff line change
@@ -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.
26 changes: 26 additions & 0 deletions js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions js/src/auto-instrumentations/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -50,6 +51,7 @@ interface InstrumentationConfigGroup {

const defaultInstrumentationConfigGroups: readonly InstrumentationConfigGroup[] =
[
{ integrations: ["retell"], configs: retellConfigs },
{ integrations: ["openai"], configs: openaiConfigs },
{
integrations: ["openaiCodexSDK"],
Expand Down
28 changes: 28 additions & 0 deletions js/src/auto-instrumentations/configs/retell.ts
Original file line number Diff line number Diff line change
@@ -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 },
})),
);
1 change: 1 addition & 0 deletions js/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,4 @@ export { wrapDeepgram } from "./wrappers/deepgram";
export { wrapElevenLabs } from "./wrappers/elevenlabs";

export { wrapFal } from "./wrappers/fal";
export { wrapRetell } from "./wrappers/retell";
3 changes: 3 additions & 0 deletions js/src/instrumentation/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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",
Expand Down
5 changes: 5 additions & 0 deletions js/src/instrumentation/instrumentation-consumers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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,
}));
Expand Down Expand Up @@ -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]],
Expand Down
2 changes: 2 additions & 0 deletions js/src/instrumentation/instrumentation-consumers.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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();
Expand Down
246 changes: 246 additions & 0 deletions js/src/instrumentation/providers/retell-instrumentation.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof _exportsForTestingOnly.useTestBackgroundLogger>;
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<string, any>[];
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<unknown> | undefined;
const parse = () => (parsed ??= response.json());
const promise = {
then: Promise.resolve<unknown>(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");
},
);
});
Loading