Skip to content

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

refactor(agent): Replace switch statements with exhaustive if conditions (#14829)

Ben Bachemf4f52805c21a
diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.ts
index 4c2cf9d142..9aecf94e5e 100644
--- a/packages/eslint-plugin/src/index.ts
+++ b/packages/eslint-plugin/src/index.ts
@@ -4,6 +4,7 @@ import { default as noMarginOnRootElements } from "./rules/no-margin-on-root-ele
import { default as noOverlayZindex } from "./rules/no-overlay-zindex.js";
import { default as requireTitleWithTruncate } from "./rules/require-title-with-truncate.js";
import { default as noStyleProps } from "./rules/no-style-props.js";
+import { default as noSwitchStatements } from "./rules/no-switch-statements.js";
import { default as noUnnecessaryCn } from "./rules/no-unnecessary-cn.js";
const plugin = {
@@ -12,6 +13,7 @@ const plugin = {
"no-margin-on-root-elements": noMarginOnRootElements,
"no-overlay-zindex": noOverlayZindex,
"no-style-props": noStyleProps,
+ "no-switch-statements": noSwitchStatements,
"no-tailwind-overflow-scroll": noTailwindOverflowScroll,
"no-unnecessary-cn": noUnnecessaryCn,
"require-title-with-truncate": requireTitleWithTruncate,
diff --git a/packages/eslint-plugin/src/rules/no-switch-statements.test.ts b/packages/eslint-plugin/src/rules/no-switch-statements.test.ts
new file mode 100644
index 0000000000..bcde6499ab
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-switch-statements.test.ts
@@ -0,0 +1,44 @@
+import { RuleTester } from "@typescript-eslint/rule-tester";
+import * as typescriptEslintParser from "@typescript-eslint/parser";
+import rule from "./no-switch-statements.js";
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ parser: typescriptEslintParser,
+ parserOptions: {
+ ecmaVersion: 2022,
+ sourceType: "module",
+ ecmaFeatures: {
+ jsx: true,
+ },
+ },
+ },
+});
+
+ruleTester.run("no-switch-statements", rule, {
+ valid: [
+ {
+ code: `if (value === "a") return 1; return 2;`,
+ },
+ {
+ code: `const valueMap = { a: 1, b: 2 } as const; const result = valueMap[value] ?? 0;`,
+ },
+ {
+ code: `function render(value: string) { if (value === "a") return <div />; return null; }`,
+ },
+ ],
+ invalid: [
+ {
+ code: `switch (value) { case "a": return 1; default: return 2; }`,
+ errors: [{ messageId: "unexpected" }],
+ },
+ {
+ code: `function render(value: string) { switch (value) { case "a": return <div />; default: return null; } }`,
+ errors: [{ messageId: "unexpected" }],
+ },
+ {
+ code: `if (enabled) { switch (value) { case "a": break; default: break; } }`,
+ errors: [{ messageId: "unexpected" }],
+ },
+ ],
+});
diff --git a/packages/eslint-plugin/src/rules/no-switch-statements.ts b/packages/eslint-plugin/src/rules/no-switch-statements.ts
new file mode 100644
index 0000000000..5444061bb6
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-switch-statements.ts
@@ -0,0 +1,26 @@
+import { createRule } from "../util.js";
+
+const rule = createRule({
+ name: "no-switch-statements",
+ meta: {
+ type: "suggestion",
+ docs: {
+ description: "Disallow switch statements.",
+ },
+ messages: {
+ unexpected:
+ "Use if statements or lookup tables instead of switch statements.",
+ },
+ schema: [],
+ },
+ defaultOptions: [],
+ create(context) {
+ return {
+ SwitchStatement(node) {
+ context.report({ node, messageId: "unexpected" });
+ },
+ };
+ },
+});
+
+export default rule;
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index 30c59bea0b..89fb96ed87 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -105,6 +105,15 @@ export default [
},
},
+ // We're using the in-app-agent directory as a testing ground for some new eslint-rules.
+ {
+ name: "langfuse/web/in-app-agent",
+ files: ["src/ee/features/in-app-agent/**/*.{ts,tsx}"],
+ rules: {
+ "@repo/no-switch-statements": "error",
+ },
+ },
+
// App-wide guard ("overlay-content" mode): a consumer must not re-introduce a
// z-index escape on an overlay it imports (e.g. nav-user's old `z-60` on
// DropdownMenuContent, or `z-50` on a HoverCardContent). This mode flags a
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 4790e5c265..874a5f45f2 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -35,6 +35,7 @@ import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@/src/features/filters/cons
import { logger } from "@langfuse/shared/src/server";
import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";
import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/ee/features/in-app-agent/constants";
+import { assertUnreachable } from "@/src/utils/types";
const ASSISTANT_TITLE = "Langfuse Assistant";
const IN_APP_AGENT_SYSTEM_PROMPT_NAME = "in-app-agent-system-prompt";
@@ -861,7 +862,13 @@ type PatchableMastraAgent = {
};
type MastraStreamChunk = {
- type?: string;
+ type?:
+ | "tool-call-input-streaming-start"
+ | "tool-call-delta"
+ | "tool-call-input-streaming-end"
+ | "tool-call"
+ | "tool-call-approval"
+ | "tool-call-suspended";
payload?: {
toolCallId?: string;
toolName?: string;
@@ -872,6 +879,44 @@ type MastraStreamChunk = {
};
};
+type MastraStreamChunkType = NonNullable<MastraStreamChunk["type"]>;
+
+const MASTRA_STREAM_CHUNK_TYPES = [
+ "tool-call-input-streaming-start",
+ "tool-call-delta",
+ "tool-call-input-streaming-end",
+ "tool-call",
+ "tool-call-approval",
+ "tool-call-suspended",
+] as const satisfies readonly MastraStreamChunkType[];
+
+function isMastraStreamChunkType(type: unknown): type is MastraStreamChunkType {
+ return (
+ typeof type === "string" &&
+ MASTRA_STREAM_CHUNK_TYPES.some((chunkType) => chunkType === type)
+ );
+}
+
+function isMastraStreamChunk(chunk: unknown): chunk is MastraStreamChunk {
+ if (typeof chunk !== "object" || chunk === null) {
+ return false;
+ }
+
+ if (!("type" in chunk) || chunk.type === undefined) {
+ return true;
+ }
+
+ if (!isMastraStreamChunkType(chunk.type)) {
+ return false;
+ }
+
+ if (!("payload" in chunk) || chunk.payload === undefined) {
+ return true;
+ }
+
+ return typeof chunk.payload === "object" && chunk.payload !== null;
+}
+
type StreamingToolCall = {
toolCallId: string;
toolName: string;
@@ -904,127 +949,143 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
return {
handleChunk(chunk: unknown) {
- const mastraChunk = chunk as MastraStreamChunk;
+ if (!isMastraStreamChunk(chunk)) {
+ logger.warn(
+ "Received unknown Mastra chunk while patching tool-call input streaming",
+ chunk,
+ );
+ return processor.handleChunk(chunk);
+ }
- switch (mastraChunk.type) {
- case "tool-call-input-streaming-start": {
- const { toolCallId, toolName } = mastraChunk.payload ?? {};
- if (!toolCallId || !toolName) {
- callbacks.onError(
- new Error(
- "Malformed tool-call-input-streaming-start: missing toolCallId or toolName in payload",
- ),
- );
- return true;
- }
+ const mastraChunk = chunk;
- streamingToolCalls.set(toolCallId, {
- toolCallId,
- toolName,
- argsText: "",
- });
- return false;
+ if (mastraChunk.type === "tool-call-input-streaming-start") {
+ const { toolCallId, toolName } = mastraChunk.payload ?? {};
+ if (!toolCallId || !toolName) {
+ callbacks.onError(
+ new Error(
+ "Malformed tool-call-input-streaming-start: missing toolCallId or toolName in payload",
+ ),
+ );
+ return true;
}
- case "tool-call-delta": {
- const { toolCallId, toolName, argsTextDelta } =
- mastraChunk.payload ?? {};
- if (!toolCallId) {
+
+ streamingToolCalls.set(toolCallId, {
+ toolCallId,
+ toolName,
+ argsText: "",
+ });
+ return false;
+ }
+
+ if (mastraChunk.type === "tool-call-delta") {
+ const { toolCallId, toolName, argsTextDelta } =
+ mastraChunk.payload ?? {};
+ if (!toolCallId) {
+ callbacks.onError(
+ new Error(
+ "Malformed tool-call-delta: missing toolCallId in payload",
+ ),
+ );
+ return true;
+ }
+
+ let streamingToolCall = streamingToolCalls.get(toolCallId);
+ if (!streamingToolCall) {
+ if (!toolName) {
callbacks.onError(
new Error(
- "Malformed tool-call-delta: missing toolCallId in payload",
+ "Malformed tool-call-delta: missing toolName for unknown toolCallId in payload",
),
);
return true;
}
- let streamingToolCall = streamingToolCalls.get(toolCallId);
- if (!streamingToolCall) {
- if (!toolName) {
- callbacks.onError(
- new Error(
- "Malformed tool-call-delta: missing toolName for unknown toolCallId in payload",
- ),
- );
- return true;
- }
+ streamingToolCall = { toolCallId, toolName, argsText: "" };
+ streamingToolCalls.set(toolCallId, streamingToolCall);
+ }
- streamingToolCall = { toolCallId, toolName, argsText: "" };
- streamingToolCalls.set(toolCallId, streamingToolCall);
- }
+ streamingToolCall.argsText += argsTextDelta ?? "";
+ return false;
+ }
- streamingToolCall.argsText += argsTextDelta ?? "";
- return false;
+ if (mastraChunk.type === "tool-call-input-streaming-end") {
+ const { toolCallId } = mastraChunk.payload ?? {};
+ const streamingToolCall = toolCallId
+ ? streamingToolCalls.get(toolCallId)
+ : undefined;
+ if (streamingToolCall) {
+ synthesizedToolCallIds.add(streamingToolCall.toolCallId);
+ const shouldStop = processor.handleChunk({
+ type: "tool-call",
+ payload: {
+ toolCallId: streamingToolCall.toolCallId,
+ toolName: streamingToolCall.toolName,
+ args: parseStreamingToolCallArgs(streamingToolCall.argsText),
+ },
+ });
+ streamingToolCalls.delete(streamingToolCall.toolCallId);
+ return shouldStop;
}
- case "tool-call-input-streaming-end": {
- const { toolCallId } = mastraChunk.payload ?? {};
- const streamingToolCall = toolCallId
- ? streamingToolCalls.get(toolCallId)
- : undefined;
- if (streamingToolCall) {
- synthesizedToolCallIds.add(streamingToolCall.toolCallId);
- const shouldStop = processor.handleChunk({
- type: "tool-call",
- payload: {
- toolCallId: streamingToolCall.toolCallId,
- toolName: streamingToolCall.toolName,
- args: parseStreamingToolCallArgs(streamingToolCall.argsText),
- },
- });
- streamingToolCalls.delete(streamingToolCall.toolCallId);
- return shouldStop;
- }
+ return false;
+ }
+
+ if (mastraChunk.type === "tool-call") {
+ const { toolCallId } = mastraChunk.payload ?? {};
+ if (toolCallId && synthesizedToolCallIds.has(toolCallId)) {
+ synthesizedToolCallIds.delete(toolCallId);
return false;
}
- case "tool-call": {
- const { toolCallId } = mastraChunk.payload ?? {};
- if (toolCallId && synthesizedToolCallIds.has(toolCallId)) {
- synthesizedToolCallIds.delete(toolCallId);
- return false;
- }
- break;
+
+ return processor.handleChunk(chunk);
+ }
+
+ if (mastraChunk.type === "tool-call-approval") {
+ const { toolCallId, toolName, args, resumeSchema } =
+ mastraChunk.payload ?? {};
+ if (!toolCallId || !toolName) {
+ callbacks.onError(
+ new Error(
+ "Malformed tool-call-approval: missing toolCallId or toolName in payload",
+ ),
+ );
+ return true;
}
- case "tool-call-approval": {
- const { toolCallId, toolName, args, resumeSchema } =
- mastraChunk.payload ?? {};
- if (!toolCallId || !toolName) {
- callbacks.onError(
- new Error(
- "Malformed tool-call-approval: missing toolCallId or toolName in payload",
- ),
- );
- return true;
- }
- streamingToolCalls.delete(toolCallId);
- synthesizedToolCallIds.delete(toolCallId);
+ streamingToolCalls.delete(toolCallId);
+ synthesizedToolCallIds.delete(toolCallId);
- return processor.handleChunk({
- type: "tool-call-suspended",
- payload: {
+ return processor.handleChunk({
+ type: "tool-call-suspended",
+ payload: {
+ toolCallId,
+ toolName,
+ args,
+ resumeSchema,
+ suspendPayload: {
+ type: "approval",
toolCallId,
toolName,
args,
- resumeSchema,
- suspendPayload: {
- type: "approval",
- toolCallId,
- toolName,
- args,
- },
},
- });
- }
- case "tool-call-suspended": {
- const { toolCallId } = mastraChunk.payload ?? {};
- if (toolCallId) {
- streamingToolCalls.delete(toolCallId);
- synthesizedToolCallIds.delete(toolCallId);
- }
- break;
+ },
+ });
+ }
+
+ if (mastraChunk.type === "tool-call-suspended") {
+ const { toolCallId } = mastraChunk.payload ?? {};
+ if (toolCallId) {
+ streamingToolCalls.delete(toolCallId);
+ synthesizedToolCallIds.delete(toolCallId);
}
+ return processor.handleChunk(chunk);
+ }
+
+ if (mastraChunk.type === undefined) {
+ return processor.handleChunk(chunk);
}
- return processor.handleChunk(chunk);
+ return assertUnreachable(mastraChunk.type);
},
flush() {
processor.flush();
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 3857961e87..80a55e740c 100644
--- a/web/src/ee/features/in-app-agent/server/instrumentation.ts
+++ b/web/src/ee/features/in-app-agent/server/instrumentation.ts
@@ -12,6 +12,7 @@ import type {
} from "@/src/ee/features/in-app-agent/schema";
import { compactTextMessageChunks } from "@/src/ee/features/in-app-agent/server/eventCompaction";
import type { InAppAgentUserAccess } from "@/src/ee/features/in-app-agent/server/tools";
+import { assertUnreachable } from "@/src/utils/types";
export type InAppAgentTracingConfig = {
environment: string;
@@ -346,62 +347,94 @@ export class InAppAgentInstrumentation {
}
private recordEvent(event: AgUiEvent) {
- switch (event.type) {
- case EventType.TEXT_MESSAGE_CHUNK:
- case EventType.TEXT_MESSAGE_CONTENT:
- if (typeof event.delta === "string") {
- this.recordAssistantText(event.delta);
- }
- return;
- case EventType.REASONING_MESSAGE_CHUNK:
- case EventType.REASONING_MESSAGE_CONTENT:
- if (typeof event.delta === "string") {
- this.reasoning += event.delta;
- }
- return;
- case EventType.TOOL_CALL_START:
- this.startToolSpan(event);
- return;
- case EventType.TOOL_CALL_ARGS:
- this.appendToolArgs(event);
- return;
- case EventType.TOOL_CALL_RESULT:
- this.recordToolResult(event);
- return;
- case EventType.TOOL_CALL_END:
- this.endToolSpan(event);
- return;
- case EventType.RUN_ERROR:
- this.endWithError(
- typeof event.message === "string"
- ? event.message
- : "Unknown assistant error",
- );
- return;
- case EventType.RUN_FINISHED:
- this.end({ result: event.result });
- return;
- case EventType.RUN_STARTED:
- case EventType.TEXT_MESSAGE_START:
- case EventType.TEXT_MESSAGE_END:
- case EventType.STATE_SNAPSHOT:
- case EventType.STATE_DELTA:
- case EventType.MESSAGES_SNAPSHOT:
- case EventType.ACTIVITY_SNAPSHOT:
- case EventType.ACTIVITY_DELTA:
- case EventType.RAW:
- case EventType.CUSTOM:
- case EventType.STEP_STARTED:
- case EventType.STEP_FINISHED:
- case EventType.REASONING_START:
- case EventType.REASONING_MESSAGE_START:
- case EventType.REASONING_MESSAGE_END:
- case EventType.REASONING_END:
- case EventType.REASONING_ENCRYPTED_VALUE:
- return;
- default:
- return;
+ if (
+ event.type === EventType.TEXT_MESSAGE_CHUNK ||
+ event.type === EventType.TEXT_MESSAGE_CONTENT
+ ) {
+ if (typeof event.delta === "string") {
+ this.recordAssistantText(event.delta);
+ }
+ return;
+ }
+
+ if (
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT
+ ) {
+ if (typeof event.delta === "string") {
+ this.reasoning += event.delta;
+ }
+ return;
+ }
+
+ if (event.type === EventType.TOOL_CALL_START) {
+ this.startToolSpan(event);
+ return;
+ }
+
+ if (event.type === EventType.TOOL_CALL_ARGS) {
+ this.appendToolArgs(event);
+ return;
+ }
+
+ if (event.type === EventType.TOOL_CALL_RESULT) {
+ this.recordToolResult(event);
+ return;
+ }
+
+ if (event.type === EventType.TOOL_CALL_END) {
+ this.endToolSpan(event);
+ return;
+ }
+
+ if (event.type === EventType.RUN_ERROR) {
+ this.endWithError(
+ typeof event.message === "string"
+ ? event.message
+ : "Unknown assistant error",
+ );
+ return;
+ }
+
+ if (event.type === EventType.RUN_FINISHED) {
+ this.end({ result: event.result });
+ return;
+ }
+
+ if (
+ event.type === EventType.RUN_STARTED ||
+ event.type === EventType.TEXT_MESSAGE_START ||
+ event.type === EventType.TEXT_MESSAGE_END ||
+ event.type === EventType.STATE_SNAPSHOT ||
+ event.type === EventType.STATE_DELTA ||
+ event.type === EventType.MESSAGES_SNAPSHOT ||
+ event.type === EventType.ACTIVITY_SNAPSHOT ||
+ event.type === EventType.ACTIVITY_DELTA ||
+ event.type === EventType.RAW ||
+ event.type === EventType.CUSTOM ||
+ event.type === EventType.STEP_STARTED ||
+ event.type === EventType.STEP_FINISHED ||
+ event.type === EventType.TOOL_CALL_CHUNK ||
+ event.type === EventType.REASONING_START ||
+ event.type === EventType.REASONING_MESSAGE_START ||
+ event.type === EventType.REASONING_MESSAGE_END ||
+ event.type === EventType.REASONING_END ||
+ event.type === EventType.REASONING_ENCRYPTED_VALUE ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_END ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_CONTENT ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_END
+ ) {
+ return;
}
+
+ return assertUnreachable(event.type);
}
private startToolSpan(event: AgUiEvent) {
@@ -716,57 +749,63 @@ function getAgentRunAvailableSkills(
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":
+ if (message.role === "developer" || message.role === "system") {
+ return [
+ {
+ role: message.role,
+ ...(message.name ? { name: message.name } : {}),
+ content: message.content,
+ },
+ ];
+ }
+
+ if (message.role === "user") {
+ return [
+ {
+ role: "user",
+ ...(message.name ? { name: message.name } : {}),
+ content: normalizeUserMessageContent(message.content),
+ },
+ ];
+ }
+
+ if (message.role === "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 } : {}),
+ },
+ ];
}
+
+ if (message.role === "tool") {
+ return [
+ {
+ role: "tool",
+ tool_call_id: message.toolCallId,
+ content: parseJsonOrString(message.content),
+ },
+ ];
+ }
+
+ if (message.role === "activity" || message.role === "reasoning") {
+ return [];
+ }
+
+ return assertUnreachable(message);
});
}
diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.ts
index 8535d7b5fe..39d6d7f276 100644
--- a/web/src/ee/features/in-app-agent/server/persistence.ts
+++ b/web/src/ee/features/in-app-agent/server/persistence.ts
@@ -20,6 +20,7 @@ import {
getLangfuseAITraceSinkParams,
} from "@/src/features/ai-features/server/bedrockCompletion";
import { truncate } from "@/src/utils/string";
+import { assertUnreachable } from "@/src/utils/types";
import {
AgUiMessageSchema,
InAppAgentRedirectActionToolResultSchema,
@@ -516,115 +517,166 @@ export function shouldFlushPersistedEvent(event: AgUiEvent) {
}
export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {
- switch (event.type) {
- case EventType.RUN_STARTED: {
- const input = isRecord(event.input)
- ? {
- ...event.input,
- messages: Array.isArray(event.input.messages)
- ? parseMessages(event.input.messages)
- : [],
- tools: [],
- context: [],
- forwardedProps: {},
- }
- : undefined;
-
- return compactObject({
- type: event.type,
- threadId: getString(event, "threadId"),
- runId: getString(event, "runId"),
- parentRunId: getString(event, "parentRunId"),
- input,
- });
- }
- case EventType.MESSAGES_SNAPSHOT:
- return null;
- case EventType.TEXT_MESSAGE_CHUNK: {
- const messageId = getString(event, "messageId");
- const role = getTextChunkRole(event);
+ if (event.type === EventType.RUN_STARTED) {
+ const input = isRecord(event.input)
+ ? {
+ ...event.input,
+ messages: Array.isArray(event.input.messages)
+ ? parseMessages(event.input.messages)
+ : [],
+ tools: [],
+ context: [],
+ forwardedProps: {},
+ }
+ : undefined;
- if (!messageId || role !== "assistant") {
- return null;
- }
+ return compactObject({
+ type: event.type,
+ threadId: getString(event, "threadId"),
+ runId: getString(event, "runId"),
+ parentRunId: getString(event, "parentRunId"),
+ input,
+ });
+ }
- return compactObject({
- type: event.type,
- messageId,
- role,
- delta: getString(event, "delta") ?? "",
- });
- }
- case EventType.TEXT_MESSAGE_START:
- return compactObject({
- type: event.type,
- messageId: getString(event, "messageId"),
- role: getString(event, "role"),
- name: getString(event, "name"),
- });
- case EventType.TEXT_MESSAGE_CONTENT:
- return compactObject({
- type: event.type,
- messageId: getString(event, "messageId"),
- delta: getString(event, "delta") ?? "",
- });
- case EventType.TEXT_MESSAGE_END:
- return compactObject({
- type: event.type,
- messageId: getString(event, "messageId"),
- });
- case EventType.TOOL_CALL_START:
- return compactObject({
- type: event.type,
- toolCallId: getString(event, "toolCallId"),
- toolCallName: getString(event, "toolCallName"),
- parentMessageId: getString(event, "parentMessageId"),
- });
- case EventType.TOOL_CALL_ARGS:
- return compactObject({
- type: event.type,
- toolCallId: getString(event, "toolCallId"),
- delta: getString(event, "delta") ?? "",
- });
- case EventType.TOOL_CALL_END:
- return compactObject({
- type: event.type,
- toolCallId: getString(event, "toolCallId"),
- });
- case EventType.TOOL_CALL_RESULT:
- return compactObject({
- type: event.type,
- messageId: getString(event, "messageId"),
- toolCallId: getString(event, "toolCallId"),
- content: getString(event, "content"),
- role: getString(event, "role"),
- error: getString(event, "error"),
- });
- case EventType.ACTIVITY_SNAPSHOT:
- return compactObject({
- type: event.type,
- messageId: getString(event, "messageId"),
- activityType: getString(event, "activityType"),
- content: isRecord(event.content) ? event.content : undefined,
- replace: typeof event.replace === "boolean" ? event.replace : undefined,
- });
- case EventType.RUN_FINISHED:
- return compactObject({
- type: event.type,
- threadId: getString(event, "threadId"),
- runId: getString(event, "runId"),
- });
- case EventType.RUN_ERROR:
- return compactObject({
- type: event.type,
- threadId: getString(event, "threadId"),
- runId: getString(event, "runId"),
- message: getString(event, "message"),
- code: getString(event, "code"),
- });
- default:
+ if (event.type === EventType.MESSAGES_SNAPSHOT) {
+ return null;
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_CHUNK) {
+ const messageId = getString(event, "messageId");
+ const role = getTextChunkRole(event);
+
+ if (!messageId || role !== "assistant") {
return null;
+ }
+
+ return compactObject({
+ type: event.type,
+ messageId,
+ role,
+ delta: getString(event, "delta") ?? "",
+ });
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_START) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ role: getString(event, "role"),
+ name: getString(event, "name"),
+ });
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_CONTENT) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ delta: getString(event, "delta") ?? "",
+ });
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_END) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ });
+ }
+
+ if (event.type === EventType.TOOL_CALL_START) {
+ return compactObject({
+ type: event.type,
+ toolCallId: getString(event, "toolCallId"),
+ toolCallName: getString(event, "toolCallName"),
+ parentMessageId: getString(event, "parentMessageId"),
+ });
+ }
+
+ if (event.type === EventType.TOOL_CALL_ARGS) {
+ return compactObject({
+ type: event.type,
+ toolCallId: getString(event, "toolCallId"),
+ delta: getString(event, "delta") ?? "",
+ });
+ }
+
+ if (event.type === EventType.TOOL_CALL_END) {
+ return compactObject({
+ type: event.type,
+ toolCallId: getString(event, "toolCallId"),
+ });
+ }
+
+ if (event.type === EventType.TOOL_CALL_RESULT) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ toolCallId: getString(event, "toolCallId"),
+ content: getString(event, "content"),
+ role: getString(event, "role"),
+ error: getString(event, "error"),
+ });
+ }
+
+ if (event.type === EventType.ACTIVITY_SNAPSHOT) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ activityType: getString(event, "activityType"),
+ content: isRecord(event.content) ? event.content : undefined,
+ replace: typeof event.replace === "boolean" ? event.replace : undefined,
+ });
+ }
+
+ if (event.type === EventType.RUN_FINISHED) {
+ return compactObject({
+ type: event.type,
+ threadId: getString(event, "threadId"),
+ runId: getString(event, "runId"),
+ });
+ }
+
+ if (event.type === EventType.RUN_ERROR) {
+ return compactObject({
+ type: event.type,
+ threadId: getString(event, "threadId"),
+ runId: getString(event, "runId"),
+ message: getString(event, "message"),
+ code: getString(event, "code"),
+ });
}
+
+ if (
+ event.type === EventType.STATE_SNAPSHOT ||
+ event.type === EventType.STATE_DELTA ||
+ event.type === EventType.ACTIVITY_DELTA ||
+ event.type === EventType.RAW ||
+ event.type === EventType.CUSTOM ||
+ event.type === EventType.STEP_STARTED ||
+ event.type === EventType.STEP_FINISHED ||
+ event.type === EventType.TOOL_CALL_CHUNK ||
+ event.type === EventType.REASONING_START ||
+ event.type === EventType.REASONING_MESSAGE_START ||
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT ||
+ event.type === EventType.REASONING_MESSAGE_END ||
+ event.type === EventType.REASONING_END ||
+ event.type === EventType.REASONING_ENCRYPTED_VALUE ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_END ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_CONTENT ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_END
+ ) {
+ return null;
+ }
+
+ return assertUnreachable(event.type);
}
export function createConversationMessageAccumulator(
@@ -674,176 +726,214 @@ export function createConversationMessageAccumulator(
}
const processEvent = (event: AgUiEvent, runId?: string): boolean => {
- switch (event.type) {
- case EventType.RUN_STARTED: {
- if (!isRecord(event.input) || !Array.isArray(event.input.messages)) {
- break;
- }
+ if (event.type === EventType.RUN_STARTED) {
+ if (!isRecord(event.input) || !Array.isArray(event.input.messages)) {
+ return false;
+ }
- let changed = false;
+ let changed = false;
- for (const message of parseMessages(event.input.messages)) {
- changed = upsertMessage(message) || changed;
- }
+ for (const message of parseMessages(event.input.messages)) {
+ changed = upsertMessage(message) || changed;
+ }
- return changed;
+ return changed;
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_CHUNK) {
+ const messageId = getString(event, "messageId");
+ const role = getTextChunkRole(event);
+
+ if (!messageId || role !== "assistant") {
+ return false;
}
- case EventType.TEXT_MESSAGE_CHUNK: {
- const messageId = getString(event, "messageId");
- const role = getTextChunkRole(event);
- if (!messageId || role !== "assistant") {
- break;
- }
+ const existingIndex = messageIndexes.get(messageId);
+ const existingMessage =
+ existingIndex === undefined ? undefined : messages[existingIndex];
+ const existingContent =
+ existingMessage?.role === "assistant"
+ ? existingMessage.content
+ : undefined;
+ const draft = textDrafts.get(messageId) ?? {
+ id: messageId,
+ content: existingContent ?? "",
+ runId,
+ };
+
+ draft.content += getString(event, "delta") ?? "";
+ draft.runId ??= runId;
+ textDrafts.set(messageId, draft);
+
+ return upsertMessage({
+ id: draft.id,
+ role: "assistant",
+ content: draft.content,
+ ...(draft.runId ? { runId: draft.runId } : {}),
+ });
+ }
- const existingIndex = messageIndexes.get(messageId);
- const existingMessage =
- existingIndex === undefined ? undefined : messages[existingIndex];
- const existingContent =
- existingMessage?.role === "assistant"
- ? existingMessage.content
- : undefined;
- const draft = textDrafts.get(messageId) ?? {
- id: messageId,
- content: existingContent ?? "",
- runId,
- };
+ if (event.type === EventType.TEXT_MESSAGE_START) {
+ const messageId = getString(event, "messageId");
+
+ if (messageId && getString(event, "role") === "assistant") {
+ textDrafts.set(messageId, { id: messageId, content: "", runId });
+ }
+ return false;
+ }
+
+ if (event.type === EventType.TEXT_MESSAGE_CONTENT) {
+ const messageId = getString(event, "messageId");
+ const delta = getString(event, "delta") ?? "";
+ const draft = messageId ? textDrafts.get(messageId) : undefined;
- draft.content += getString(event, "delta") ?? "";
+ if (draft) {
+ draft.content += delta;
draft.runId ??= runId;
- textDrafts.set(messageId, draft);
+ }
+ return false;
+ }
- return upsertMessage({
- id: draft.id,
- role: "assistant",
- content: draft.content,
- ...(draft.runId ? { runId: draft.runId } : {}),
- });
+ if (event.type === EventType.TEXT_MESSAGE_END) {
+ const messageId = getString(event, "messageId");
+ const draft = messageId ? textDrafts.get(messageId) : undefined;
+
+ if (!draft) {
+ return false;
}
- case EventType.TEXT_MESSAGE_START: {
- const messageId = getString(event, "messageId");
- if (messageId && getString(event, "role") === "assistant") {
- textDrafts.set(messageId, { id: messageId, content: "", runId });
- }
- break;
+ const changed = upsertMessage({
+ id: draft.id,
+ role: "assistant",
+ content: draft.content,
+ ...((draft.runId ?? runId) ? { runId: draft.runId ?? runId } : {}),
+ });
+
+ textDrafts.delete(draft.id);
+ return changed;
+ }
+
+ if (event.type === EventType.TOOL_CALL_START) {
+ const toolCallId = getString(event, "toolCallId");
+ const parentMessageId = getString(event, "parentMessageId");
+ const name = getString(event, "toolCallName");
+
+ if (toolCallId && parentMessageId && name) {
+ toolCallDrafts.set(toolCallId, {
+ parentMessageId,
+ name,
+ args: "",
+ runId,
+ });
}
- case EventType.TEXT_MESSAGE_CONTENT: {
- const messageId = getString(event, "messageId");
- const delta = getString(event, "delta") ?? "";
- const draft = messageId ? textDrafts.get(messageId) : undefined;
-
- if (draft) {
- draft.content += delta;
- draft.runId ??= runId;
- }
- break;
+ return false;
+ }
+
+ if (event.type === EventType.TOOL_CALL_ARGS) {
+ const toolCallId = getString(event, "toolCallId");
+ const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;
+
+ if (draft) {
+ draft.args += getString(event, "delta") ?? "";
}
- case EventType.TEXT_MESSAGE_END: {
- const messageId = getString(event, "messageId");
- const draft = messageId ? textDrafts.get(messageId) : undefined;
+ return false;
+ }
- if (!draft) {
- break;
- }
+ if (event.type === EventType.TOOL_CALL_END) {
+ const toolCallId = getString(event, "toolCallId");
+ const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;
+ if (toolCallId && draft) {
const changed = upsertMessage({
- id: draft.id,
+ id: draft.parentMessageId,
role: "assistant",
- content: draft.content,
...((draft.runId ?? runId) ? { runId: draft.runId ?? runId } : {}),
+ toolCalls: [
+ {
+ id: toolCallId,
+ type: "function",
+ function: {
+ name: draft.name,
+ arguments: draft.args,
+ },
+ },
+ ],
});
-
- textDrafts.delete(draft.id);
+ toolCallDrafts.delete(toolCallId);
return changed;
}
- case EventType.TOOL_CALL_START: {
- const toolCallId = getString(event, "toolCallId");
- const parentMessageId = getString(event, "parentMessageId");
- const name = getString(event, "toolCallName");
-
- if (toolCallId && parentMessageId && name) {
- toolCallDrafts.set(toolCallId, {
- parentMessageId,
- name,
- args: "",
- runId,
- });
- }
- break;
- }
- case EventType.TOOL_CALL_ARGS: {
- const toolCallId = getString(event, "toolCallId");
- const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;
+ return false;
+ }
- if (draft) {
- draft.args += getString(event, "delta") ?? "";
- }
- break;
- }
- case EventType.TOOL_CALL_END: {
- const toolCallId = getString(event, "toolCallId");
- const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;
-
- if (toolCallId && draft) {
- const changed = upsertMessage({
- id: draft.parentMessageId,
- role: "assistant",
- ...((draft.runId ?? runId) ? { runId: draft.runId ?? runId } : {}),
- toolCalls: [
- {
- id: toolCallId,
- type: "function",
- function: {
- name: draft.name,
- arguments: draft.args,
- },
- },
- ],
- });
- toolCallDrafts.delete(toolCallId);
- return changed;
- }
- break;
- }
- case EventType.TOOL_CALL_RESULT: {
- const messageId = getString(event, "messageId");
- const toolCallId = getString(event, "toolCallId");
- const content = getString(event, "content");
-
- if (messageId && toolCallId && content !== undefined) {
- return upsertMessage({
- id: messageId,
- role: "tool",
- content,
- toolCallId,
- ...(getString(event, "error")
- ? { error: getString(event, "error") }
- : {}),
- });
- }
- break;
+ if (event.type === EventType.TOOL_CALL_RESULT) {
+ const messageId = getString(event, "messageId");
+ const toolCallId = getString(event, "toolCallId");
+ const content = getString(event, "content");
+
+ if (messageId && toolCallId && content !== undefined) {
+ return upsertMessage({
+ id: messageId,
+ role: "tool",
+ content,
+ toolCallId,
+ ...(getString(event, "error")
+ ? { error: getString(event, "error") }
+ : {}),
+ });
}
- case EventType.ACTIVITY_SNAPSHOT: {
- const messageId = getString(event, "messageId");
- const activityType = getString(event, "activityType");
- const content = event.content;
-
- if (messageId && activityType && isRecord(content)) {
- return upsertMessage({
- id: messageId,
- role: "activity",
- activityType,
- content,
- });
- }
- break;
+ return false;
+ }
+
+ if (event.type === EventType.ACTIVITY_SNAPSHOT) {
+ const messageId = getString(event, "messageId");
+ const activityType = getString(event, "activityType");
+ const content = event.content;
+
+ if (messageId && activityType && isRecord(content)) {
+ return upsertMessage({
+ id: messageId,
+ role: "activity",
+ activityType,
+ content,
+ });
}
- default:
- break;
+ return false;
}
- return false;
+ if (
+ event.type === EventType.MESSAGES_SNAPSHOT ||
+ event.type === EventType.RUN_FINISHED ||
+ event.type === EventType.RUN_ERROR ||
+ event.type === EventType.STATE_SNAPSHOT ||
+ event.type === EventType.STATE_DELTA ||
+ event.type === EventType.ACTIVITY_DELTA ||
+ event.type === EventType.RAW ||
+ event.type === EventType.CUSTOM ||
+ event.type === EventType.STEP_STARTED ||
+ event.type === EventType.STEP_FINISHED ||
+ event.type === EventType.TOOL_CALL_CHUNK ||
+ event.type === EventType.REASONING_START ||
+ event.type === EventType.REASONING_MESSAGE_START ||
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT ||
+ event.type === EventType.REASONING_MESSAGE_END ||
+ event.type === EventType.REASONING_END ||
+ event.type === EventType.REASONING_ENCRYPTED_VALUE ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_END ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_START ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_CONTENT ||
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ event.type === EventType.THINKING_TEXT_MESSAGE_END
+ ) {
+ return false;
+ }
+
+ return assertUnreachable(event.type);
};
return {