Skip to content

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

refactor(agent): upgrade @ag-ui/mastra to 1.1.1 and remove custom chunk parsing (#15241)

Lysander Kieselb316fabf3a06
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 368d2af788..d39504498d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -51,6 +51,7 @@ overrides:
'@ai-sdk/provider-utils@<=4.0.26': 4.0.27
'@ai-sdk/provider-utils-v5': npm:@ai-sdk/[email protected]
+ '@ai-sdk/ui-utils>@ai-sdk/provider-utils': 2.2.8
'@copilotkit/[email protected]>@ag-ui/langgraph': 0.0.29
'@anthropic-ai/vertex-sdk>@anthropic-ai/sdk': 0.104.1
next-auth>nodemailer: ^9.0.3
@@ -419,8 +420,8 @@ importers:
specifier: ^0.0.52
version: 0.0.52
'@ag-ui/mastra':
- specifier: 1.0.3
+ specifier: 1.1.1
'@ai-sdk/amazon-bedrock':
specifier: 4.0.81
version: 4.0.81([email protected])
@@ -1147,6 +1148,9 @@ packages:
resolution: {integrity: sha512-Ff9+ksdQQB3rMncgqDK78uLznstjyfIf2Arnh22pW8kBpLs6rpKDwgnZT46hin5Hl1WzazzK64DOrhSwYpS7bQ==}
+ '@ag-ui/[email protected]':
+ resolution: {integrity: sha512-9VPmgpCAsFVICk7z23kh+Kp/BwYMxw0D0KGjOiKXhm1MAH+Wid2iC3yKsXso+q7UZZiyhWgeDUSgaAkltyLmGg==}
+
resolution: {integrity: sha512-9Bl6GN6N3NWa3Ewqgl8E3nJzo88prIB2LS50bTNgw35h5BxC1UY21c0SImqQWZ+VV5kbhs6AUrriypKEBB7F5A==}
@@ -1171,14 +1175,14 @@ packages:
'@ag-ui/client': '>=0.0.42'
'@ag-ui/core': '>=0.0.42'
- '@ag-ui/[email protected]':
- resolution: {integrity: sha512-KiUEg+m04afE6uw1M/SdldnMOxP9+E8tE2bAOhRBKxrWoUKIuVUOJoVkNxzRLmIDLG3bQFJti2ljpRyIJvnFNA==}
+ '@ag-ui/[email protected]':
+ resolution: {integrity: sha512-6j+3msihWB+b6sc1N+6APR6UM57n0ONR+YCfB7e1twCoyuINJ97z3MEYA5YY9SynTLpfJk58+Yk1wxckJL4v6g==}
peerDependencies:
'@ag-ui/client': '>=0.0.44'
'@ag-ui/core': '>=0.0.44'
- '@copilotkit/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603
+ '@copilotkit/runtime': ^1.60.1
'@mastra/client-js': '>=1.0.0-0 <2.0.0-0'
- '@mastra/core': '>=1.0.0-0 <2.0.0-0'
+ '@mastra/core': '>=1.29.0 <2.0.0-0'
resolution: {integrity: sha512-+FfVhB1OP5A1+5BrEccQnwfODTbfBRWT3+NVnbW4RDFUDVmO9EUA+XPuO1ZxWcDfziTvQriwm0vNyaXGidSIhw==}
@@ -1282,6 +1286,12 @@ packages:
peerDependencies:
zod: 4.3.6
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: 4.3.6
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw==}
engines: {node: '>=18'}
@@ -11652,6 +11662,8 @@ snapshots:
'@adobe/[email protected]': {}
+ '@ag-ui/[email protected]': {}
+
dependencies:
'@ag-ui/core': 0.0.46
@@ -11718,17 +11730,18 @@ snapshots:
- ws
- zod-to-json-schema
dependencies:
+ '@ag-ui/a2ui-toolkit': 0.0.4
'@ag-ui/client': 0.0.52
'@ag-ui/core': 0.0.52
'@ai-sdk/ui-utils': 1.2.11([email protected])
'@copilotkit/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(8a42fcd90342b5e5e0a318760eda49df)
+ fast-json-patch: 3.1.1
rxjs: 7.8.1
- transitivePeerDependencies:
- - zod
+ zod: 4.3.6
dependencies:
@@ -11858,6 +11871,13 @@ snapshots:
'@ai-sdk/provider-utils': 5.0.3([email protected])
zod: 4.3.6
+ dependencies:
+ '@ai-sdk/provider': 1.1.3
+ nanoid: 3.3.12
+ secure-json-parse: 2.7.0
+ zod: 4.3.6
+
dependencies:
'@ai-sdk/provider': 3.0.10
@@ -11908,7 +11928,7 @@ snapshots:
dependencies:
'@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 4.0.27([email protected])
+ '@ai-sdk/provider-utils': 2.2.8([email protected])
zod: 4.3.6
zod-to-json-schema: 3.25.2([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index b2691bf732..8a745baec5 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -58,6 +58,10 @@ overrides:
"@ai-sdk/provider-utils@<=4.0.26": 4.0.27
"@ai-sdk/provider-utils-v5": "npm:@ai-sdk/[email protected]"
+ # @ag-ui/mastra imports parsePartialJson from @ai-sdk/ui-utils, whose module
+ # evaluation needs exports (validatorSymbol) that only exist in its own
+ # provider-utils 2.x line — exempt it from the blanket 4.0.27 lift above.
+ "@ai-sdk/ui-utils>@ai-sdk/provider-utils": 2.2.8
"@copilotkit/[email protected]>@ag-ui/langgraph": 0.0.29
# Keep Anthropic's Vertex client on an SDK version that emits Vertex rawPredict URLs.
# Remove once @langchain/anthropic allows the same SDK range.
diff --git a/web/package.json b/web/package.json
index 14eac1bf63..043cf1f50b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -32,7 +32,7 @@
"dependencies": {
"@ag-ui/client": "^0.0.52",
"@ag-ui/core": "^0.0.52",
- "@ag-ui/mastra": "1.0.3",
+ "@ag-ui/mastra": "1.1.1",
"@ai-sdk/amazon-bedrock": "4.0.81",
"@appsignal/opentelemetry-instrumentation-bullmq": "^0.8.0",
"@astral-sh/ruff-wasm-web": "0.15.13",
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 f22d86d581..d85fc1667d 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -10,7 +10,7 @@ import {
IN_APP_AGENT_REDIRECT_TOOL_NAME,
IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
} from "@/src/ee/features/in-app-agent/constants";
-import { patchMastraToolCallInputStreaming } from "@/src/ee/features/in-app-agent/server/agent";
+import { patchMastraApprovalChunks } from "@/src/ee/features/in-app-agent/server/agent";
import {
createInAppAgentSandbox,
type SandboxProvider,
@@ -275,305 +275,21 @@ const createPatchedChunkProcessor = () => {
})),
};
- patchMastraToolCallInputStreaming(adapter as unknown as MastraAgent);
+ patchMastraApprovalChunks(adapter as unknown as MastraAgent);
const processor = adapter.createChunkProcessor({ onError });
return { forwardedChunks, onError, processor, flush };
};
-describe("patchMastraToolCallInputStreaming", () => {
- it("converts streamed tool-call input chunks to one native tool-call", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call-input-streaming-start",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: '{"query":"invite',
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: ' users"}',
- },
- });
- processor.handleChunk({
- type: "tool-call-input-streaming-end",
- payload: { toolCallId: "tool-call-1" },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- args: { query: "invite users" },
- },
- },
- ]);
- });
-
- it("uses empty args when streamed tool-call input is malformed JSON", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call-input-streaming-start",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: '{"query":"invite users"',
- },
- });
- processor.handleChunk({
- type: "tool-call-input-streaming-end",
- payload: { toolCallId: "tool-call-1" },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- args: {},
- },
- },
- ]);
- });
-
- it("suppresses one duplicate native tool-call after synthesizing it", () => {
- const { forwardedChunks, processor } = createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call-input-streaming-start",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: '{"query":"invite users"}',
- },
- });
- processor.handleChunk({
- type: "tool-call-input-streaming-end",
- payload: { toolCallId: "tool-call-1" },
- });
- processor.handleChunk({
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- args: { query: "invite users" },
- },
- });
- processor.handleChunk({
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-2",
- toolName: "langfuse_search",
- args: { traceId: "trace-1" },
- },
- });
-
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- args: { query: "invite users" },
- },
- },
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-2",
- toolName: "langfuse_search",
- args: { traceId: "trace-1" },
- },
- },
- ]);
- });
-
- it("passes non-tool streaming chunks through unchanged", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "step-start",
- payload: {},
- });
- processor.handleChunk({
- type: "text-start",
- payload: { textMessageId: "assistant-1" },
- });
- processor.handleChunk({
- type: "text-delta",
- payload: {
- textMessageId: "assistant-1",
- textDelta: "Investigating...",
- },
- });
- processor.handleChunk({
- type: "tool-result",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- result: { ok: true },
- },
- });
- processor.handleChunk({
- type: "step-finish",
- payload: {},
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "step-start",
- payload: {},
- },
- {
- type: "text-start",
- payload: { textMessageId: "assistant-1" },
- },
- {
- type: "text-delta",
- payload: {
- textMessageId: "assistant-1",
- textDelta: "Investigating...",
- },
- },
- {
- type: "tool-result",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuseDocs_search",
- result: { ok: true },
- },
- },
- {
- type: "step-finish",
- payload: {},
- },
- ]);
- });
-
- it("passes through native tool-calls that were not synthesized", () => {
- const { forwardedChunks, processor } = createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuse_search",
- args: { query: "errors" },
- },
- });
-
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuse_search",
- args: { query: "errors" },
- },
- },
- ]);
- });
-
- it("keeps suppressing the duplicate native tool-call after a tool-result arrives", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call-input-streaming-start",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "bash",
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: '{"command":"date"}',
- },
- });
- processor.handleChunk({
- type: "tool-call-input-streaming-end",
- payload: { toolCallId: "tool-call-1" },
- });
- processor.handleChunk({
- type: "tool-result",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "bash",
- result: "Wed Jul 08 2026",
- },
- });
- processor.handleChunk({
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "bash",
- args: { command: "date" },
- },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "bash",
- args: { command: "date" },
- },
- },
- {
- type: "tool-result",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "bash",
- result: "Wed Jul 08 2026",
- },
- },
- ]);
- });
-
+describe("patchMastraApprovalChunks", () => {
it("converts tool-call approval chunks to suspended tool calls", () => {
const { forwardedChunks, onError, processor } =
createPatchedChunkProcessor();
processor.handleChunk({
type: "tool-call-approval",
+ runId: "run-1",
payload: {
toolCallId: "tool-call-1",
toolName: "langfuse_createScoreConfig",
@@ -591,6 +307,7 @@ describe("patchMastraToolCallInputStreaming", () => {
expect(forwardedChunks).toEqual([
{
type: "tool-call-suspended",
+ runId: "run-1",
payload: {
toolCallId: "tool-call-1",
toolName: "langfuse_createScoreConfig",
@@ -617,61 +334,6 @@ describe("patchMastraToolCallInputStreaming", () => {
]);
});
- it("drops streamed tool-call args when the tool call becomes an approval", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "tool-call-input-streaming-start",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuse_createScoreConfig",
- },
- });
- processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta:
- '{"name":"readiness","dataType":"NUMERIC","numericMinValue":0,"numericMaxValue":1}',
- },
- });
- processor.handleChunk({
- type: "tool-call-approval",
- payload: {
- toolCallId: "tool-call-1",
- toolName: "langfuse_createScoreConfig",
- args: {
- name: "readiness",
- dataType: "NUMERIC",
- numericMinValue: 0,
- numericMaxValue: 1,
- },
- },
- });
- processor.handleChunk({
- type: "tool-call-input-streaming-end",
- payload: { toolCallId: "tool-call-1" },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "tool-call-suspended",
- payload: expect.objectContaining({
- toolCallId: "tool-call-1",
- toolName: "langfuse_createScoreConfig",
- args: {
- name: "readiness",
- dataType: "NUMERIC",
- numericMinValue: 0,
- numericMaxValue: 1,
- },
- }),
- },
- ]);
- });
-
it("reports malformed tool-call approvals", () => {
const { forwardedChunks, onError, processor } =
createPatchedChunkProcessor();
@@ -693,123 +355,6 @@ describe("patchMastraToolCallInputStreaming", () => {
expect(forwardedChunks).toEqual([]);
});
- it("reports malformed tool-call deltas with no known tool name", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- const shouldStop = processor.handleChunk({
- type: "tool-call-delta",
- payload: {
- toolCallId: "tool-call-1",
- argsTextDelta: '{"query":"invite users"}',
- },
- });
-
- expect(shouldStop).toBe(true);
- expect(onError).toHaveBeenCalledWith(
- new Error(
- "Malformed tool-call-delta: missing toolName for unknown toolCallId in payload",
- ),
- );
- expect(forwardedChunks).toEqual([]);
- });
-
- it("passes through text streaming chunks", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "text-start",
- payload: { textMessageId: "message-1" },
- });
- processor.handleChunk({
- type: "text-delta",
- payload: { textMessageId: "message-1", textDelta: "hello" },
- });
- processor.handleChunk({
- type: "text-end",
- payload: { textMessageId: "message-1" },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "text-start",
- payload: { textMessageId: "message-1" },
- },
- {
- type: "text-delta",
- payload: { textMessageId: "message-1", textDelta: "hello" },
- },
- {
- type: "text-end",
- payload: { textMessageId: "message-1" },
- },
- ]);
- });
-
- it("passes lifecycle chunks through unchanged", () => {
- const { forwardedChunks, onError, processor } =
- createPatchedChunkProcessor();
-
- processor.handleChunk({
- type: "start",
- runId: "run-1",
- from: "AGENT",
- payload: { id: "langfuse-in-app-assistant", messageId: "message-1" },
- });
- processor.handleChunk({
- type: "step-start",
- runId: "run-1",
- from: "AGENT",
- payload: { request: {}, warnings: [], messageId: "message-1" },
- });
- processor.handleChunk({
- type: "step-finish",
- runId: "run-1",
- from: "AGENT",
- payload: {
- messageId: "message-1",
- stepResult: { reason: "tool-calls", isContinued: true },
- },
- });
-
- expect(onError).not.toHaveBeenCalled();
- expect(forwardedChunks).toEqual([
- {
- type: "start",
- from: "AGENT",
- runId: "run-1",
- payload: {
- id: "langfuse-in-app-assistant",
- messageId: "message-1",
- },
- },
- {
- type: "step-start",
- from: "AGENT",
- runId: "run-1",
- payload: {
- messageId: "message-1",
- request: {},
- warnings: [],
- },
- },
- {
- type: "step-finish",
- from: "AGENT",
- runId: "run-1",
- payload: {
- messageId: "message-1",
- stepResult: {
- isContinued: true,
- reason: "tool-calls",
- },
- },
- },
- ]);
- });
-
it("converts tool-error chunks to tool-result error chunks", () => {
const { forwardedChunks, onError, processor } =
createPatchedChunkProcessor();
@@ -817,7 +362,6 @@ describe("patchMastraToolCallInputStreaming", () => {
processor.handleChunk({
type: "tool-error",
runId: "run-1",
- from: "AGENT",
payload: {
toolCallId: "tool-call-1",
toolName: "bash",
@@ -832,41 +376,30 @@ describe("patchMastraToolCallInputStreaming", () => {
expect(forwardedChunks).toEqual([
{
type: "tool-result",
+ runId: "run-1",
payload: {
toolCallId: "tool-call-1",
toolName: "bash",
args: { command: "date" },
isError: true,
- result: JSON.stringify(
- {
- error: "Error: Region is missing",
- },
- null,
- 2,
- ),
+ result: { error: "Error: Region is missing" },
},
},
]);
});
- it("reports malformed tool-error chunks", () => {
+ it("passes other chunks through unchanged", () => {
const { forwardedChunks, onError, processor } =
createPatchedChunkProcessor();
+ const streamingChunk = {
+ type: "tool-call-delta",
+ payload: { toolCallId: "tool-call-1", argsTextDelta: '{"query":' },
+ };
- const shouldStop = processor.handleChunk({
- type: "tool-error",
- payload: {
- error: { message: "boom" },
- },
- });
+ processor.handleChunk(streamingChunk);
- expect(shouldStop).toBe(true);
- expect(onError).toHaveBeenCalledWith(
- new Error(
- "Malformed tool-error: missing toolCallId or toolName in payload",
- ),
- );
- expect(forwardedChunks).toEqual([]);
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([streamingChunk]);
});
});
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 7189c14ccc..c868bcb2d9 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -34,7 +34,6 @@ 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";
@@ -819,10 +818,12 @@ async function createMastraAdapter(params: {
const adapter = new MastraAgent({
agent,
resourceId: params.input.threadId,
+ // The structured RUN_FINISHED interrupt outcome targets CopilotKit
+ // >= 1.61.2 clients; ours consumes the legacy on_interrupt CUSTOM
+ // events, so keep the pre-flag behavior.
+ emitInterruptOutcome: false,
});
- // @ag-ui/[email protected] does not understand Mastra's newer streaming
- // tool-call chunks yet, so translate them locally to avoid warning noise.
- patchMastraToolCallInputStreaming(adapter);
+ patchMastraApprovalChunks(adapter);
return {
adapter,
@@ -896,29 +897,17 @@ type MastraStreamCallbacks = {
type PatchableMastraAgent = {
createChunkProcessor?: (
callbacks: MastraStreamCallbacks,
+ ...rest: unknown[]
) => MastraChunkProcessor;
};
-type MastraStreamChunk = {
- type?:
- | "start"
- | "step-start"
- | "step-finish"
- | "text-start"
- | "text-delta"
- | "text-end"
- | "tool-call-input-streaming-start"
- | "tool-call-delta"
- | "tool-call-input-streaming-end"
- | "tool-call"
- | "tool-result"
- | "tool-error"
- | "tool-call-approval"
- | "tool-call-suspended";
+type MastraApprovalStreamChunk = {
+ type?: string;
+ runId?: string;
payload?: {
- text?: string;
- textDelta?: string;
- textMessageId?: string;
+ toolCallId?: string;
+ toolName?: string;
+ args?: unknown;
error?: {
message?: string;
cause?: {
@@ -928,70 +917,21 @@ type MastraStreamChunk = {
errorMessage?: string;
};
};
- toolCallId?: string;
- toolName?: string;
- argsTextDelta?: string;
- args?: unknown;
- result?: unknown;
- isError?: boolean;
- resumeSchema?: unknown;
- suspendPayload?: unknown;
};
};
-type MastraStreamChunkType = NonNullable<MastraStreamChunk["type"]>;
-
-const MASTRA_STREAM_CHUNK_TYPES = [
- "start",
- "step-start",
- "step-finish",
- "text-start",
- "text-delta",
- "text-end",
- "tool-call-input-streaming-start",
- "tool-call-delta",
- "tool-call-input-streaming-end",
- "tool-call",
- "tool-result",
- "tool-error",
- "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;
- argsText: string;
-};
-
-export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
+// @ag-ui/mastra handles Mastra's suspend()-based interrupts natively
+// (tool-call-suspended), but not the requireApproval flow used by
+// withInAppAgentToolApproval: Mastra emits a tool-call-approval chunk for
+// those tools and the bridge has no case for it, so approvals would never
+// surface as on_interrupt events. Map approvals onto the suspend protocol.
+// Non-background tool-error chunks are likewise swallowed by the bridge, so
+// convert them to tool results carrying the error message as content. Note:
+// the bridge emits TOOL_CALL_RESULT without a top-level `error` field, so the
+// failure renders with the error message in the result body but a "succeeded"
+// status; the model is unaffected (Mastra's loop feeds it the real error).
+// Status fidelity is tracked as a follow-up.
+export function patchMastraApprovalChunks(adapter: MastraAgent) {
const patchableAdapter = adapter as unknown as PatchableMastraAgent;
const createChunkProcessor = patchableAdapter.createChunkProcessor;
@@ -1002,225 +942,76 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
patchableAdapter.createChunkProcessor = function patchedCreateChunkProcessor(
this: PatchableMastraAgent,
callbacks: MastraStreamCallbacks,
+ ...rest: unknown[]
) {
- const processor = createChunkProcessor.call(this, callbacks);
- const streamingToolCalls = new Map<string, StreamingToolCall>();
- const synthesizedToolCallIds = new Set<string>();
-
- const parseStreamingToolCallArgs = (argsText: string): unknown => {
- try {
- return JSON.parse(argsText || "{}");
- } catch {
- return {};
- }
- };
+ const processor = createChunkProcessor.call(this, callbacks, ...rest);
return {
handleChunk(chunk: unknown) {
- if (!isMastraStreamChunk(chunk)) {
- logger.warn(
- "Received unknown Mastra chunk while patching tool-call input streaming",
- chunk,
- );
-
- return processor.handleChunk(chunk);
- }
-
- const mastraChunk = chunk;
-
- if (mastraChunk.type === undefined) {
- return processor.handleChunk(chunk);
- }
-
- 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;
- }
+ const mastraChunk = chunk as MastraApprovalStreamChunk;
- streamingToolCalls.set(toolCallId, {
+ if (mastraChunk?.type === "tool-call-approval") {
+ const {
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 toolName for unknown toolCallId in payload",
- ),
- );
- return true;
- }
-
- streamingToolCall = { toolCallId, toolName, argsText: "" };
- streamingToolCalls.set(toolCallId, streamingToolCall);
- }
-
- 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;
- }
- return false;
- }
-
- if (mastraChunk.type === "tool-call") {
- const { toolCallId } = mastraChunk.payload ?? {};
- if (toolCallId && synthesizedToolCallIds.has(toolCallId)) {
- synthesizedToolCallIds.delete(toolCallId);
- return false;
- }
-
- return processor.handleChunk(chunk);
- }
-
- if (mastraChunk.type === "tool-error") {
- const { toolCallId, toolName, args } = mastraChunk.payload ?? {};
+ args: toolArgs,
+ } = mastraChunk.payload ?? {};
if (!toolCallId || !toolName) {
callbacks.onError(
new Error(
- "Malformed tool-error: missing toolCallId or toolName in payload",
+ "Malformed tool-call-approval: missing toolCallId or toolName in payload",
),
);
return true;
}
- streamingToolCalls.delete(toolCallId);
- synthesizedToolCallIds.delete(toolCallId);
-
return processor.handleChunk({
- type: "tool-result",
+ ...mastraChunk,
+ type: "tool-call-suspended",
payload: {
- toolCallId,
- toolName,
- args,
- isError: true,
- result: JSON.stringify(
- {
- error: ((): string => {
- if (
- typeof mastraChunk.payload?.error?.details
- ?.errorMessage === "string"
- ) {
- return mastraChunk.payload.error.details.errorMessage;
- }
-
- if (
- typeof mastraChunk.payload?.error?.cause?.message ===
- "string"
- ) {
- return mastraChunk.payload.error.cause.message;
- }
-
- if (
- typeof mastraChunk.payload?.error?.message === "string"
- ) {
- return mastraChunk.payload.error.message;
- }
-
- return "Unknown tool error";
- })(),
- },
- null,
- 2,
- ),
+ ...mastraChunk.payload,
+ suspendPayload: {
+ type: "approval",
+ toolCallId,
+ toolName,
+ args: toolArgs,
+ },
},
});
}
- if (mastraChunk.type === "tool-call-approval") {
- const { toolCallId, toolName, args, resumeSchema } =
- mastraChunk.payload ?? {};
+ if (mastraChunk?.type === "tool-error") {
+ const {
+ toolCallId,
+ toolName,
+ args: toolArgs,
+ } = mastraChunk.payload ?? {};
if (!toolCallId || !toolName) {
callbacks.onError(
new Error(
- "Malformed tool-call-approval: missing toolCallId or toolName in payload",
+ "Malformed tool-error: missing toolCallId or toolName in payload",
),
);
return true;
}
- streamingToolCalls.delete(toolCallId);
- synthesizedToolCallIds.delete(toolCallId);
-
return processor.handleChunk({
- type: "tool-call-suspended",
+ ...mastraChunk,
+ type: "tool-result",
payload: {
toolCallId,
toolName,
- args,
- resumeSchema,
- suspendPayload: {
- type: "approval",
- toolCallId,
- toolName,
- args,
- },
+ args: toolArgs,
+ isError: true,
+ // Raw object, not pre-stringified: the bridge JSON-stringifies
+ // payload.result into the event content, so a string here would
+ // double-encode.
+ result: { error: getToolErrorMessage(mastraChunk) },
},
});
}
- 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 === "start" ||
- mastraChunk.type === "step-start" ||
- mastraChunk.type === "step-finish" ||
- mastraChunk.type === "text-start" ||
- mastraChunk.type === "text-delta" ||
- mastraChunk.type === "text-end" ||
- mastraChunk.type === "tool-result"
- ) {
- return processor.handleChunk(chunk);
- }
-
- return assertUnreachable(mastraChunk.type);
+ return processor.handleChunk(chunk);
},
flush() {
processor.flush();
@@ -1229,6 +1020,24 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
};
}
+function getToolErrorMessage(chunk: MastraApprovalStreamChunk): string {
+ const error = chunk.payload?.error;
+
+ if (typeof error?.details?.errorMessage === "string") {
+ return error.details.errorMessage;
+ }
+
+ if (typeof error?.cause?.message === "string") {
+ return error.cause.message;
+ }
+
+ if (typeof error?.message === "string") {
+ return error.message;
+ }
+
+ return "Unknown tool error";
+}
+
async function getSystemPromptInstructions(params: {
langfuseClient: Langfuse;
useLocalPrompt: boolean;