Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(assistant): better trace design (#14638)

Nimar94ad15dc8615
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index 8a5cc1a4f0..99257c5df1 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -19,6 +19,7 @@ const adapterEvents = vi.hoisted(() => ({
const instrumentationMocks = vi.hoisted(() => {
const instrumentation = {
recordEvents: vi.fn(),
+ recordAvailableTools: vi.fn(),
end: vi.fn(),
endWithError: vi.fn(),
flush: vi.fn(),
diff --git a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
index 39ea5dfd95..5e25fc7760 100644
--- a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
+++ b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
@@ -60,6 +60,9 @@ const input: AgUiRunAgentInput = {
context: [],
forwardedProps: {},
};
+const expectedAgentRunInput = {
+ messages: [{ role: "user", content: "hello" }],
+};
describe("InAppAgentInstrumentation", () => {
beforeEach(() => {
@@ -68,6 +71,13 @@ describe("InAppAgentInstrumentation", () => {
it("records agent output and tool calls as tool observations", () => {
const instrumentation = createInstrumentation();
+ const toolCall = {
+ id: "tool-1",
+ name: "listObservations",
+ arguments: '{"limit":10}',
+ type: "function",
+ };
+ const toolOutput = { traces: [{ id: "trace-1" }] };
instrumentation.recordEvents([
{
@@ -82,6 +92,7 @@ describe("InAppAgentInstrumentation", () => {
type: EventType.TOOL_CALL_START,
toolCallId: "tool-1",
toolCallName: "listObservations",
+ parentMessageId: "assistant-message-1",
},
{
type: EventType.TOOL_CALL_ARGS,
@@ -100,7 +111,14 @@ describe("InAppAgentInstrumentation", () => {
{
type: EventType.TOOL_CALL_RESULT,
toolCallId: "tool-1",
- content: "tool result",
+ content: JSON.stringify({
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(toolOutput),
+ },
+ ],
+ }),
},
{
type: EventType.RUN_FINISHED,
@@ -130,7 +148,7 @@ describe("InAppAgentInstrumentation", () => {
expect.objectContaining({
id: agentRunObservationId,
name: "agent-run",
- input: "hello",
+ input: expectedAgentRunInput,
}),
);
expect(mocks.handler.langfuse.enqueue).toHaveBeenCalledWith(
@@ -141,18 +159,38 @@ describe("InAppAgentInstrumentation", () => {
parentObservationId: agentRunObservationId,
name: "listObservations",
input: { limit: 10 },
- output: "tool result",
+ output: toolOutput,
startTime: expect.any(Date),
endTime: expect.any(Date),
completionStartTime: expect.any(Date),
- metadata: expect.objectContaining({ toolCallId: "tool-1" }),
+ metadata: expect.objectContaining({
+ toolCallId: "tool-1",
+ parentMessageId: "assistant-message-1",
+ }),
}),
);
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
- output: "hi there",
+ input: expectedAgentRunInput,
+ output: {
+ messages: [
+ { role: "assistant", content: "hi there" },
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [toolCall],
+ },
+ {
+ role: "tool",
+ tool_call_id: "tool-1",
+ content: toolOutput,
+ },
+ ],
+ text: "hi there",
+ tool_calls: [toolCall],
+ },
+ completionStartTime: expect.any(Date),
}),
);
expect(mocks.handler.langfuse.enqueue).not.toHaveBeenCalledWith(
@@ -164,6 +202,12 @@ describe("InAppAgentInstrumentation", () => {
it("records run failures on the agent generation", () => {
const instrumentation = createInstrumentation();
+ const toolCall = {
+ id: "tool-1",
+ name: "getTrace",
+ arguments: '{"traceId":',
+ type: "function",
+ };
instrumentation.recordEvents([
{
@@ -174,7 +218,7 @@ describe("InAppAgentInstrumentation", () => {
{
type: EventType.TOOL_CALL_ARGS,
toolCallId: "tool-1",
- delta: '{"traceId":"trace-1"}',
+ delta: '{"traceId":',
},
]);
instrumentation.endWithError(new Error("agent failed"));
@@ -182,16 +226,30 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.handler.langfuse.enqueue).toHaveBeenCalledWith(
"tool-create",
expect.objectContaining({
- input: { traceId: "trace-1" },
+ input: '{"traceId":',
level: "ERROR",
statusMessage: "agent failed",
- metadata: expect.objectContaining({ error: "agent failed" }),
+ metadata: expect.objectContaining({
+ argsComplete: false,
+ error: "agent failed",
+ }),
}),
);
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
+ input: expectedAgentRunInput,
+ output: {
+ messages: [
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [toolCall],
+ },
+ ],
+ tool_calls: [toolCall],
+ },
+ completionStartTime: expect.any(Date),
level: "ERROR",
statusMessage: "agent failed",
metadata: expect.objectContaining({ error: "agent failed" }),
@@ -199,6 +257,114 @@ describe("InAppAgentInstrumentation", () => {
);
});
+ it("records available tools on the agent generation input", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordAvailableTools({
+ langfuse_listObservations: {
+ description: "List observations in a project.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ includeErrors: { type: "boolean", nullable: true },
+ limit: { type: "number", required: false },
+ },
+ },
+ },
+ langfuse_redirect: {
+ description: "Redirect the user to a Langfuse page.",
+ inputSchema: {
+ parse: vi.fn(),
+ },
+ },
+ });
+ instrumentation.end();
+
+ expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "agent-run",
+ input: {
+ messages: [{ role: "user", content: "hello" }],
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "langfuse_listObservations",
+ description: "List observations in a project.",
+ parameters: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ includeErrors: { type: "boolean", nullable: true },
+ limit: { type: "number", required: false },
+ },
+ },
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "langfuse_redirect",
+ description: "Redirect the user to a Langfuse page.",
+ },
+ },
+ ],
+ },
+ }),
+ );
+ });
+
+ it("marks tool observations with error outputs as error level", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-1",
+ toolCallName: "listObservations",
+ },
+ {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-1",
+ delta: '{"type":"TRACE"}',
+ },
+ {
+ type: EventType.TOOL_CALL_END,
+ toolCallId: "tool-1",
+ },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-1",
+ content: JSON.stringify({
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify({
+ error: true,
+ message: "Tool input validation failed",
+ }),
+ },
+ ],
+ }),
+ },
+ ]);
+
+ const toolCreateBody = mocks.handler.langfuse.enqueue.mock.calls[0]?.[1];
+
+ expect(toolCreateBody).toEqual(
+ expect.objectContaining({
+ input: { type: "TRACE" },
+ output: {
+ error: true,
+ message: "Tool input validation failed",
+ },
+ level: "ERROR",
+ }),
+ );
+ expect(toolCreateBody).not.toHaveProperty("statusMessage");
+ });
+
it("sets static prompt metadata on the trace and agent generation", () => {
const instrumentation = createInstrumentation(undefined, {
name: "in-app-agent-system-prompt",
@@ -232,7 +398,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.trace.generation).toHaveBeenCalledWith({
id: agentRunObservationId,
name: "agent-run",
- input: "hello",
+ input: expectedAgentRunInput,
metadata: {
langfuse_project_id: "project-1",
langfuse_user_email: "[email protected]",
@@ -248,7 +414,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
+ input: expectedAgentRunInput,
promptName: "in-app-agent-system-prompt",
promptVersion: 3,
}),
@@ -274,8 +440,12 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
- output: "second turn output",
+ input: expectedAgentRunInput,
+ output: {
+ messages: [{ role: "assistant", content: "second turn output" }],
+ text: "second turn output",
+ },
+ completionStartTime: expect.any(Date),
}),
);
expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
@@ -289,6 +459,14 @@ describe("InAppAgentInstrumentation", () => {
value:
"https://cloud.langfuse.com/project/project-1/traces?filter=value",
},
+ {
+ description: "browser_languages",
+ value: "en-US, en, de",
+ },
+ {
+ description: "current_trace",
+ value: JSON.stringify({ id: "trace-1" }),
+ },
],
});
@@ -296,14 +474,13 @@ describe("InAppAgentInstrumentation", () => {
expect.objectContaining({
name: "agent-run",
input: {
- message: "hello",
- context: [
- {
- description: "current_url",
- value:
- "https://cloud.langfuse.com/project/project-1/traces?filter=value",
- },
- ],
+ messages: [{ role: "user", content: "hello" }],
+ context: {
+ current_url:
+ "https://cloud.langfuse.com/project/project-1/traces?filter=value",
+ browser_languages: ["en-US", "en", "de"],
+ current_trace: { id: "trace-1" },
+ },
},
}),
);
@@ -312,6 +489,79 @@ describe("InAppAgentInstrumentation", () => {
);
});
+ it("records replayed conversation messages in the agent generation input", () => {
+ createInstrumentation({
+ messages: [
+ {
+ id: "message-previous-user",
+ role: "user",
+ content: "previous question",
+ },
+ {
+ id: "message-previous-assistant",
+ role: "assistant",
+ content: "previous answer",
+ toolCalls: [
+ {
+ id: "tool-previous",
+ type: "function",
+ function: {
+ name: "getTrace",
+ arguments: '{"traceId":"trace-1"}',
+ },
+ },
+ ],
+ },
+ {
+ id: "message-previous-tool",
+ role: "tool",
+ toolCallId: "tool-previous",
+ content: '{"found":true}',
+ },
+ {
+ id: "message-activity",
+ role: "activity",
+ activityType: "loading",
+ content: { label: "Loading" },
+ },
+ {
+ id: "message-1",
+ role: "user",
+ content: "hello",
+ },
+ ],
+ });
+
+ expect(mocks.trace.generation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "agent-run",
+ input: {
+ messages: [
+ { role: "user", content: "previous question" },
+ {
+ role: "assistant",
+ content: "previous answer",
+ tool_calls: [
+ {
+ id: "tool-previous",
+ name: "getTrace",
+ arguments: '{"traceId":"trace-1"}',
+ type: "function",
+ },
+ ],
+ },
+ {
+ role: "tool",
+ tool_call_id: "tool-previous",
+ content: { found: true },
+ },
+ { role: "user", content: "hello" },
+ ],
+ },
+ }),
+ );
+ });
+
it("compacts text message chunks before recording output", () => {
const instrumentation = createInstrumentation();
@@ -335,8 +585,12 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
- output: "chunk output",
+ input: expectedAgentRunInput,
+ output: {
+ messages: [{ role: "assistant", content: "chunk output" }],
+ text: "chunk output",
+ },
+ completionStartTime: expect.any(Date),
}),
);
});
@@ -367,8 +621,12 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
name: "agent-run",
- input: "hello",
- output: "Done",
+ input: expectedAgentRunInput,
+ output: {
+ messages: [{ role: "assistant", content: "Done" }],
+ text: "Done",
+ },
+ completionStartTime: expect.any(Date),
metadata: expect.objectContaining({ reasoning: "Checking filters" }),
}),
);
diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.ts
index 93ad8d30a4..760c743117 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -372,6 +372,8 @@ export async function createAgUiStream(params: {
options: params.options,
awsProfile,
instructions,
+ onToolsAvailable: (tools) =>
+ instrumentation?.recordAvailableTools(tools),
})
.then(({ adapter, cleanup, interrupt }) => {
if (ending || closed || params.signal.aborted) {
@@ -544,6 +546,7 @@ async function createMastraAdapter(params: {
options: CreateAgUiStreamOptions;
awsProfile?: string;
instructions: string;
+ onToolsAvailable?: (tools: Record<string, unknown>) => void;
}) {
const bedrock = createAmazonBedrock({
...(params.options.awsBedrock.region
@@ -586,6 +589,10 @@ async function createMastraAdapter(params: {
});
}
+ // @ag-ui/mastra drives execution via adapter.run(input), not a direct
+ // agent.stream(..., { toolsets }) call. Keep Mastra's per-request MCP
+ // discovery, then prefix tool names for constructor-based tools so the
+ // model sees the same names that later appear in AG-UI tool-call events.
const tools = {
...prefixToolsetTools("langfuse", toolsets.langfuse),
...prefixToolsetTools("langfuseDocs", toolsets.langfuseDocs),
@@ -594,6 +601,7 @@ async function createMastraAdapter(params: {
isV4Enabled: params.options.redirectAction.isV4Enabled,
}),
};
+ params.onToolsAvailable?.(tools);
const agent = new Agent({
id: "langfuse-in-app-assistant",
diff --git a/web/src/ee/features/in-app-agent/server/instrumentation.ts b/web/src/ee/features/in-app-agent/server/instrumentation.ts
index db602cece9..8646567dba 100644
--- a/web/src/ee/features/in-app-agent/server/instrumentation.ts
+++ b/web/src/ee/features/in-app-agent/server/instrumentation.ts
@@ -3,6 +3,7 @@ import { getInternalTracingHandler, logger } from "@langfuse/shared/src/server";
import type {
AgUiEvent,
+ AgUiMessage,
AgUiRunAgentInput,
} from "@/src/ee/features/in-app-agent/schema";
import { compactTextMessageChunks } from "@/src/ee/features/in-app-agent/server/eventCompaction";
@@ -37,6 +38,27 @@ type InAppAgentTrace = ReturnType<
>;
type InAppAgentGeneration = ReturnType<InAppAgentTrace["generation"]>;
type InAppAgentLangfuse = InternalTracingHandler["handler"]["langfuse"];
+type AgentRunToolCall = {
+ id: string;
+ name: string;
+ arguments: string;
+ type: "function";
+};
+type AgentRunToolDefinition = {
+ type: "function";
+ function: {
+ name: string;
+ description?: string;
+ parameters?: unknown;
+ };
+};
+type AgentRunChatMessage = {
+ role: string;
+ name?: string;
+ content?: unknown;
+ tool_calls?: AgentRunToolCall[];
+ tool_call_id?: string;
+};
type ToolObservationBody = {
id: string;
traceId: string;
@@ -82,7 +104,7 @@ export class InAppAgentInstrumentation {
private readonly langfuse: InAppAgentLangfuse;
private readonly trace: InAppAgentTrace;
private readonly agentRun: InAppAgentGeneration;
- private readonly agentRunInput: unknown;
+ private agentRunInput: unknown;
private readonly prompt?: InAppAgentPromptMetadata;
private readonly toolSpans = new Map<
string,
@@ -92,11 +114,15 @@ export class InAppAgentInstrumentation {
args: string;
argsComplete: boolean;
output?: unknown;
+ parentMessageId?: string;
}
>();
private readonly metadata: Record<string, unknown>;
+ private readonly agentRunOutputMessages: AgentRunChatMessage[] = [];
+ private readonly agentRunToolCalls: AgentRunToolCall[] = [];
private output = "";
private reasoning = "";
+ private completionStartTime?: Date;
private ended = false;
constructor(params: {
@@ -170,6 +196,23 @@ export class InAppAgentInstrumentation {
}
}
+ recordAvailableTools(tools: Record<string, unknown>) {
+ if (this.ended) {
+ return;
+ }
+
+ const availableTools = getAgentRunAvailableTools(tools);
+
+ if (availableTools.length === 0) {
+ return;
+ }
+
+ this.agentRunInput = addAvailableToolsToAgentRunInput(
+ this.agentRunInput,
+ availableTools,
+ );
+ }
+
endWithError(error: unknown) {
if (this.ended) {
return;
@@ -180,7 +223,10 @@ export class InAppAgentInstrumentation {
this.agentRun.update({
name: IN_APP_AGENT_RUN_NAME,
input: this.agentRunInput,
- output: this.output || undefined,
+ output: this.getAgentRunOutput(),
+ ...(this.completionStartTime
+ ? { completionStartTime: this.completionStartTime }
+ : {}),
level: "ERROR",
statusMessage: message,
metadata: {
@@ -217,7 +263,10 @@ export class InAppAgentInstrumentation {
this.agentRun.update({
name: IN_APP_AGENT_RUN_NAME,
input: this.agentRunInput,
- output: this.output || undefined,
+ output: this.getAgentRunOutput(),
+ ...(this.completionStartTime
+ ? { completionStartTime: this.completionStartTime }
+ : {}),
metadata,
...(this.prompt
? {
@@ -242,7 +291,7 @@ export class InAppAgentInstrumentation {
case EventType.TEXT_MESSAGE_CHUNK:
case EventType.TEXT_MESSAGE_CONTENT:
if (typeof event.delta === "string") {
- this.output += event.delta;
+ this.recordAssistantText(event.delta);
}
return;
case EventType.REASONING_MESSAGE_CHUNK:
@@ -308,6 +357,9 @@ export class InAppAgentInstrumentation {
startTime: new Date(),
args: "",
argsComplete: false,
+ ...(typeof event.parentMessageId === "string"
+ ? { parentMessageId: event.parentMessageId }
+ : {}),
});
}
@@ -359,6 +411,7 @@ export class InAppAgentInstrumentation {
args: string;
argsComplete: boolean;
output?: unknown;
+ parentMessageId?: string;
},
) {
if (!tool.argsComplete || tool.output === undefined) {
@@ -375,13 +428,19 @@ export class InAppAgentInstrumentation {
name: string;
startTime: Date;
args: string;
+ argsComplete: boolean;
output?: unknown;
+ parentMessageId?: string;
},
options?: {
metadata?: Record<string, unknown>;
statusMessage?: string;
},
) {
+ const input = parseJsonOrUndefined(tool.args);
+ const output =
+ tool.output === undefined ? undefined : normalizeToolOutput(tool.output);
+ const isError = options?.statusMessage !== undefined || isToolError(output);
const body: ToolObservationBody = {
id: toolCallId,
traceId: this.agentRun.traceId,
@@ -390,17 +449,24 @@ export class InAppAgentInstrumentation {
startTime: tool.startTime,
endTime: new Date(),
completionStartTime: tool.startTime,
- input: parseJsonOrString(tool.args),
- output: tool.output,
+ input,
+ output,
+ ...(isError ? { level: "ERROR" } : {}),
...(options?.statusMessage
- ? { level: "ERROR", statusMessage: options.statusMessage }
+ ? { statusMessage: options.statusMessage }
: {}),
metadata: {
...(options?.metadata ?? {}),
toolCallId,
+ ...(tool.argsComplete ? {} : { argsComplete: false }),
+ ...(tool.parentMessageId
+ ? { parentMessageId: tool.parentMessageId }
+ : {}),
},
};
+ this.recordToolCall(toolCallId, tool, output);
+
(
this.langfuse as unknown as {
enqueue: (type: string, body: ToolObservationBody) => void;
@@ -420,45 +486,333 @@ export class InAppAgentInstrumentation {
this.toolSpans.delete(toolCallId);
}
}
+
+ private recordAssistantText(delta: string) {
+ this.output += delta;
+ this.completionStartTime ??= new Date();
+
+ const lastMessage = this.agentRunOutputMessages.at(-1);
+ if (lastMessage?.role === "assistant" && !lastMessage.tool_calls?.length) {
+ lastMessage.content = `${typeof lastMessage.content === "string" ? lastMessage.content : ""}${delta}`;
+ return;
+ }
+
+ this.agentRunOutputMessages.push({
+ role: "assistant",
+ content: delta,
+ });
+ }
+
+ private recordToolCall(
+ toolCallId: string,
+ tool: {
+ name: string;
+ args: string;
+ startTime: Date;
+ },
+ output: unknown,
+ ) {
+ this.completionStartTime ??= tool.startTime;
+
+ const toolCall: AgentRunToolCall = {
+ id: toolCallId,
+ name: tool.name,
+ arguments: tool.args || "{}",
+ type: "function",
+ };
+
+ this.agentRunToolCalls.push(toolCall);
+ this.agentRunOutputMessages.push({
+ role: "assistant",
+ content: "",
+ tool_calls: [toolCall],
+ });
+
+ if (output !== undefined) {
+ this.agentRunOutputMessages.push({
+ role: "tool",
+ tool_call_id: toolCallId,
+ content: output,
+ });
+ }
+ }
+
+ private getAgentRunOutput() {
+ if (this.agentRunOutputMessages.length === 0) {
+ return undefined;
+ }
+
+ return {
+ messages: this.agentRunOutputMessages,
+ ...(this.output ? { text: this.output } : {}),
+ ...(this.agentRunToolCalls.length > 0
+ ? { tool_calls: this.agentRunToolCalls }
+ : {}),
+ };
+ }
}
function getAgentRunInput(input: AgUiRunAgentInput): unknown {
- const message = getLastUserMessageText(input);
+ const messages = getAgentRunMessages(input.messages);
+ const context = getAgentRunContext(input);
- if (input.context.length === 0) {
- return message;
+ if (!context) {
+ return { messages };
}
return {
- message,
- context: input.context,
+ messages,
+ context,
};
}
-function getLastUserMessageText(input: AgUiRunAgentInput): string | undefined {
- const lastMessage = input.messages.at(-1);
+function addAvailableToolsToAgentRunInput(
+ input: unknown,
+ tools: AgentRunToolDefinition[],
+) {
+ if (!isRecord(input)) {
+ return input;
+ }
- if (lastMessage?.role !== "user") {
+ return {
+ ...input,
+ tools,
+ };
+}
+
+function getAgentRunAvailableTools(
+ tools: Record<string, unknown>,
+): AgentRunToolDefinition[] {
+ return Object.entries(tools).map(([name, tool]) => {
+ const toolRecord = isRecord(tool) ? tool : {};
+ const description = getStringValue(toolRecord.description);
+ const parameters = getSerializableToolParameters(toolRecord);
+
+ return {
+ type: "function" as const,
+ function: {
+ name,
+ ...(description ? { description } : {}),
+ ...(parameters ? { parameters } : {}),
+ },
+ };
+ });
+}
+
+function getAgentRunMessages(messages: AgUiMessage[]): AgentRunChatMessage[] {
+ return messages.flatMap((message): AgentRunChatMessage[] => {
+ switch (message.role) {
+ case "developer":
+ case "system":
+ return [
+ {
+ role: message.role,
+ ...(message.name ? { name: message.name } : {}),
+ content: message.content,
+ },
+ ];
+ case "user":
+ return [
+ {
+ role: "user",
+ ...(message.name ? { name: message.name } : {}),
+ content: normalizeUserMessageContent(message.content),
+ },
+ ];
+ case "assistant": {
+ const toolCalls = message.toolCalls?.map((toolCall) => ({
+ id: toolCall.id,
+ name: toolCall.function.name,
+ arguments: toolCall.function.arguments,
+ type: "function" as const,
+ }));
+
+ if (!message.content && !toolCalls?.length) {
+ return [];
+ }
+
+ return [
+ {
+ role: "assistant",
+ ...(message.name ? { name: message.name } : {}),
+ content: message.content ?? "",
+ ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),
+ },
+ ];
+ }
+ case "tool":
+ return [
+ {
+ role: "tool",
+ tool_call_id: message.toolCallId,
+ content: parseJsonOrString(message.content),
+ },
+ ];
+ case "activity":
+ case "reasoning":
+ return [];
+ }
+ });
+}
+
+function normalizeUserMessageContent(
+ content: Extract<AgUiMessage, { role: "user" }>["content"],
+): unknown {
+ if (typeof content === "string") {
+ return content;
+ }
+
+ if (content.every((part) => part.type === "text")) {
+ return content.map((part) => part.text).join("");
+ }
+
+ return content;
+}
+
+function getAgentRunContext(input: AgUiRunAgentInput) {
+ if (input.context.length === 0) {
return undefined;
}
- if (typeof lastMessage.content === "string") {
- return lastMessage.content;
+ return Object.fromEntries(
+ input.context.map((item) => [
+ item.description,
+ parseContextValue(item.description, item.value),
+ ]),
+ );
+}
+
+function parseContextValue(description: string, value: string): unknown {
+ const parsed = parseJsonOrString(value);
+
+ if (description === "browser_languages" && typeof parsed === "string") {
+ return parsed
+ .split(",")
+ .map((language) => language.trim())
+ .filter(Boolean);
}
- return lastMessage.content
- .flatMap((part) => (part.type === "text" ? [part.text] : []))
- .join("");
+ return parsed;
}
-function parseJsonOrString(value: string): unknown {
+function normalizeToolOutput(output: unknown): unknown {
+ const parsedOutput =
+ typeof output === "string" ? parseJsonOrString(output) : output;
+
+ if (!isRecord(parsedOutput) || !Array.isArray(parsedOutput.content)) {
+ return parsedOutput;
+ }
+
+ const firstContent = parsedOutput.content[0];
+
+ if (
+ parsedOutput.content.length !== 1 ||
+ !isRecord(firstContent) ||
+ firstContent.type !== "text" ||
+ typeof firstContent.text !== "string"
+ ) {
+ return parsedOutput;
+ }
+
+ return parseJsonOrString(firstContent.text);
+}
+
+function isToolError(output: unknown): boolean {
+ return isRecord(output) && output.error === true;
+}
+
+function getSerializableToolParameters(tool: Record<string, unknown>): unknown {
+ const parameters =
+ tool.parameters ??
+ tool.inputSchema ??
+ tool.parameters_json_schema ??
+ tool.input_schema;
+
+ return toSerializableJson(parameters);
+}
+
+function toSerializableJson(
+ value: unknown,
+ seen = new WeakSet<object>(),
+ depth = 0,
+): unknown {
+ if (value === null || typeof value === "string") {
+ return value;
+ }
+
+ if (typeof value === "boolean") {
+ return value;
+ }
+
+ if (typeof value === "number") {
+ return Number.isFinite(value) ? value : undefined;
+ }
+
+ if (Array.isArray(value)) {
+ if (depth >= 8) {
+ return undefined;
+ }
+
+ return value
+ .map((item) => toSerializableJson(item, seen, depth + 1))
+ .filter((item) => item !== undefined);
+ }
+
+ if (!isRecord(value)) {
+ return undefined;
+ }
+
+ if (Object.getPrototypeOf(value) !== Object.prototype) {
+ return undefined;
+ }
+
+ if (seen.has(value)) {
+ return undefined;
+ }
+
+ if (depth >= 8) {
+ return undefined;
+ }
+
+ seen.add(value);
+
+ const entries = Object.entries(value).flatMap(([key, item]) => {
+ const serializableItem = toSerializableJson(item, seen, depth + 1);
+
+ return serializableItem === undefined
+ ? []
+ : [[key, serializableItem] as const];
+ });
+
+ seen.delete(value);
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+function parseJsonOrUndefined(value: string): unknown {
if (!value) {
return undefined;
}
+ return parseJsonOrString(value);
+}
+
+function parseJsonOrString(value: string): unknown {
+ if (!value) {
+ return value;
+ }
+
try {
return JSON.parse(value);
} catch {
return value;
}
}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function getStringValue(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value : undefined;
+}