From 2adec5ada39a67f7f809c15231a80a2b2f503105 Mon Sep 17 00:00:00 2001 From: pear1-pea <3435565952@qq.com> Date: Sat, 21 Nov 2026 23:57:09 +0800 Subject: [PATCH] feat: instrument Inngest AgentKit execution --- .changeset/agentkit-execution-tracing.md | 5 + js/README.md | 26 ++ .../configs/agent-kit.ts | 27 ++ js/src/auto-instrumentations/configs/all.ts | 2 + js/src/instrumentation/config.ts | 4 + .../instrumentation-consumers.test.ts | 5 + .../instrumentation-consumers.ts | 2 + .../agent-kit-instrumentation.test.ts | 298 ++++++++++++++++++ .../providers/agent-kit-instrumentation.ts | 146 +++++++++ .../providers/agent-kit-interceptors.ts | 31 ++ .../instrumentation/registrations/agentKit.ts | 6 + js/src/span-origin.ts | 5 +- js/src/wrappers/agent-kit-tools.ts | 50 +++ 13 files changed, 604 insertions(+), 3 deletions(-) create mode 100644 .changeset/agentkit-execution-tracing.md create mode 100644 js/src/auto-instrumentations/configs/agent-kit.ts create mode 100644 js/src/instrumentation/providers/agent-kit-instrumentation.test.ts create mode 100644 js/src/instrumentation/providers/agent-kit-instrumentation.ts create mode 100644 js/src/instrumentation/providers/agent-kit-interceptors.ts create mode 100644 js/src/instrumentation/registrations/agentKit.ts create mode 100644 js/src/wrappers/agent-kit-tools.ts diff --git a/.changeset/agentkit-execution-tracing.md b/.changeset/agentkit-execution-tracing.md new file mode 100644 index 000000000..ed63ae14a --- /dev/null +++ b/.changeset/agentkit-execution-tracing.md @@ -0,0 +1,5 @@ +--- +"braintrust": minor +--- + +Add automatic instrumentation for Inngest AgentKit 0.13.2 network, agent, model, routing and tool execution. diff --git a/js/README.md b/js/README.md index 18b88b51d..bb083c935 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. +### Inngest AgentKit + +The Node.js hook and bundler plugins support `@inngest/agent-kit@0.13.2`. +Initialize Braintrust logging as usual and load the hook before AgentKit: + +```bash +node --import braintrust/hook.mjs app.js +``` + +Network runs contain routing and agent task spans; agents contain model-inference +and tool spans. Names stay stable across calls, with agent, network and tool names +in metadata. Model traces capture parsed output and reported OpenAI-compatible +token usage, without copying the raw provider response or model credentials. + +Tools created by `createTool` are prepared when created. Plain tools, Inngest +function tools and MCP tools are also prepared immediately before invocation. +Tool objects and call receivers are retained. Already immutable handlers and +accessor-based handlers are left unchanged; those tools may lack individual spans. +Freezing a tool after `createTool` remains supported. Instrumentation uses the +published ESM chunk and CommonJS entrypoint; other versions are not enabled until +their compiled layouts are validated. This integration currently exposes automatic +instrumentation, without a separate module wrapper API. + +Disable with `configureInstrumentation({ integrations: { agentKit: false } })` +before registration, or `BRAINTRUST_DISABLE_INSTRUMENTATION=agent-kit`. + ## Migration Guides ### Upgrading from 3.x to 4.x diff --git a/js/src/auto-instrumentations/configs/agent-kit.ts b/js/src/auto-instrumentations/configs/agent-kit.ts new file mode 100644 index 000000000..fab91dbe9 --- /dev/null +++ b/js/src/auto-instrumentations/configs/agent-kit.ts @@ -0,0 +1,27 @@ +import type { InstrumentationConfig } from "../orchestrion-js"; +import { agentKitChannels } from "../../instrumentation/providers/agent-kit-interceptors"; + +// Validate new published layouts before extending this range or chunk path. +export const agentKitConfigs: InstrumentationConfig[] = [ + "dist/chunk-BSWKEFTT.js", + "dist/index.cjs", +].flatMap((filePath) => [ + ...( + [ + ["Agent", "run", agentKitChannels.agentRun], + ["Agent", "invokeTools", agentKitChannels.prepareTools], + ["Network", "run", agentKitChannels.networkRun], + ["AgenticModel", "infer", agentKitChannels.infer], + ["NetworkRun", "getNextAgents", agentKitChannels.route], + ] as const + ).map(([className, methodName, hook]) => ({ + channelName: hook.channelName, + module: { name: "@inngest/agent-kit", versionRange: "=0.13.2", filePath }, + functionQuery: { className, methodName }, + })), + { + channelName: agentKitChannels.createTool.channelName, + module: { name: "@inngest/agent-kit", versionRange: "=0.13.2", filePath }, + functionQuery: { functionName: "createTool" }, + }, +]); diff --git a/js/src/auto-instrumentations/configs/all.ts b/js/src/auto-instrumentations/configs/all.ts index 2e1b59609..8090460a5 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 { agentKitConfigs } from "./agent-kit"; import { elevenLabsConfigs } from "./elevenlabs"; import { voyageAIConfigs } from "./voyageai"; import { mcpConfigs } from "./mcp"; @@ -50,6 +51,7 @@ interface InstrumentationConfigGroup { const defaultInstrumentationConfigGroups: readonly InstrumentationConfigGroup[] = [ + { integrations: ["agentKit"], configs: agentKitConfigs }, { integrations: ["openai"], configs: openaiConfigs }, { integrations: ["openaiCodexSDK"], diff --git a/js/src/instrumentation/config.ts b/js/src/instrumentation/config.ts index 0e11588ef..15f52d3e8 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; + agentKit?: 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,9 @@ const envIntegrationAliases: Record< fal: "fal", "@fal-ai/client": "fal", elevenlabs: "elevenlabs", + agentkit: "agentKit", + "agent-kit": "agentKit", + "@inngest/agent-kit": "agentKit", "@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..197292d08 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(), + agentKit: 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/agent-kit-instrumentation", () => ({ + registerAgentKitInstrumentation: registrations.agentKit, +})); vi.mock("./providers/cohere-instrumentation", () => ({ registerCohereInstrumentation: registrations.cohere, })); @@ -141,6 +145,7 @@ const integrationCases: Array< ["cloudflareThink", [registrations.cloudflareThink]], ["cohere", [registrations.cohere]], ["fal", [registrations.fal]], + ["agentKit", [registrations.agentKit]], ["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..327797b95 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 agentKit } from "./registrations/agentKit"; 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 { + agentKit(); mcp(); mcpHandler(); fastmcp(); diff --git a/js/src/instrumentation/providers/agent-kit-instrumentation.test.ts b/js/src/instrumentation/providers/agent-kit-instrumentation.test.ts new file mode 100644 index 000000000..9fef7482c --- /dev/null +++ b/js/src/instrumentation/providers/agent-kit-instrumentation.test.ts @@ -0,0 +1,298 @@ +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, +} from "vite-plus/test"; +import { _exportsForTestingOnly } from "../../logger/testing"; +import { currentSpan, initLogger } from "../../logger/core"; +import { configureNode } from "../../node/config"; +import { wrapAgentKitTool } from "../../wrappers/agent-kit-tools"; +import { registerInstrumentation } from "../registrations/agentKit"; +import { agentKitChannels } from "./agent-kit-interceptors"; + +configureNode(); +registerInstrumentation(); + +describe("AgentKit execution instrumentation", () => { + let logger: ReturnType; + beforeAll(async () => { + await _exportsForTestingOnly.simulateLoginForTests(); + }); + beforeEach(() => { + logger = _exportsForTestingOnly.useTestBackgroundLogger(); + initLogger({ projectName: "tmp-agent-kit", projectId: "test-project-id" }); + }); + afterEach(() => { + _exportsForTestingOnly.clearTestBackgroundLogger(); + }); + + it("parents model and tool calls under the agent within a network", async () => { + const messages = [{ type: "text", role: "assistant", content: "Done" }]; + const modelResult = { + output: messages, + raw: { + usage: { prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 }, + authKey: "sentinel-model-secret", + }, + }; + const agent = { name: "worker" }; + const network = { name: "team", state: { results: [] as unknown[] } }; + const toolDefinition = { + name: "lookup", + handler: (_input: unknown) => "found", + }; + const tool = agentKitChannels.createTool.invoke( + () => toolDefinition, + undefined, + [{}], + {}, + ) as typeof toolDefinition; + await agentKitChannels.networkRun.invoke( + async () => { + await agentKitChannels.route.invoke( + async () => [agent], + network, + ["question"], + {}, + ); + const result = await agentKitChannels.agentRun.invoke( + async () => { + await agentKitChannels.infer.invoke( + async () => modelResult, + {}, + ["worker", [{ role: "user", content: "question" }], [], "auto"], + {}, + ); + expect(tool.handler({ query: "question" })).toBe("found"); + return { output: messages, agent }; + }, + agent, + ["question"], + {}, + ); + network.state.results.push(result); + return network; + }, + network, + ["question"], + {}, + ); + const rows = (await logger.drain()) as Record[]; + expect(rows).toHaveLength(5); + const byName = (name: string) => + rows.find((row) => row.span_attributes?.name === name)!; + const root = byName("agentkit.network.run"); + const agentSpan = byName("agentkit.agent.run"); + expect(agentSpan.span_parents).toEqual([root.span_id]); + expect(byName("agentkit.network.route")).toMatchObject({ + output: ["worker"], + span_parents: [root.span_id], + }); + for (const name of ["agentkit.model.infer", "agentkit.tool"]) { + expect(byName(name).span_parents).toEqual([agentSpan.span_id]); + } + expect(byName("agentkit.model.infer")).toMatchObject({ + output: messages, + metrics: { prompt_tokens: 4, completion_tokens: 2, tokens: 6 }, + }); + expect(root.output).toEqual(messages); + expect(JSON.stringify(rows)).not.toContain("sentinel-model-secret"); + }); + + it.each(["agentRun", "networkRun", "infer", "route"] as const)( + "preserves %s promise helpers and receiver", + async (key) => { + const hook = agentKitChannels[key]; + const self = { name: "instance" }; + const output = { output: [] }; + const promise = Object.assign(Promise.resolve(output), { + helper: () => "helper", + }); + const target = function (this: unknown, ..._args: unknown[]) { + expect(this).toBe(self); + expect(currentSpan().id).toBeTruthy(); + return promise; + }; + const args = + key === "infer" + ? (["agent", [], [], "auto"] as const) + : (["input"] as const); + // Each channel receives the actual SDK method's argument tuple. + const result = + key === "infer" + ? agentKitChannels.infer.invoke( + target, + self, + [...args] as [string, unknown, unknown, unknown], + {}, + ) + : (hook as typeof agentKitChannels.agentRun).invoke( + target, + self, + ["input"], + {}, + ); + expect(result).toBe(promise); + expect(result.helper()).toBe("helper"); + expect(await result).toBe(output); + const rows = await logger.drain(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ metrics: { end: expect.any(Number) } }); + }, + ); + + it.each(["throw", "reject"])( + "records %s errors without replacing them", + async (mode) => { + const error = new Error("original error"); + const invoke = () => + agentKitChannels.agentRun.invoke( + () => { + if (mode === "throw") throw error; + return Promise.reject(error); + }, + { name: "agent" }, + ["input"], + {}, + ); + if (mode === "throw") expect(invoke).toThrow(error); + else await expect(invoke()).rejects.toBe(error); + expect(await logger.drain()).toMatchObject([ + { + error: expect.stringContaining("original error"), + metrics: { end: expect.any(Number) }, + }, + ]); + }, + ); + + it("wraps synchronous and asynchronous tools once and preserves context", async () => { + const context = { agent: { name: "agent" } }; + const input = { query: "question" }; + const promise = Promise.resolve("async result"); + const definition = { + name: "lookup", + handler(this: unknown, value: unknown, options?: unknown) { + expect(this).toBe(definition); + expect(value).toBe(input); + expect(options).toBe(context); + return promise; + }, + }; + const wrapped = wrapAgentKitTool(definition); + expect(wrapAgentKitTool(wrapped)).toBe(wrapped); + expect(wrapAgentKitTool(definition)).toBe(wrapped); + expect(wrapped.handler(input, context)).toBe(promise); + await promise; + const sync = wrapAgentKitTool({ + name: "sync", + handler: () => "sync result", + }); + expect(sync.handler()).toBe("sync result"); + const rows = (await logger.drain()) as Record[]; + expect(rows).toHaveLength(2); + expect(rows.map((row) => row.output).sort()).toEqual([ + "async result", + "sync result", + ]); + }); + + it("retains tool error identity for synchronous throws and rejected promises", async () => { + const error = new Error("tool failed"); + const sync = wrapAgentKitTool({ + handler() { + throw error; + }, + }); + expect(() => sync.handler()).toThrow(error); + const asyncTool = wrapAgentKitTool({ + handler: () => Promise.reject(error), + }); + await expect(asyncTool.handler()).rejects.toBe(error); + expect(await logger.drain()).toHaveLength(2); + }); + + it("does not invent token metrics for unsupported or invalid usage", async () => { + await agentKitChannels.infer.invoke( + async () => ({ + output: [], + raw: { + usage: { + prompt_tokens: NaN, + completion_tokens: -1, + total_tokens: "6", + }, + }, + }), + {}, + ["agent", [], [], "auto"], + {}, + ); + const rows = (await logger.drain()) as Record[]; + expect(rows[0].metrics).not.toHaveProperty("prompt_tokens"); + expect(rows[0].metrics).not.toHaveProperty("completion_tokens"); + expect(rows[0].metrics).not.toHaveProperty("tokens"); + }); + + it("keeps tools usable when frozen after creation or supplied already frozen", () => { + const tool = agentKitChannels.createTool.invoke( + () => ({ name: "tool", handler: () => "ok" }), + undefined, + [{}], + {}, + ); + const frozen = Object.freeze(tool as { handler(): string }); + expect(frozen.handler()).toBe("ok"); + const immutable = Object.freeze({ handler: () => "unchanged" }); + expect(wrapAgentKitTool(immutable)).toBe(immutable); + expect(immutable.handler()).toBe("unchanged"); + }); + + it("prepares plain and SDK-populated tools before invocation without replacing tool objects", async () => { + const error = new Error("plain tool failed"); + const tool = { name: "plain", handler: () => Promise.reject(error) }; + const agent = { tools: new Map([["plain", tool]]) }; + await agentKitChannels.prepareTools.invoke( + async () => { + expect(agent.tools.get("plain")).toBe(tool); + await expect(tool.handler()).rejects.toBe(error); + }, + agent, + [[], undefined, undefined, undefined], + {}, + ); + expect(await logger.drain()).toMatchObject([ + { + error: expect.stringContaining("plain tool failed"), + metadata: { tool_name: "plain" }, + }, + ]); + }); + + it("preserves tool call receivers, extra arguments and stable handler identity", () => { + const receiver = { marker: "receiver" }; + const tool = { + handler(this: unknown, ...args: unknown[]) { + expect(this).toBe(receiver); + return args; + }, + }; + const wrapped = wrapAgentKitTool(tool); + const handler = wrapped.handler; + expect(wrapAgentKitTool(tool).handler).toBe(handler); + expect(handler.call(receiver, 1, 2, 3)).toEqual([1, 2, 3]); + }); + + it("does not let a throwing tool name getter prevent execution", () => { + const tool = { + get name(): string { + throw new Error("unreadable metadata"); + }, + handler: () => "ok", + }; + expect(wrapAgentKitTool(tool).handler()).toBe("ok"); + }); +}); diff --git a/js/src/instrumentation/providers/agent-kit-instrumentation.ts b/js/src/instrumentation/providers/agent-kit-instrumentation.ts new file mode 100644 index 000000000..63e09b082 --- /dev/null +++ b/js/src/instrumentation/providers/agent-kit-instrumentation.ts @@ -0,0 +1,146 @@ +import { isObject } from "../../../util"; +import { INSTRUMENTATION_NAMES } from "../../span-origin"; +import { + prepareAgentKitTools, + wrapAgentKitTool, +} from "../../wrappers/agent-kit-tools"; +import { runInstrumentation } from "../core/observe-result"; +import { traceAsyncCall } from "../core/tracing"; +import { agentKitChannels } from "./agent-kit-interceptors"; + +function nameOf(value: unknown): string | undefined { + return isObject(value) && typeof value.name === "string" + ? value.name + : undefined; +} + +function outputOf(result: unknown): unknown { + if (!isObject(result)) return undefined; + return Array.isArray(result.output) ? result.output : undefined; +} + +export function registerAgentKitInstrumentation(): void { + agentKitChannels.prepareTools.intercept((target, self, args) => { + runInstrumentation(() => prepareAgentKitTools(self)); + return Reflect.apply(target, self, args); + }); + agentKitChannels.createTool.intercept((target, self, args) => + wrapAgentKitTool(Reflect.apply(target, self, args)), + ); + for (const [key, name] of [ + ["agentRun", "agent.run"], + ["networkRun", "network.run"], + ] as const) { + const hook = agentKitChannels[key]; + hook.intercept((target, self, args, additional) => + traceAsyncCall( + () => Reflect.apply(target, self, args), + { ...additional, arguments: args, self }, + { + instrumentationName: INSTRUMENTATION_NAMES.AGENT_KIT, + name: `agentkit.${name}`, + type: "task", + extractInput: ([input]) => ({ + input: isObject(input) ? input.content : input, + metadata: { + provider: "inngest", + [key === "agentRun" ? "agent_name" : "network_name"]: + nameOf(self), + }, + }), + extractOutput: (result) => { + if (key === "agentRun") return outputOf(result); + if ( + !isObject(result) || + !isObject(result.state) || + !Array.isArray(result.state.results) + ) + return undefined; + return outputOf(result.state.results.at(-1)); + }, + extractMetrics: () => ({}), + }, + ), + ); + } + agentKitChannels.infer.intercept((target, self, args, additional) => + traceAsyncCall( + () => Reflect.apply(target, self, args), + { ...additional, arguments: args, self }, + { + instrumentationName: INSTRUMENTATION_NAMES.AGENT_KIT, + name: "agentkit.model.infer", + type: "llm", + extractInput: ([stepId, input]) => ({ + input, + metadata: { provider: "inngest", agent_name: stepId }, + }), + extractOutput: outputOf, + extractMetrics: (result) => { + if ( + !isObject(result) || + !isObject(result.raw) || + !isObject(result.raw.usage) + ) + return {}; + const usage = result.raw.usage; + const metrics: Record = {}; + for (const [source, destination] of [ + ["prompt_tokens", "prompt_tokens"], + ["completion_tokens", "completion_tokens"], + ["total_tokens", "tokens"], + ] as const) { + const value = usage[source]; + if ( + typeof value === "number" && + Number.isFinite(value) && + value >= 0 + ) + metrics[destination] = value; + } + return metrics; + }, + }, + ), + ); + agentKitChannels.route.intercept((target, self, args, additional) => + traceAsyncCall( + () => Reflect.apply(target, self, args), + { ...additional, arguments: args, self }, + { + instrumentationName: INSTRUMENTATION_NAMES.AGENT_KIT, + name: "agentkit.network.route", + type: "task", + extractInput: ([input]) => ({ + input: isObject(input) ? input.content : input, + metadata: { provider: "inngest", network_name: nameOf(self) }, + }), + extractOutput: (result) => + Array.isArray(result) + ? result.map(nameOf).filter((name) => name !== undefined) + : [], + extractMetrics: () => ({}), + }, + ), + ); + agentKitChannels.tool.intercept((target, self, args, additional) => + traceAsyncCall( + () => Reflect.apply(target, self, args), + { ...additional, arguments: args, self }, + { + instrumentationName: INSTRUMENTATION_NAMES.AGENT_KIT, + name: "agentkit.tool", + type: "tool", + extractInput: ([input]) => ({ + input, + metadata: { + provider: "inngest", + tool_name: additional.toolName ?? nameOf(self), + }, + }), + extractOutput: (result) => result, + extractMetrics: () => ({}), + }, + ), + ); +} diff --git a/js/src/instrumentation/providers/agent-kit-interceptors.ts b/js/src/instrumentation/providers/agent-kit-interceptors.ts new file mode 100644 index 000000000..e674acbf4 --- /dev/null +++ b/js/src/instrumentation/providers/agent-kit-interceptors.ts @@ -0,0 +1,31 @@ +import { channel, defineInterceptor } from "../core/interceptor-definitions"; + +export const agentKitChannels = defineInterceptor("@inngest/agent-kit", { + agentRun: channel<[input: unknown, options?: unknown], PromiseLike>({ + channelName: "Agent.run", + }), + networkRun: channel< + [input: unknown, options?: unknown], + PromiseLike + >({ channelName: "Network.run" }), + infer: channel< + [stepId: string, input: unknown, tools: unknown, toolChoice: unknown], + PromiseLike + >({ channelName: "AgenticModel.infer" }), + route: channel<[input: unknown, router?: unknown], PromiseLike>({ + channelName: "NetworkRun.getNextAgents", + }), + createTool: channel<[options: unknown], unknown>({ + channelName: "createTool", + }), + prepareTools: channel>({ + channelName: "Agent.invokeTools", + }), + tool: channel< + [input: unknown, context?: unknown], + unknown, + { toolName?: string } + >({ + channelName: "tool.handler", + }), +}); diff --git a/js/src/instrumentation/registrations/agentKit.ts b/js/src/instrumentation/registrations/agentKit.ts new file mode 100644 index 000000000..361485c87 --- /dev/null +++ b/js/src/instrumentation/registrations/agentKit.ts @@ -0,0 +1,6 @@ +import { registerAgentKitInstrumentation } from "../providers/agent-kit-instrumentation"; +import { registry } from "../registry"; + +export function registerInstrumentation(): void { + registry.register("agentKit", registerAgentKitInstrumentation); +} diff --git a/js/src/span-origin.ts b/js/src/span-origin.ts index 9c1063512..377269314 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", + AGENT_KIT: "agent-kit", } 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/wrappers/agent-kit-tools.ts b/js/src/wrappers/agent-kit-tools.ts new file mode 100644 index 000000000..f4458d179 --- /dev/null +++ b/js/src/wrappers/agent-kit-tools.ts @@ -0,0 +1,50 @@ +import { isObject } from "../../util"; +import { agentKitChannels } from "../instrumentation/providers/agent-kit-interceptors"; + +const handlers = new WeakMap(); + +/** Wrap invocation mechanics while retaining the tool object and receiver. */ +export function wrapAgentKitTool(tool: T): T { + if (!isObject(tool)) return tool; + try { + const descriptor = Object.getOwnPropertyDescriptor(tool, "handler"); + if ( + !descriptor || + !("value" in descriptor) || + typeof descriptor.value !== "function" + ) + return tool; + const original = descriptor.value; + if ( + handlers.get(tool) === original || + (!descriptor.writable && !descriptor.configurable) + ) + return tool; + const wrapped = function (this: unknown, ...args: unknown[]) { + let toolName: string | undefined; + try { + const name = tool.name; + if (typeof name === "string") toolName = name; + } catch { + // Metadata access must not prevent the user's handler from running. + } + return agentKitChannels.tool.invoke( + (...parameters: unknown[]) => Reflect.apply(original, this, parameters), + this, + args, + { toolName }, + ); + }; + Object.defineProperty(tool, "handler", { ...descriptor, value: wrapped }); + handlers.set(tool, wrapped); + } catch { + // Immutable or unusual tool objects must keep their original behavior. + } + return tool; +} + +/** Include plain, Inngest-function and MCP tools populated by the SDK. */ +export function prepareAgentKitTools(agent: unknown): void { + if (!isObject(agent) || !(agent.tools instanceof Map)) return; + for (const tool of agent.tools.values()) wrapAgentKitTool(tool); +}