🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(agent): Move in-app-agent runtime into shared package (#15421)
Lysander Kieselb97e8195289e
diff --git a/.prettierignore b/.prettierignoreindex 05f658f671..98f0ab19d3 100644--- a/.prettierignore+++ b/.prettierignore@@ -1,5 +1,9 @@# Generated codepackages/shared/prisma/generated+# Verbatim upstream skill markdown; must stay byte-identical for+# scripts/in-app-agent/sync-raw-skills.mjs --check+packages/shared/src/in-app-agent/server/skills/generated/raw+# Local, untracked screenshot/review archives.screenshots-reviewdiff --git a/knip.jsonc b/knip.jsoncindex 102186999b..37c8ec22d4 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -32,6 +32,13 @@"raw-loader",// The next-auth patch requires this module from core/lib/oauth/client.js."https-proxy-agent",+ // In-app-agent servertests vi.mock these runtime deps of the shared+ // agent module (@langfuse/shared/in-app-agent/server); the mock+ // specifiers must resolve from web.+ "@aws-sdk/client-lambda-microvms",+ "@aws-sdk/credential-providers",+ "dockerode",+ "@types/dockerode",],},"ee": {diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.mdindex 540fbb53a5..21e095d548 100644--- a/packages/shared/AGENTS.md+++ b/packages/shared/AGENTS.md@@ -57,6 +57,14 @@ Use root [AGENTS.md](../../AGENTS.md) for monorepo-level rules.- `@langfuse/shared/encryption` via `src/encryption/index.ts`: encryption andsignature helpers for secrets and signed payloads.- `@langfuse/shared/query` via `src/features/query/index.ts`: dashboard query feature.+- `@langfuse/shared/in-app-agent` via `src/in-app-agent/index.ts`:+ client-safe contracts (AG-UI schemas, constants, id helpers) of the+ EE-licensed in-app-agent module. Never re-export server code here.+- `@langfuse/shared/in-app-agent/server` (plus per-module subpaths via the+ `./in-app-agent/server/*` wildcard) via `src/in-app-agent/server/`:+ the EE-licensed in-app-agent runtime (Mastra/Bedrock/MCP loop, tools,+ persistence, sandbox), consumed by web's foreground adapter and the future+ worker background-execution processor.- Narrower exported subpaths also exist for targeted imports:`@langfuse/shared/src/server/auth/apiKeys`,`@langfuse/shared/src/server/ee/ingestionMasking`, anddiff --git a/packages/shared/package.json b/packages/shared/package.jsonindex b9018604ce..7757542850 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -62,6 +62,22 @@"./monitors/server": {"import": "./dist/src/features/monitors/server.js","require": "./dist/src/features/monitors/server.js"+ },+ "./in-app-agent": {+ "import": "./dist/src/in-app-agent/index.js",+ "require": "./dist/src/in-app-agent/index.js"+ },+ "./in-app-agent/server": {+ "import": "./dist/src/in-app-agent/server/index.js",+ "require": "./dist/src/in-app-agent/server/index.js"+ },+ "./in-app-agent/server/sandbox": {+ "import": "./dist/src/in-app-agent/server/sandbox/index.js",+ "require": "./dist/src/in-app-agent/server/sandbox/index.js"+ },+ "./in-app-agent/server/*": {+ "import": "./dist/src/in-app-agent/server/*.js",+ "require": "./dist/src/in-app-agent/server/*.js"}},"scripts": {@@ -94,6 +110,9 @@"seed": "dotenv -e ../../.env -- tsx scripts/seeder/seed-postgres.ts"},"dependencies": {+ "@ag-ui/client": "^0.0.52",+ "@ag-ui/core": "^0.0.52",+ "@ag-ui/mastra": "1.1.1","@ai-sdk/amazon-bedrock": "^5.0.24","@ai-sdk/anthropic": "^4.0.5","@ai-sdk/azure": "^4.0.5",@@ -103,6 +122,7 @@"@ai-sdk/openai-compatible": "^3.0.3","@aws-sdk/client-cloudwatch": "catalog:","@aws-sdk/client-lambda": "catalog:",+ "@aws-sdk/client-lambda-microvms": "catalog:","@aws-sdk/client-s3": "catalog:","@aws-sdk/client-sesv2": "catalog:","@aws-sdk/credential-providers": "catalog:",@@ -111,10 +131,13 @@"@azure/storage-blob": "^12.26.0","@clickhouse/client": "1.23.1","@google-cloud/storage": "^7.19.0",+ "@mastra/core": "1.46.0",+ "@mastra/mcp": "1.8.1","@opentelemetry/api": ">=1.0.0 <1.10.0","@opentelemetry/otlp-transformer": "^0.220.0","@opentelemetry/resources": "^2.9.0","@opentelemetry/sdk-trace-base": "^2.9.0",+ "@paralleldrive/cuid2": "^2.2.2","@prisma/client": "^6.19.3","@react-email/components": "^0.5.1","@react-email/render": "^1.2.1",@@ -123,6 +146,7 @@"@smithy/node-http-handler": "4.5.1","@types/bcryptjs": "^2.4.6","ai": "^7.0.0",+ "ai-sdk-amazon-bedrock-v4": "npm:@ai-sdk/[email protected]","ajv": "^8.18.0","ajv-formats": "^3.0.1","bcryptjs": "^2.4.3",@@ -135,6 +159,7 @@"ioredis": "^5.10.1","ipaddr.js": "^2.2.0","jsonpath-plus": "10.3.0",+ "langfuse": "3.38.4","langfuse-langchain": "3.38.20","lodash": "^4.18.1","lossless-json": "^4.1.1",@@ -148,16 +173,19 @@"undici": "^7.28.0","uuid": "^14.0.0","winston": "^3.15.0",+ "yaml": "^2.9.0","zod": "^4.3.6"},"devDependencies": {"@opentelemetry/context-async-hooks": "^2.9.0","@repo/eslint-config": "workspace:*","@repo/typescript-config": "workspace:*",+ "@types/dockerode": "^4.0.1","@types/lodash": "^4.17.24","@types/node": "^24.3.0","@types/nodemailer": "^8.0.1","@types/react": "19.2.14",+ "dockerode": "^4.0.9","dotenv-cli": "^7.4.4","eslint": "^9.39.2","prisma": "^6.19.3",diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex 35e58f8b83..e064c70267 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -1,10 +1,9 @@import { randomUUID } from "node:crypto";-import { readFileSync } from "node:fs";-import { resolve } from "node:path";import { parseArgs } from "node:util";import { hash } from "bcryptjs";import { v4 } from "uuid";import { encrypt } from "../../src/encryption";+import { IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE } from "../../src/in-app-agent/server/prompts/in-app-agent-system-prompt";import {EvalTemplateSourceCodeLanguage,EvalTemplateType,@@ -43,26 +42,7 @@ const options = {const prisma = new PrismaClient();const IN_APP_AGENT_SYSTEM_PROMPT_NAME = "in-app-agent-system-prompt";-const IN_APP_AGENT_SYSTEM_PROMPT_PATH = resolve(- __dirname,- "../../../..",- "web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txt",-);--// The path above resolves to `web/src` relative to this file, which only exists-// in a monorepo checkout. In built/published packages (e.g. the worker image-// that runs the seeder in deployed environments) the web source isn't present,-// so fall back to an empty prompt instead of throwing at import time — the-// in-app-agent demo prompt is optional seed content.-let inAppAgentSystemPrompt = "";-try {- inAppAgentSystemPrompt = readFileSync(- IN_APP_AGENT_SYSTEM_PROMPT_PATH,- "utf-8",- );-} catch {- inAppAgentSystemPrompt = "";-}+const inAppAgentSystemPrompt = IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE;async function main() {const environment = parseArgs({diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 31d9040eac..2e72cbb67f 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -490,6 +490,23 @@ const EnvSchema = z.object({LANGFUSE_AWS_BEDROCK_MODEL: z.string().optional(),LANGFUSE_AWS_BEDROCK_SMALL_MODEL: z.string().optional(),LANGFUSE_IN_APP_AGENT_AWS_PROFILE: z.string().optional(),+ // Ambient AWS profile of the host process; the in-app agent prefers it over+ // the configured Bedrock profile so local dev credentials win.+ AWS_PROFILE: z.string().optional(),+ LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER: z+ .enum(["dangerous-docker", "lambda-microvm"])+ .optional(),+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER: z+ .string()+ .optional(),+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN: z+ .string()+ .optional(),+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EGRESS_NETWORK_CONNECTOR_ARN:+ z.string().optional(),+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION: z+ .string()+ .optional(),// API Performance Flags// Whether to add a `FINAL` modifier to the observations CTE in GET /api/public/traces.diff --git a/web/src/features/in-app-agent/constants.ts b/packages/shared/src/in-app-agent/constants.tssimilarity index 100%rename from web/src/features/in-app-agent/constants.tsrename to packages/shared/src/in-app-agent/constants.tsdiff --git a/web/src/features/in-app-agent/ids.ts b/packages/shared/src/in-app-agent/ids.tssimilarity index 100%rename from web/src/features/in-app-agent/ids.tsrename to packages/shared/src/in-app-agent/ids.tsdiff --git a/packages/shared/src/in-app-agent/index.ts b/packages/shared/src/in-app-agent/index.tsnew file mode 100644index 0000000000..fe5a4bc660--- /dev/null+++ b/packages/shared/src/in-app-agent/index.ts@@ -0,0 +1,6 @@+// Client-safe entry of the in-app-agent module. Server code must never be+// re-exported here — this barrel is imported by web client components and is+// covered by the client-bundle scan.+export * from "./schema";+export * from "./constants";+export * from "./ids";diff --git a/web/src/features/in-app-agent/schema.ts b/packages/shared/src/in-app-agent/schema.tssimilarity index 100%rename from web/src/features/in-app-agent/schema.tsrename to packages/shared/src/in-app-agent/schema.tsdiff --git a/web/src/features/in-app-agent/server/agent.ts b/packages/shared/src/in-app-agent/server/agent.tssimilarity index 96%rename from web/src/features/in-app-agent/server/agent.tsrename to packages/shared/src/in-app-agent/server/agent.tsindex f2ffc8998a..9d99ffd776 100644--- a/web/src/features/in-app-agent/server/agent.ts+++ b/packages/shared/src/in-app-agent/server/agent.ts@@ -1,9 +1,7 @@-import { readFile } from "node:fs/promises";-import path from "node:path";-import { EventType } from "@ag-ui/core";import { MastraAgent } from "@ag-ui/mastra";-import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock";+import { IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE } from "./prompts/in-app-agent-system-prompt";+import { createAmazonBedrock } from "ai-sdk-amazon-bedrock-v4";import { fromNodeProviderChain } from "@aws-sdk/credential-providers";import { Agent } from "@mastra/core/agent";import { MCPClient } from "@mastra/mcp";@@ -14,36 +12,33 @@ import {type AgUiRunAgentInput,type InAppAgentToolApprovalRequest,type ResumeForwardedProps,-} from "@/src/features/in-app-agent/schema";-import { createManualToolApprovalRunInput } from "@/src/features/in-app-agent/server/human-in-the-loop";+} from "../schema";+import { createManualToolApprovalRunInput } from "./human-in-the-loop";import type {InAppAgentPromptMetadata,InAppAgentTracingConfig,-} from "@/src/features/in-app-agent/server/instrumentation";-import { createInAppAgentInstrumentation } from "@/src/features/in-app-agent/server/instrumentation";+} from "./instrumentation";+import { createInAppAgentInstrumentation } from "./instrumentation";import {createSandboxTools,createRedirectActionTool,filterInAppAgentAvailableLangfuseMcpTools,type InAppAgentUserAccess,withInAppAgentToolApproval,-} from "@/src/features/in-app-agent/server/tools";-import { LANGFUSE_IN_APP_AGENT_SKILLS } from "@/src/features/in-app-agent/server/skills";-import type { InAppAgentSandbox } from "@/src/features/in-app-agent/server/sandbox";-import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@langfuse/shared";-import { logger } from "@langfuse/shared/src/server";+} from "./tools";+import { LANGFUSE_IN_APP_AGENT_SKILLS } from "./skills";+import type { InAppAgentSandbox } from "./sandbox";+import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "../../features/filters/internalEnvironments";+import { env } from "../../env";+import { logger } from "../../server";import {IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER,IN_APP_AGENT_MCP_USER_AGENT,IN_APP_AGENT_REDIRECT_TOOL_NAME,-} from "@/src/features/in-app-agent/constants";+} from "../constants";const ASSISTANT_TITLE = "Langfuse Assistant";const IN_APP_AGENT_SYSTEM_PROMPT_NAME = "in-app-agent-system-prompt";-const LOCAL_IN_APP_AGENT_SYSTEM_PROMPT_DIR = path.join(- process.cwd(),- "src/features/in-app-agent/prompts/",-);const MAX_AGENT_STEPS = 10;const BEDROCK_CLAUDE_MODEL_ID_PART = "anthropic.claude";const LANGFUSE_DOCS_MCP_URL = "https://langfuse.com/api/mcp";@@ -191,8 +186,7 @@ export async function createAgUiStream(params: {options: CreateAgUiStreamOptions;}) {const encoder = new TextEncoder();- const awsProfile =- process.env.AWS_PROFILE ?? params.options.awsBedrock.profile;+ const awsProfile = env.AWS_PROFILE ?? params.options.awsBedrock.profile;const langfuseMcpAuthHeader = `Basic ${Buffer.from(`${params.options.langfuseMcp.publicKey}:${params.options.langfuseMcp.secretKey}`,@@ -1060,16 +1054,11 @@ async function getSystemPromptInstructions(params: {};}): Promise<{ instructions: string; prompt: InAppAgentPromptMetadata }> {if (params.useLocalPrompt) {- const promptTemplate = await readFile(- path.join(- LOCAL_IN_APP_AGENT_SYSTEM_PROMPT_DIR,- `${IN_APP_AGENT_SYSTEM_PROMPT_NAME}.txt`,- ),- "utf8",- );-return {- instructions: compileLocalPrompt(promptTemplate, params.variables),+ instructions: compileLocalPrompt(+ IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE,+ params.variables,+ ),prompt: {name: IN_APP_AGENT_SYSTEM_PROMPT_NAME,version: 1,diff --git a/web/src/features/in-app-agent/server/eventCompaction.ts b/packages/shared/src/in-app-agent/server/eventCompaction.tssimilarity index 97%rename from web/src/features/in-app-agent/server/eventCompaction.tsrename to packages/shared/src/in-app-agent/server/eventCompaction.tsindex 31905bea34..0358cde048 100644--- a/web/src/features/in-app-agent/server/eventCompaction.ts+++ b/packages/shared/src/in-app-agent/server/eventCompaction.ts@@ -1,6 +1,6 @@import { EventType } from "@ag-ui/core";-import type { AgUiEvent } from "@/src/features/in-app-agent/schema";+import type { AgUiEvent } from "../schema";export function compactTextMessageChunks(events: readonly AgUiEvent[],diff --git a/web/src/features/in-app-agent/server/human-in-the-loop.ts b/packages/shared/src/in-app-agent/server/human-in-the-loop.tssimilarity index 94%rename from web/src/features/in-app-agent/server/human-in-the-loop.tsrename to packages/shared/src/in-app-agent/server/human-in-the-loop.tsindex 074a84de90..8ad885c2f6 100644--- a/web/src/features/in-app-agent/server/human-in-the-loop.ts+++ b/packages/shared/src/in-app-agent/server/human-in-the-loop.ts@@ -1,22 +1,21 @@import { EventType } from "@ag-ui/core";import { z } from "zod";+import { InvalidRequestError } from "../../index";+import { prisma } from "../../db";+import { IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE } from "../constants";import {- InvalidRequestError,- safeJsonParse,- stableJsonStringify,-} from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";-import type { McpToolName } from "@/src/features/mcp/server/bootstrap";-import { IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE } from "@/src/features/in-app-agent/constants";-import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES } from "@/src/features/in-app-agent/server/tools";+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES,+ type InAppAgentLangfuseMcpToolName,+} from "./tools";+import { safeJsonParse, stableJsonStringify } from "../../utils/json";import {type AgUiEvent,type AgUiMessage,type AgUiRunAgentInput,type InAppAgentToolApprovalRequest,type ResumeForwardedProps,-} from "@/src/features/in-app-agent/schema";+} from "../schema";const MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE ="Tool call was not approved by the user.";@@ -34,15 +33,18 @@ const PendingToolApprovalSchema = z.object({argsFingerprint: z.string(),});-const McpToolNameSchema = z.custom<McpToolName>(- (value) =>- typeof value === "string" &&- IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(value as McpToolName),- { message: "Invalid MCP tool name" },-);+const InAppAgentLangfuseMcpToolNameSchema =+ z.custom<InAppAgentLangfuseMcpToolName>(+ (value) =>+ typeof value === "string" &&+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(+ value as InAppAgentLangfuseMcpToolName,+ ),+ { message: "Invalid MCP tool name" },+ );export const InAppAgentMcpRunOverrideSchema = z.object({- toolName: McpToolNameSchema,+ toolName: InAppAgentLangfuseMcpToolNameSchema,});const MastraSuspendEventSchema = z.object({@@ -137,7 +139,7 @@ export async function consumeAndValidatePendingToolApproval(params: {}export async function createInAppAgentMcpRunOverride(params: {- toolName: McpToolName;+ toolName: InAppAgentLangfuseMcpToolName;}) {return JSON.stringify({toolName: params.toolName,diff --git a/packages/shared/src/in-app-agent/server/index.ts b/packages/shared/src/in-app-agent/server/index.tsnew file mode 100644index 0000000000..de566f0af0--- /dev/null+++ b/packages/shared/src/in-app-agent/server/index.ts@@ -0,0 +1,12 @@+// Server entry of the in-app-agent runtime, consumed by web's foreground+// adapter (handler/router) and, once background execution ships, the worker+// queue processor.+export * from "./agent";+export * from "./tools";+export * from "./human-in-the-loop";+export * from "./instrumentation";+export * from "./eventCompaction";+export * from "./persistence";+export * from "./skills";+export * from "./sandbox";+export * from "./prompts/in-app-agent-system-prompt";diff --git a/web/src/features/in-app-agent/server/instrumentation.ts b/packages/shared/src/in-app-agent/server/instrumentation.tssimilarity index 98%rename from web/src/features/in-app-agent/server/instrumentation.tsrename to packages/shared/src/in-app-agent/server/instrumentation.tsindex 9f29dc56c9..f047bd6576 100644--- a/web/src/features/in-app-agent/server/instrumentation.ts+++ b/packages/shared/src/in-app-agent/server/instrumentation.ts@@ -1,18 +1,14 @@import { EventType } from "@ag-ui/core";-import { getInternalTracingHandler, logger } from "@langfuse/shared/src/server";+import { getInternalTracingHandler, logger } from "../../server";import {getInAppAgentInstrumentationObservationId,getInAppAgentInstrumentationTraceId,-} from "@/src/features/in-app-agent/constants";-import type {- AgUiEvent,- AgUiMessage,- AgUiRunAgentInput,-} from "@/src/features/in-app-agent/schema";-import { compactTextMessageChunks } from "@/src/features/in-app-agent/server/eventCompaction";-import type { InAppAgentUserAccess } from "@/src/features/in-app-agent/server/tools";-import { assertUnreachable } from "@/src/utils/types";+} from "../constants";+import type { AgUiEvent, AgUiMessage, AgUiRunAgentInput } from "../schema";+import { compactTextMessageChunks } from "./eventCompaction";+import type { InAppAgentUserAccess } from "./tools";+import { assertUnreachable } from "../../utils/typeChecks";export type InAppAgentTracingConfig = {environment: string;diff --git a/web/src/features/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.tssimilarity index 98%rename from web/src/features/in-app-agent/server/persistence.tsrename to packages/shared/src/in-app-agent/server/persistence.tsindex dd1df5f392..f6e620f99d 100644--- a/web/src/features/in-app-agent/server/persistence.ts+++ b/packages/shared/src/in-app-agent/server/persistence.ts@@ -6,35 +6,34 @@ import {InAppAgentRunStatus,LangfuseConflictError,LangfuseNotFoundError,- safeJsonParse,-} from "@langfuse/shared";+} from "../../index";import {ChatMessageRole,ChatMessageType,LangfuseInternalTraceEnvironment,logger,+} from "../../server";+import { Prisma } from "../../db";+import type { InAppAgentConversation, PrismaClient } from "../../db";++import { env } from "../../env";+import {generateLangfuseAIText,getLangfuseAITraceSinkParams,-} from "@langfuse/shared/src/server";-import { Prisma } from "@langfuse/shared/src/db";-import type {- InAppAgentConversation,- PrismaClient,-} from "@langfuse/shared/src/db";--import { env } from "@/src/env.mjs";-import { getProductBaseUrl } from "@/src/utils/base-url";-import { truncate } from "@/src/utils/string";-import { assertUnreachable } from "@/src/utils/types";+} from "../../server/llm/langfuseAiCompletion";+import { getProductBaseUrl } from "../../server/utils/baseUrl";+import { truncate } from "../../utils/stringChecks";+import { assertUnreachable } from "../../utils/typeChecks";import {AgUiMessageSchema,InAppAgentRedirectActionToolResultSchema,type AgUiEvent,type AgUiMessage,-} from "@/src/features/in-app-agent/schema";-import { compactPersistedEventDeltas } from "@/src/features/in-app-agent/server/eventCompaction";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/features/in-app-agent/constants";-import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "@/src/features/in-app-agent/server/tools";+} from "../schema";+import { compactPersistedEventDeltas } from "./eventCompaction";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "../constants";+import { safeJsonParse } from "../../utils/json";+import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "./tools";// Keep this close to the route maxDuration (120s) so a killed foreground stream// does not block the conversation long after the route can no longer respond.@@ -106,7 +105,7 @@ export async function getOwnedConversationOrThrow(params: {projectId: string;conversationId: string;userId: string;-}) {+}): Promise<InAppAgentConversation> {const conversation = await params.prisma.inAppAgentConversation.findFirst({where: {id: params.conversationId,@@ -128,7 +127,7 @@ export async function ensureOwnedConversation(params: {projectId: string;conversationId: string;userId: string;-}) {+}): Promise<InAppAgentConversation> {const existing = await params.prisma.inAppAgentConversation.findUnique({where: {id_projectId: {diff --git a/web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txt b/packages/shared/src/in-app-agent/server/prompts/in-app-agent-system-prompt.tssimilarity index 94%rename from web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txtrename to packages/shared/src/in-app-agent/server/prompts/in-app-agent-system-prompt.tsindex 8d15574aa5..f7a1d5d584 100644--- a/web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txt+++ b/packages/shared/src/in-app-agent/server/prompts/in-app-agent-system-prompt.ts@@ -1,4 +1,8 @@-<identity>+// The in-app agent system prompt used when running with a local prompt+// (dev) and by the seeder to register the prompt in Langfuse prompt+// management. Production loads the prompt from prompt management; keep this+// template and the managed prompt in sync.+export const IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE = `<identity>You are an assistant called Langfuse Assistant.Your role is to assist users with tasks in the Langfuse Cloud product.</identity>@@ -68,3 +72,4 @@ The current date is {{currentDate}}.{{userContext}}{{sandboxFilesystem}}+`;diff --git a/web/src/features/in-app-agent/server/sandbox/config.ts b/packages/shared/src/in-app-agent/server/sandbox/config.tssimilarity index 89%rename from web/src/features/in-app-agent/server/sandbox/config.tsrename to packages/shared/src/in-app-agent/server/sandbox/config.tsindex fb3669ff7c..bfc7eba47d 100644--- a/web/src/features/in-app-agent/server/sandbox/config.ts+++ b/packages/shared/src/in-app-agent/server/sandbox/config.ts@@ -1,8 +1,8 @@import { createLambdaMicrovmSandboxProvider } from "./providers/lambdaMicrovm";import type { InAppAgentSandboxProviderType, SandboxProvider } from "./types";-import { env } from "@/src/env.mjs";-import { IN_APP_AGENT_LOCAL_SANDBOX_IMAGE } from "@/src/features/in-app-agent/constants";-import { assertUnreachable } from "@/src/utils/types";+import { env } from "../../../env";+import { IN_APP_AGENT_LOCAL_SANDBOX_IMAGE } from "../../constants";+import { assertUnreachable } from "../../../utils/typeChecks";export function getDefaultInAppAgentSandboxProviderType(): InAppAgentSandboxProviderType | null {const providerType = env.LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER ?? null;@@ -31,7 +31,8 @@ export async function createInAppAgentSandboxProvider(}// Keep the Docker provider behind a runtime import since it's only used in development- const { createDockerSandboxProvider } = await import("./providers/docker");+ const { createDockerSandboxProvider } =+ await import("./providers/docker.js");return createDockerSandboxProvider({image: IN_APP_AGENT_LOCAL_SANDBOX_IMAGE,});diff --git a/web/src/features/in-app-agent/server/sandbox/index.ts b/packages/shared/src/in-app-agent/server/sandbox/index.tssimilarity index 100%rename from web/src/features/in-app-agent/server/sandbox/index.tsrename to packages/shared/src/in-app-agent/server/sandbox/index.tsdiff --git a/web/src/features/in-app-agent/server/sandbox/providers/docker.ts b/packages/shared/src/in-app-agent/server/sandbox/providers/docker.tssimilarity index 99%rename from web/src/features/in-app-agent/server/sandbox/providers/docker.tsrename to packages/shared/src/in-app-agent/server/sandbox/providers/docker.tsindex 0d7b6c0232..57709134df 100644--- a/web/src/features/in-app-agent/server/sandbox/providers/docker.ts+++ b/packages/shared/src/in-app-agent/server/sandbox/providers/docker.ts@@ -1,7 +1,7 @@import { PassThrough } from "node:stream";import type Docker from "dockerode";-import { logger } from "@langfuse/shared/src/server";+import { logger } from "../../../../server";import type { SandboxFile, SandboxProvider, SandboxSession } from "../types";diff --git a/web/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts b/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.tssimilarity index 99%rename from web/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.tsrename to packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.tsindex 6d359f40e9..8c7dd9d4eb 100644--- a/web/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts+++ b/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts@@ -10,7 +10,7 @@ import {TerminateMicrovmCommand,type RunMicrovmCommandInput,} from "@aws-sdk/client-lambda-microvms";-import { logger } from "@langfuse/shared/src/server";+import { logger } from "../../../../server";import { z } from "zod";import type { SandboxFile, SandboxProvider, SandboxSession } from "../types";diff --git a/web/src/features/in-app-agent/server/sandbox/service.ts b/packages/shared/src/in-app-agent/server/sandbox/service.tssimilarity index 100%rename from web/src/features/in-app-agent/server/sandbox/service.tsrename to packages/shared/src/in-app-agent/server/sandbox/service.tsdiff --git a/web/src/features/in-app-agent/server/sandbox/types.ts b/packages/shared/src/in-app-agent/server/sandbox/types.tssimilarity index 100%rename from web/src/features/in-app-agent/server/sandbox/types.tsrename to packages/shared/src/in-app-agent/server/sandbox/types.tsdiff --git a/web/src/features/in-app-agent/server/skills.ts b/packages/shared/src/in-app-agent/server/skills.tssimilarity index 100%rename from web/src/features/in-app-agent/server/skills.tsrename to packages/shared/src/in-app-agent/server/skills.tsdiff --git a/web/src/features/in-app-agent/server/skills/generated/raw/README.md b/packages/shared/src/in-app-agent/server/skills/generated/raw/README.mdsimilarity index 100%rename from web/src/features/in-app-agent/server/skills/generated/raw/README.mdrename to packages/shared/src/in-app-agent/server/skills/generated/raw/README.mddiff --git a/web/src/features/in-app-agent/server/skills/generated/raw/cli.md b/packages/shared/src/in-app-agent/server/skills/generated/raw/cli.mdsimilarity index 100%rename from web/src/features/in-app-agent/server/skills/generated/raw/cli.mdrename to packages/shared/src/in-app-agent/server/skills/generated/raw/cli.mddiff --git a/web/src/features/in-app-agent/server/skills/generated/raw/error-analysis.md b/packages/shared/src/in-app-agent/server/skills/generated/raw/error-analysis.mdsimilarity index 100%rename from web/src/features/in-app-agent/server/skills/generated/raw/error-analysis.mdrename to packages/shared/src/in-app-agent/server/skills/generated/raw/error-analysis.mddiff --git a/web/src/features/in-app-agent/server/skills/generated/raw/prompt-engineering.md b/packages/shared/src/in-app-agent/server/skills/generated/raw/prompt-engineering.mdsimilarity index 100%rename from web/src/features/in-app-agent/server/skills/generated/raw/prompt-engineering.mdrename to packages/shared/src/in-app-agent/server/skills/generated/raw/prompt-engineering.mddiff --git a/web/src/features/in-app-agent/server/skills/generated/raw/v4-project-migration.md b/packages/shared/src/in-app-agent/server/skills/generated/raw/v4-project-migration.mdsimilarity index 100%rename from web/src/features/in-app-agent/server/skills/generated/raw/v4-project-migration.mdrename to packages/shared/src/in-app-agent/server/skills/generated/raw/v4-project-migration.mddiff --git a/packages/shared/src/in-app-agent/server/skills/generated/skill-markdown.ts b/packages/shared/src/in-app-agent/server/skills/generated/skill-markdown.tsnew file mode 100644index 0000000000..f043a46d95--- /dev/null+++ b/packages/shared/src/in-app-agent/server/skills/generated/skill-markdown.ts@@ -0,0 +1,25 @@+// This file is generated by scripts/in-app-agent/sync-raw-skills.mjs.+// Do not edit it manually.++export const LANGFUSE_IN_APP_AGENT_SKILL_MARKDOWN = [+ {+ fileName: "cli.md",+ markdown:+ "---\nname: langfuse-cli\ndescription: Langfuse CLI usage reference — install, resource/action discovery, credentials, and common usage tips for `langfuse-cli`. Use for further tips on using the Langfuse CLI.\nmetadata:\n required_access:\n - LANGFUSE_PROJECT_INTERFACE\n---\n\n# Langfuse CLI Reference\n\nDocumentation: https://langfuse.com/docs/api-and-data-platform/features/cli\n\n## Install\n\n```bash\n# Run directly (recommended)\nnpx langfuse-cli api <resource> <action>\nbunx langfuse-cli api <resource> <action>\n\n# Or install globally\nnpm i -g langfuse-cli\nlangfuse api <resource> <action>\n```\n\n## Discovery\n\n```bash\n# List all resources and auth info\nlangfuse api __schema\n\n# List actions for a resource\nlangfuse api <resource> --help\n\n# Show args/options for a specific action\nlangfuse api <resource> <action> --help\n\n# Preview the curl command without executing\nlangfuse api <resource> <action> --curl\n```\n\n## Credentials\n\nSet environment variables:\n\n```bash\nexport LANGFUSE_PUBLIC_KEY=pk-lf-...\nexport LANGFUSE_SECRET_KEY=sk-lf-...\nexport LANGFUSE_BASE_URL=https://cloud.langfuse.com \n```\n\n## Tips\n\n- Use `--json` for machine-readable JSON output\n- Use `--curl` to preview the HTTP request without executing\n- All list commands support filtering — check `<resource> <action> --help` for available options\n- Prefer `observations` over `legacy-observations-v1s` — `observations` is the modern high-performance endpoint (cursor pagination, selective field groups); `legacy-observations-v1s` is the deprecated v1\n- Prefer `metrics` over `legacy-metrics-v1s` for the same reason\n- Prefer `scores` over `legacy-score-v1s` for list/get operations\n- For broad trace queries, `traces list` can time out on Langfuse Cloud — use `observations list` (with `--trace-id` if you're traversing from a known trace) instead. See the [Observations API docs](https://langfuse.com/docs/api-and-data-platform/features/observations-api) for the v1 → v2 mapping.\n- Pagination: legacy v1 endpoints use `--limit` and `--page`; modern endpoints (`observations`, `metrics`, `scores`) use cursor-based pagination — pass `--limit`, then thread `meta.cursor` from the response into the next request's `--cursor`\n",+ },+ {+ fileName: "error-analysis.md",+ markdown:+ '---\nname: langfuse-error-analysis\ndescription: Deep-dive error analysis of an LLM pipeline or AI application using Langfuse traces.\n Use this skill whenever the user wants to understand why their AI system is producing\n bad outputs, where their pipeline is failing, how to categorise or label failures,\n what to prioritise fixing, or how to set up evaluators. Also trigger for "review my\n traces", "my outputs look wrong", "help me debug my LLM app", "I want to analyse\n errors", "build a failure taxonomy", "what\'s going wrong with my pipeline", or any\n request to systematically inspect, annotate, or score Langfuse traces. If the user\n is trying to understand or improve the quality of an AI system\'s outputs, use this skill.\nmetadata:\n required_access:\n - LANGFUSE_PROJECT_INTERFACE\n---\n\n# Error Analysis\n\n## Primary Guide\n\n**1. Fetch the guide in this blogpost**\n\nhttps://langfuse.com/guides/cookbook/error-analysis-llm-applications.md\n\nIf fetch is not available query for langfuse.com error analysis guide\n\nRead it in full. It defines the authoritative 5-step process (sample selection → open coding → clustering → labelling → deciding what to fix).\n\n**2. Guide the user through this step by step**\n\nYou as a coding agent and the user go through this together to perform a full error analysis with their data in langfuse. Do as much of the work as you can directly for the user (look up traces, create annotation queues, ...). Provide them with direct links to UI wherever their action is required. Be proactive and narrate what is going on for the user. \n\n## Rules CRITICAL\nPerform interactions with the user\'s Langfuse instance yourself rather than telling the user to do them — don\'t say "now do this in Langfuse" when you can do it directly\nBut don\'t barrel through on assumptions: where a step needs the user\'s judgment or input (e.g. what to fix, how to label, which evaluator), pause and ask before acting\nUse charts where possible to display data\n\n---\n\n## Langfuse Implementation Notes\n\nThe guide describes the process. These notes cover the Langfuse-specific mechanics required to execute it.\n\n### Credentials\n\nMake sure Langfuse credentials are available before starting — a public key (`pk-lf-...`), a secret key (`sk-lf-...`), and the host (e.g. `https://cloud.langfuse.com` for EU, `https://us.cloud.langfuse.com` for US, `https://jp.cloud.langfuse.com` for JP, or a self-hosted URL). If they aren\'t configured, ask the user to set them — do not ask them to paste secret values into chat.\n\nVerify you can actually reach the user\'s project before proceeding. If access fails, stop and ask the user to check their credentials and host.\n\n### Annotation target: OBSERVATION versus TRACE\n\n> **CRITICAL:** In OpenTelemetry-instrumented apps, trace-level `input`/`output` can be null — content often lives in a GENERATION observation. In that case, add the GENERATION observation (not the trace) to the annotation queue, so the content being reviewed is actually visible.\n\n### Annotation queues\n\n> **CRITICAL:** Queues cannot be updated or deleted after creation. Create score configs first, then the queue with all config IDs. To add new configs later, create a new queue.\n\n\n**Always give the user a direct link immediately after creating a queue:**\n\n| Host | URL pattern |\n|------|-------------|\n| EU cloud | `https://cloud.langfuse.com/project/<projectId>/annotation-queues/<queueId>` |\n| US cloud | `https://us.cloud.langfuse.com/project/<projectId>/annotation-queues/<queueId>` |\n| Self-hosted | `<LANGFUSE_BASE_URL>/project/<projectId>/annotation-queues/<queueId>` |\n\nInstruction to give: *"Please open code the first ~50 examples. For each trace, write what you observe in the `open_coding` field (describe behaviour, don\'t diagnose root causes), then set `pass_fail_assessment` to Pass or Fail."*\n\n\n### Prompt fixes\n\nWhen a category warrants a prompt fix, always offer the user two options:\n1. Create it as a versioned prompt in Langfuse (tracked, usable via the prompt API)\n2. Draft the specific text change for them to review and apply\n\n### Setup evaluators\n\nWhen a category warrants an evaluator setup, propose the type of evaluator and offer to set it up for the user\n\n\n### Common gotchas\n\n| Mistake | Fix |\n|---------|-----|\n| Annotating the trace instead of the observation | Target the GENERATION observation, not the trace, when content lives there |\n| Creating a score config without checking existing ones | Check existing score configs first; they can\'t be deleted |\n| Queue created before score configs | Create configs → collect IDs → create queue |\n| Requesting too many traces at once | Page size is capped (max 100); paginate to get more |\n| No rate limiting on bulk queue item creation | Space out requests to avoid hitting rate limits (429) |\n',+ },+ {+ fileName: "prompt-engineering.md",+ markdown:+ '---\nname: langfuse-prompt-engineering\ndescription: Write or change prompts in Langfuse or code. Use whenever the user asks to create, edit, rewrite, debug, tune, or otherwise modify a prompt, including a small wording or instruction change. Distinct from prompt-migration and judge-calibration.\nmetadata:\n required_access: []\n---\n\n# Prompt Engineering\n\n## Universal principles\n\n1. **Be specific.** State the required output format, constraints, and, when order matters, numbered steps. Write for someone with minimal context.\n2. **Use labeled sections** for the role, instructions, examples, and context. Use XML tags when they help distinguish rules, data, and variables.\n3. **Give the model a role.** A focused system-prompt sentence can steer tone and behavior.\n4. **Explain why important rules exist** so the model can apply them to adjacent cases.\n\n## Adjusting an existing prompt\n\n1. **Pin down the failure first.** Use concrete misbehaving outputs and name the exact failure mode: wrong format, ignored instruction, wrong tone, hallucination, or another observable error. The task and data show what could fail, not what did fail; do not write a fix before observing the failure.\n2. **Trace the failure to the prompt.** Look for a missing, ambiguous, or conflicting instruction.\n3. **Fix the failure class, not the example.** Generalize the observed mistake into an error class and write the instruction at that level, in your own words. Cover adjacent cases, but do not add definitions, rules, or examples for unobserved problems or encode the failing example itself. If a generalized instruction does not work, report the failure instead of narrowing the rule to that case.\n4. **Preserve existing behavior.** Before changing text, identify what behavior it protects. Avoid contradicting other rules or breaking cases that already work.\n5. **Make the smallest testable edit.** Change one cause per attempt so you can attribute the result. Avoid extra length, emphasis, or all-caps. In Langfuse, save each attempt as a new version or label so you can compare and roll back.\n\n## Model-specific tuning\n\nIdentify the target model if you can — tuning differs by model, so when you know which model the prompt runs on, follow that model\'s own prompting guidance.\n\n| Technique | Standard (GPT) | Reasoning (Claude latest) |\n|-----------|----------------|---------------------------|\n| Instruction density | High, prescriptive | Goal-level; don\'t micro-manage steps |\n| Reasoning | Add explicit chain-of-thought | Native thinking; "think thoroughly" + tune `effort` |\n| Emphasis language | Strong directives fine | Dial back `MUST`/`CRITICAL` |\n| Output format | Prefilling/scaffolds | Prefill removed (4.6+); structured outputs + "no preamble" |\n| Roles | `developer` > `user` > `assistant` | `system` role + `user`/`assistant` |\n',+ },+ {+ fileName: "v4-project-migration.md",+ markdown:+ "---\nname: langfuse-v4-project-migration\ndescription: Prepare a Langfuse project for the v4 platform by migrating deprecated API calls to their replacement endpoints, inventorying active evaluation rules, migrating legacy trace and dataset evaluators to observation and experiment targets, and moving exports to the enriched observation schema.\nmetadata:\n required_access:\n - LANGFUSE_PROJECT_INTERFACE\n---\n\n# Langfuse v4 project migration\n\nUse this as the canonical v4 platform migration workflow. A coding agent should execute the SDK and code changes using the SDK and trace-level evaluator upgrade workflows; the Langfuse in-app agent can execute the project steps and produce the same code handoff.\n\n## Sources of truth\n\nFetch the applicable pages before taking action:\n\n- [Langfuse v4 overview](https://langfuse.com/docs/v4)\n- [Langfuse CLI](https://langfuse.com/docs/api-and-data-platform/features/cli)\n- [SDK upgrade paths](https://langfuse.com/docs/observability/sdk/upgrade-path)\n- [Deprecated API migration](https://langfuse.com/docs/deprecated-api-migration)\n- [Deprecated APIs reference](https://langfuse.com/docs/api-and-data-platform/features/deprecated-apis)\n- [Evaluator migration guide](https://langfuse.com/faq/all/llm-as-a-judge-migration)\n- [Observation evaluator context](https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge#observation-evaluator-context)\n- [Evaluators API](https://api.reference.langfuse.com/#tag/unstableevaluators)\n- [Evaluation Rules API](https://api.reference.langfuse.com/#tag/unstableevaluationrules)\n- [Blob storage export migration](https://langfuse.com/docs/api-and-data-platform/features/export-to-blob-storage#export-source-fast-preview)\n- [Export field reference](https://langfuse.com/docs/api-and-data-platform/features/blob-storage-export-fields#enriched-vs-legacy-differences)\n- [Mixpanel export migration](https://langfuse.com/integrations/analytics/mixpanel#migrate-export-source)\n- [PostHog export migration](https://langfuse.com/integrations/analytics/posthog#migrate-export-source)\n\nDiscover the current API or tool schema before writes; the evaluator endpoints are unstable.\n\n## 1. Set up project access\n\n- Prefer an available Langfuse project interface. Otherwise recommend the [Langfuse CLI](https://langfuse.com/docs/api-and-data-platform/features/cli) and run it directly with `npx langfuse-cli` or `bunx langfuse-cli`; a global installation is optional.\n- Ask the user to configure `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, and `LANGFUSE_BASE_URL` in their environment. Never ask them to paste secrets into the conversation or commit credentials.\n- Verify access and discover the current resources with `npx langfuse-cli api __schema`. Inspect each resource and action with `--help` before use, and request machine-readable output with `--json`.\n- Confirm the project and host before any read or write. If credentials or a project interface are unavailable, continue with the code migration and report project-side checks as blocked.\n\n## 2. Upgrade SDKs and instrumentation\n\n- For a coding agent with repository access, execute the repository-wide SDK upgrade in the steps below — using the version-specific breaking-changes guide under [SDK upgrade paths](https://langfuse.com/docs/observability/sdk/upgrade-path) as the docs reference — before declaring the platform migration ready.\n- Inventory every Langfuse SDK, integration package, direct OpenTelemetry exporter, initialization site, and lockfile across the repository. Upgrade each ingestion path to the latest stable release in the major required by the current v4 migration docs, unless the repository has a documented compatibility constraint.\n- Apply every applicable SDK migration step and update removed tracing APIs using the current docs. A dependency-only update is incomplete. Deprecated API routes reached outside the SDK client are migrated in the next step.\n- Use the evaluator migration contract below to consolidate all required evaluation input, output, metadata, tool calls, and propagated filter attributes onto the single target observation.\n- Verify the resolved versions and representative ingestion behavior. If the agent cannot access or edit the codebase, return an exact SDK and instrumentation handoff and keep this area blocked rather than marking it ready.\n\n## 3. Migrate direct API calls\n\n- Fetch the [deprecated API migration guide](https://langfuse.com/docs/deprecated-api-migration) before rewriting any call. It maps every deprecated endpoint to its replacement with parameter mappings, semantic differences, and before/after examples, and is also served as plain markdown at `https://langfuse.com/docs/deprecated-api-migration.md` with stable section anchors for programmatic use.\n- This step covers API usage outside the SDK client methods migrated in the previous step: raw HTTP calls in application code, `curl` in scripts and CI, generated API clients, SDK API namespaces such as `langfuse.api.*` and `langfuse.api.legacy.*`, notebooks, dashboards, and data pipelines. Inventory them by searching for `/api/public` paths and the deprecated endpoint names, not only for client libraries.\n- Map each inventoried call to its replacement using the guide's quick reference and per-endpoint sections; do not rewrite calls from memory. Check the guide before touching a call — some routes on the same resources are not deprecated and must stay unchanged.\n- Migrate parameters, pagination, filters, field groups, and response parsing together with the path, following the guide's parameter mappings and semantic differences per endpoint. The replacements are not drop-in; a path-only rewrite is incomplete.\n- Where the guide changes the response shape rather than only the route, rework the downstream consumer to the new model instead of reshaping the response back into the deprecated structure.\n- Confirm the deployment the code targets serves each replacement endpoint before cutover, using the [compatibility matrix](https://langfuse.com/docs/compatibility). Code calling a self-hosted v3 deployment must keep the deprecated routes; report its cutover as blocked on the server upgrade.\n- Verify each rewritten call against real project data, comparing with the deprecated response where it is still available. Return calls that cannot be migrated or verified as part of the deprecated API code handoff instead of marking this area ready.\n\n## 4. Inventory active evaluation rules\n\n- Confirm the project, host, and whether it is Cloud or self-hosted.\n- Page through all available evaluators and evaluation rules. Inspect each referenced evaluator definition, not only its name.\n- Migrate rules whose effective `status` is `active`. Report paused/inactive rules separately; do not reactivate or migrate them unless requested.\n- Use unstable evaluation-rule `list` and `get` as the source of truth for legacy trace rules. If a bulk page fails, retry with `limit=1` and report unreadable entries as blockers.\n- Open the [Evaluators UI](https://cloud.langfuse.com/project/~/evals) and check for active rows marked **Legacy** whenever the interface cannot list those targets. In the in-app agent, redirect the user there. Treat this confirmation as required before declaring the project ready.\n\n## 5. Build an evaluator migration contract\n\nFor every active legacy rule, record:\n\n| Field | Required decision |\n| ------------- | -------------------------------------------------------------------------------------------- |\n| Existing rule | Name, evaluator, active status, filters, sampling, and variable mappings |\n| New target | Trace to one observation; dataset/dataset run to experiment |\n| Selector | Stable observation name/type plus any propagated trace-attribute filters |\n| Mapping | Every evaluator variable mapped exactly once to a supported source and optional JSONPath |\n| Required data | Exact input, output, metadata, or tool-call fields that must exist on the target observation |\n| Code handoff | Missing observation fields or attributes that the coding agent must add |\n| Cutover | How the new rule will be verified before the legacy rule is disabled |\n\n- Inspect representative observations instead of guessing the target or data shape.\n- Use observation sources for live rules. Experiment rules may additionally use expected output and experiment-item metadata; confirm the current schema before writing.\n- Observation evaluators see only the matched observation. If the evaluator needs an end-to-end request, response, or summary assembled from multiple steps, target a root observation and require the application to write that context onto it.\n- Rebuild filters and mappings deliberately. Do not assume the UI upgrade wizard semantically preserves a legacy rule.\n- When a trace-level evaluator requires code changes, make the handoff self-contained: include the full legacy filters and mappings, representative observation names/types and payload shapes, the preferred target observation, and each missing field or propagated attribute. The coding agent follows `references/trace-evaluator-upgrade.md`; do not ask it to rediscover project configuration from code.\n\n## 6. Create and cut over successor rules\n\n- Reuse the existing evaluator definition when it remains valid. Create a new evaluator version only when the prompt, output definition, or variable contract must change.\n- Update an existing successor rule instead of creating a duplicate with the same name.\n- Create the observation or experiment successor disabled first when the interface supports it. Validate its target, filters, mappings, sampling, and evaluator-variable coverage against real project data.\n- Enable the successor only after the user approves the write. Verify it on newly ingested data; public evaluation rules are live-ingestion rules and do not perform historical backfills.\n- Compare resulting scores and execution logs. Keep the legacy rule available for rollback until the successor is proven.\n- Disable the active legacy rule in the UI after verification. Do not delete legacy rules or historical scores by default.\n- Re-list rules and re-check the UI. Completion requires no unintended active legacy trace/dataset rule and an active verified successor for every migrated rule.\n\nIf the available project interface cannot read or update a legacy rule, provide the exact [Evaluators UI](https://cloud.langfuse.com/project/~/evals) action and retain it as an explicit blocker rather than claiming completion.\n\n## 7. Migrate exports\n\nSwitching an integration to enriched-only output is a breaking change for downstream consumers; enabling the dual source (legacy plus enriched observations) is additive and safe. Fetch the documented upgrade paths and follow them instead of restating export mechanics from memory:\n\n- [Blob Storage upgrade path](https://langfuse.com/docs/api-and-data-platform/features/export-to-blob-storage#upgrade-path) and the [enriched vs. legacy field differences](https://langfuse.com/docs/api-and-data-platform/features/blob-storage-export-fields#enriched-vs-legacy-differences)\n- [Mixpanel export migration](https://langfuse.com/integrations/analytics/mixpanel#migrate-export-source) and the [legacy vs. enriched event changes](https://langfuse.com/integrations/analytics/mixpanel#legacy-vs-enriched)\n- [PostHog export migration](https://langfuse.com/integrations/analytics/posthog#migrate-export-source) and the [legacy vs. enriched event changes](https://langfuse.com/integrations/analytics/posthog#legacy-vs-enriched)\n\nKey takeaways:\n\n- Inventory configured Blob Storage, Mixpanel, PostHog, and other export integrations in **Project Settings > Integrations**.\n- Check eligibility first: many integrations can no longer select legacy sources (Langfuse Cloud date cutoffs; self-hosted deployments that completed the v4 migration — see the docs for the exact rules). An integration that already exports enriched observations only is complete by default.\n- Follow the documented dual-export transition per integration. Switching from legacy to legacy plus enriched observations is additive and needs no downstream sign-off — apply it directly. The switch from the dual source to enriched observations only stops the legacy output and requires the user's explicit confirmation that downstream owners are prepared. Never switch a legacy integration directly to enriched-only.\n- A source change applies to future exports only; already-exported history keeps the legacy shape and is not re-exported.\n- Change only the export source. Leave credentials, schedules, prefixes, file formats, field groups, and integration secrets untouched. Apply the change in the integration settings UI — for Blob Storage the documented public API (project-scoped keys) also works; Mixpanel and PostHog have no API migration path.\n\nEffects outside Langfuse — spell these out per configured integration before the enriched-only cutover:\n\n- **Blob Storage:** the exported tables, file paths, and column sets change (scores are unaffected). Warehouse loaders, table schemas, trace-observation joins, dashboards, and any storage-event automation keyed on the legacy file paths must be updated — the integration setting is the smallest part of the migration. After the switch the legacy directories receive no further files, so pipelines still watching them go silent without an error signal.\n- **Mixpanel and PostHog:** the source determines which events and properties are sent, so dashboards, transformations, funnels, and alerts built on the legacy events in those systems must be revalidated.\n- **Dual mode** exports the same data in both the legacy and the enriched shape by design. Downstream counts, costs, and metrics are inflated only where a consumer ingests both — for example a warehouse model loading both observation tables, or analytics queries matching both event sets. Keep each consumer on exactly one shape during the transition.\n- Because history is not re-exported, downstream consumers must either keep handling the legacy schema for historical data or the user must re-export history as documented.\n- Treat the downstream consumer update as part of the migration. Report this area as `manual action`, not `ready`, until the user confirms consumers handle the new schema.\n\n## 8. Report readiness\n\nReturn one row per area with `ready`, `changed`, `manual action`, or `blocked`:\n\n- CLI or project-interface setup\n- SDK versions and instrumentation migration, including any code handoff\n- active trace-to-observation evaluator migrations\n- active dataset-to-experiment evaluator migrations\n- direct API call migration, including any deprecated API code handoff\n- Blob Storage and analytics export migrations\n- verification and rollback status\n\nInclude direct UI links and the evaluator migration contract so an off-platform coding agent and the in-app agent can continue from the same facts.\n",+ },+] as const;diff --git a/web/src/features/in-app-agent/server/tools.ts b/packages/shared/src/in-app-agent/server/tools.tssimilarity index 92%rename from web/src/features/in-app-agent/server/tools.tsrename to packages/shared/src/in-app-agent/server/tools.tsindex 92e09a7caa..29f9f2aea3 100644--- a/web/src/features/in-app-agent/server/tools.ts+++ b/packages/shared/src/in-app-agent/server/tools.ts@@ -1,12 +1,10 @@import { createTool } from "@mastra/core/tools";-import type { InAppAgentSandbox } from "@/src/features/in-app-agent/server/sandbox";+import type { InAppAgentSandbox } from "./sandbox";import {+ hasProjectAccessByRole,type ProjectScope,- ObservationLevelDomain,- TracingSearchType,-} from "@langfuse/shared";-import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { assertUnreachable } from "@/src/utils/types";+} from "../../features/rbac/projectAccessRights";+import { assertUnreachable } from "../../utils/typeChecks";import {buildDashboardsPath,buildDashboardWidgetPath,@@ -24,12 +22,12 @@ import {buildSessionsPath,buildTracePath,buildTracesPath,-} from "@langfuse/shared/src/server";+} from "../../server/utils/productUrl";import z from "zod";-import { TABLE_AGGREGATION_OPTIONS } from "@/src/utils/date-range-utils";-import { Role } from "@langfuse/shared/src/db";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/features/in-app-agent/constants";-import type { McpToolName } from "@/src/features/mcp/server/bootstrap";+import { TABLE_AGGREGATION_OPTIONS } from "../../utils/dateRanges";+import { ObservationLevelDomain, TracingSearchType } from "../../index";+import { Role } from "../../db";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "../constants";type InAppAgentMcpToolApproval = "auto" | "approval";@@ -47,12 +45,12 @@ type InAppAgentMcpToolPolicy = {};// Exhaustive approval policy for Langfuse MCP tools. Keys use the unprefixed-// MCP registry names; tests compare this map with toolRegistry so new MCP tools-// must be classified before the in-app agent can auto/approval-gate them.-export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES: Record<- McpToolName,- InAppAgentMcpToolPolicy-> = {+// MCP registry names and are the source of truth for the tool-name type below.+// Exhaustiveness against web's MCP toolRegistry is enforced by a compile-time+// assertion in web (src/features/in-app-agent/server/handler.ts) plus+// the registry-comparison servertest, so new MCP tools must be classified+// before the in-app agent can auto/approval-gate them.+export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES = {listAnnotationQueues: {approval: "auto",availability: { scope: "annotationQueues:read" },@@ -369,11 +367,17 @@ export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES: Record<approval: "approval",availability: { scope: "dashboards:CUD" },},-};+} satisfies Record<string, InAppAgentMcpToolPolicy>;-export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES = new Set<McpToolName>(- Object.keys(IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES) as McpToolName[],-);+export type InAppAgentLangfuseMcpToolName =+ keyof typeof IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES;++export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES =+ new Set<InAppAgentLangfuseMcpToolName>(+ Object.keys(+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES,+ ) as InAppAgentLangfuseMcpToolName[],+ );export const IN_APP_AGENT_AUTO_APPROVED_EXTERNAL_TOOL_NAMES = new Set([IN_APP_AGENT_REDIRECT_TOOL_NAME,@@ -397,12 +401,16 @@ export const IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES = new Set([...IN_APP_AGENT_SANDBOX_TOOL_NAMES,]);-export function isMcpToolName(input: string): input is McpToolName {- return IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(input as McpToolName);+export function isMcpToolName(+ input: string,+): input is InAppAgentLangfuseMcpToolName {+ return IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(+ input as InAppAgentLangfuseMcpToolName,+ );}export function isInAppAgentLangfuseMcpToolAvailable(params: {- toolName: McpToolName;+ toolName: InAppAgentLangfuseMcpToolName;userAccess?: InAppAgentUserAccess;}): boolean {if (!params.userAccess) {@@ -415,7 +423,7 @@ export function isInAppAgentLangfuseMcpToolAvailable(params: {return false;}- return hasProjectAccess({+ return hasProjectAccessByRole({role: params.userAccess.projectRole ?? Role.MEMBER,admin: params.userAccess.isAdmin,scope: policy.availability.scope,@@ -423,9 +431,9 @@ export function isInAppAgentLangfuseMcpToolAvailable(params: {}export function filterInAppAgentAvailableLangfuseMcpTools<TTool>(params: {- tools: Partial<Record<McpToolName, TTool>> | undefined;+ tools: Partial<Record<InAppAgentLangfuseMcpToolName, TTool>> | undefined;userAccess?: InAppAgentUserAccess;-}): Partial<Record<McpToolName, TTool>> {+}): Partial<Record<InAppAgentLangfuseMcpToolName, TTool>> {return Object.fromEntries(Object.entries(params.tools ?? {}).flatMap(([toolName, tool]) => {if (!isMcpToolName(toolName)) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c0a5f846a3..c31b5b0a2c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -202,6 +202,15 @@ importers:packages/shared:dependencies:+ '@ag-ui/client':+ specifier: ^0.0.52+ version: 0.0.52+ '@ag-ui/core':+ specifier: ^0.0.52+ version: 0.0.52+ '@ag-ui/mastra':+ specifier: 1.1.1+ version: 1.1.1(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkit/[email protected](1060c54502e6f347b0aa0d1cbe91322c))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))'@ai-sdk/amazon-bedrock':specifier: ^5.0.24version: 5.0.24([email protected])@@ -229,6 +238,9 @@ importers:'@aws-sdk/client-lambda':specifier: 'catalog:'version: 3.1074.0+ '@aws-sdk/client-lambda-microvms':+ specifier: 'catalog:'+ version: 3.1074.0'@aws-sdk/client-s3':specifier: 'catalog:'version: 3.1074.0@@ -253,6 +265,12 @@ importers:'@google-cloud/storage':specifier: ^7.19.0version: 7.19.0+ '@mastra/core':+ specifier: 1.46.0+ version: 1.46.0(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@mastra/mcp':+ specifier: 1.8.1+ version: 1.8.1(@cfworker/[email protected])(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])'@opentelemetry/api':specifier: '>=1.0.0 <1.10.0'version: 1.9.1@@ -265,6 +283,9 @@ importers:'@opentelemetry/sdk-trace-base':specifier: ^2.9.0version: 2.9.0(@opentelemetry/[email protected])+ '@paralleldrive/cuid2':+ specifier: ^2.2.2+ version: 2.2.2'@prisma/client':specifier: ^6.19.3@@ -289,6 +310,9 @@ importers:ai:specifier: ^7.0.0version: 7.0.8([email protected])+ ai-sdk-amazon-bedrock-v4:+ specifier: npm:@ai-sdk/[email protected]+ version: '@ai-sdk/[email protected]([email protected])'ajv:specifier: ^8.18.0version: 8.20.0@@ -325,6 +349,9 @@ importers:jsonpath-plus:specifier: 10.3.0version: 10.3.0+ langfuse:+ specifier: 3.38.4+ version: 3.38.4langfuse-langchain:specifier: 3.38.20version: 3.38.20([email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]([email protected])))@@ -367,6 +394,9 @@ importers:winston:specifier: ^3.15.0version: 3.15.0+ yaml:+ specifier: ^2.9.0+ version: 2.9.0zod:specifier: 4.3.6version: 4.3.6@@ -380,6 +410,9 @@ importers:'@repo/typescript-config':specifier: workspace:*version: link:../config-typescript+ '@types/dockerode':+ specifier: ^4.0.1+ version: 4.0.1'@types/lodash':specifier: ^4.17.24version: 4.17.24@@ -392,6 +425,9 @@ importers:'@types/react':specifier: 19.2.14version: 19.2.14+ dockerode:+ specifier: ^4.0.9+ version: 4.0.12dotenv-cli:specifier: ^7.4.4version: 7.4.4@@ -422,9 +458,6 @@ importers:'@ag-ui/mastra':specifier: 1.1.1version: 1.1.1(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkit/[email protected](1060c54502e6f347b0aa0d1cbe91322c))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))- '@ai-sdk/amazon-bedrock':- specifier: 4.0.81- version: 4.0.81([email protected])'@appsignal/opentelemetry-instrumentation-bullmq':specifier: ^0.8.0version: 0.8.0([email protected])@@ -539,9 +572,6 @@ importers:'@opentelemetry/sdk-trace-base':specifier: ^2.9.0version: 2.9.0(@opentelemetry/[email protected])- '@paralleldrive/cuid2':- specifier: ^2.2.2- version: 2.2.2'@prisma/instrumentation':specifier: ^6.19.3version: 6.19.3(@opentelemetry/[email protected])@@ -644,6 +674,9 @@ importers:'@uiw/react-codemirror':specifier: ^4.25.8version: 4.25.8(@babel/[email protected])(@codemirror/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected]))(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected](@lezer/[email protected]))([email protected]([email protected]))([email protected])+ ai-sdk-amazon-bedrock-v4:+ specifier: npm:@ai-sdk/[email protected]+ version: '@ai-sdk/[email protected]([email protected])'bcryptjs:specifier: ^2.4.3version: 2.4.3@@ -11865,6 +11898,19 @@ snapshots:rxjs: 7.8.1zod: 4.3.6+ '@ag-ui/[email protected](@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkit/[email protected](1060c54502e6f347b0aa0d1cbe91322c))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))':+ 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': 1.63.1(1060c54502e6f347b0aa0d1cbe91322c)+ '@mastra/client-js': 1.21.1(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])+ '@mastra/core': 1.46.0(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ fast-json-patch: 3.1.1+ rxjs: 7.8.1+ zod: 4.3.6+'@ag-ui/[email protected](@ag-ui/[email protected])(@cfworker/[email protected])([email protected])':dependencies:'@ag-ui/client': 0.0.57@@ -14158,6 +14204,32 @@ snapshots:- supports-color- utf-8-validate+ '@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])':+ dependencies:+ '@ai-sdk/ui-utils': 1.2.11([email protected])+ '@lukeed/uuid': 2.0.1+ '@mastra/core': 1.37.1(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])+ '@mastra/schema-compat': 1.2.10([email protected])+ canonicalize: 1.0.8+ jose: 6.2.3+ json-schema: 0.4.0+ zod: 4.3.6+ transitivePeerDependencies:+ - '@bufbuild/protobuf'+ - '@cfworker/json-schema'+ - '@grpc/grpc-js'+ - '@hono/standard-validator'+ - '@standard-community/standard-json'+ - '@standard-community/standard-openapi'+ - '@types/json-schema'+ - ai+ - bufferutil+ - express+ - openapi-types+ - rxjs+ - supports-color+ - utf-8-validate+'@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])':dependencies:@@ -14208,6 +14280,56 @@ snapshots:- supports-color- utf-8-validate+ '@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])':+ dependencies:+ '@ai-sdk/provider-utils-v5': '@ai-sdk/[email protected]([email protected])'+ '@ai-sdk/provider-utils-v6': '@ai-sdk/[email protected]([email protected])'+ '@ai-sdk/provider-v5': '@ai-sdk/[email protected]'+ '@ai-sdk/provider-v6': '@ai-sdk/[email protected]'+ '@ai-sdk/ui-utils-v5': '@ai-sdk/[email protected]([email protected])'+ '@isaacs/ttlcache': 2.1.5+ '@lukeed/uuid': 2.0.1+ '@mastra/schema-compat': 1.2.10([email protected])+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])+ '@sindresorhus/slugify': 2.2.1+ '@standard-schema/spec': 1.1.0+ ajv: 8.20.0+ croner: 10.0.1+ dotenv: 17.4.2+ execa: 9.6.1+ fastq: 1.20.1+ gray-matter: 4.0.3+ hono: 4.12.27+ hono-openapi: 1.3.0(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])+ ignore: 7.0.5+ json-schema: 0.4.0+ lru-cache: 11.2.7+ p-map: 7.0.4+ p-retry: 7.1.1+ picomatch: 4.0.4+ posthog-node: 5.45.2([email protected])+ tokenx: 1.3.0+ ws: 8.21.1+ xxhash-wasm: 1.1.0+ zod: 4.3.6+ transitivePeerDependencies:+ - '@bufbuild/protobuf'+ - '@cfworker/json-schema'+ - '@grpc/grpc-js'+ - '@hono/standard-validator'+ - '@standard-community/standard-json'+ - '@standard-community/standard-openapi'+ - '@types/json-schema'+ - ai+ - bufferutil+ - express+ - openapi-types+ - rxjs+ - supports-color+ - utf-8-validate+'@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':dependencies:@@ -14251,6 +14373,49 @@ snapshots:- supports-color- utf-8-validate+ '@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':+ dependencies:+ '@ai-sdk/provider-utils-v5': '@ai-sdk/[email protected]([email protected])'+ '@ai-sdk/provider-utils-v6': '@ai-sdk/[email protected]([email protected])'+ '@ai-sdk/provider-v5': '@ai-sdk/[email protected]'+ '@ai-sdk/provider-v6': '@ai-sdk/[email protected]'+ '@isaacs/ttlcache': 2.1.5+ '@lukeed/uuid': 2.0.1+ '@mastra/schema-compat': 1.3.0([email protected])+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])+ '@sindresorhus/slugify': 2.2.1+ '@standard-schema/spec': 1.1.0+ ajv: 8.20.0+ croner: 10.0.1+ dotenv: 17.4.2+ execa: 9.6.1+ fastq: 1.20.1+ gray-matter: 4.0.3+ ignore: 7.0.5+ jpeg-js: 0.4.4+ json-schema: 0.4.0+ lru-cache: 11.2.7+ p-map: 7.0.4+ p-retry: 7.1.1+ picomatch: 4.0.4+ posthog-node: 5.45.2([email protected])+ tokenx: 1.3.0+ ws: 8.21.1+ xxhash-wasm: 1.1.0+ zod: 4.3.6+ transitivePeerDependencies:+ - '@bufbuild/protobuf'+ - '@cfworker/json-schema'+ - '@grpc/grpc-js'+ - ai+ - bufferutil+ - express+ - rxjs+ - supports-color+ - utf-8-validate+'@mastra/[email protected](@cfworker/[email protected])(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@mastra/core': 1.46.0(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])@@ -14265,6 +14430,20 @@ snapshots:- supports-color- zod+ '@mastra/[email protected](@cfworker/[email protected])(@mastra/[email protected](@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])':+ dependencies:+ '@mastra/core': 1.46.0(@bufbuild/[email protected])(@cfworker/[email protected])(@grpc/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@modelcontextprotocol/ext-apps': 1.7.2(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])+ exit-hook: 5.1.0+ fast-deep-equal: 3.1.3+ transitivePeerDependencies:+ - '@cfworker/json-schema'+ - react+ - react-dom+ - supports-color+ - zod+'@mastra/[email protected]([email protected])':dependencies:json-schema-to-zod: 2.8.1@@ -18229,6 +18408,21 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@workflow/serde': 4.1.0-beta.2+ mdast-util-to-string: 4.0.0+ remark-gfm: 4.0.1+ remark-parse: 11.0.0+ remark-stringify: 11.0.0+ remend: 1.3.0+ unified: 11.0.5+ optionalDependencies:+ ai: 7.0.8([email protected])+ zod: 4.3.6+ transitivePeerDependencies:+ - supports-color+diff --git a/scripts/in-app-agent/README.md b/scripts/in-app-agent/README.mdindex b109c847b2..e568178328 100644--- a/scripts/in-app-agent/README.md+++ b/scripts/in-app-agent/README.md@@ -4,11 +4,15 @@The generated in-app agent skills live at:-`web/src/features/in-app-agent/server/skills/generated/raw`+`packages/shared/src/in-app-agent/server/skills/generated/raw`The generated TypeScript index lives at:-`web/src/features/in-app-agent/server/skills/generated/skill-markdown.ts`+`packages/shared/src/in-app-agent/server/skills/generated/skill-markdown.ts`++The generated module inlines each markdown file as a string literal so it+compiles under plain `tsc` in `@langfuse/shared`; the `raw/*.md` copies exist+for reviewable diffs only.Use `sync-raw-skills.mjs` to download all markdown files from`https://github.com/langfuse/skills/tree/main/skills/langfuse/references` whose@@ -29,9 +33,9 @@ node scripts/in-app-agent/sync-raw-skills.mjs --checkThe canonical system prompt for the in-app agent lives at:-`web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txt`+`packages/shared/src/in-app-agent/server/prompts/in-app-agent-system-prompt.ts`-The local Postgres seeder reads this file and creates the text prompt named+The local Postgres seeder imports this module and creates the text prompt named`in-app-agent-system-prompt` in the seed project`7a88fb47-b4e2-43b8-a06c-a5ce950dc53a` with the `production` and `latest`labels.diff --git a/scripts/in-app-agent/sync-prompt.sh b/scripts/in-app-agent/sync-prompt.shindex 8ae0b78b3b..ce983b6fce 100755--- a/scripts/in-app-agent/sync-prompt.sh+++ b/scripts/in-app-agent/sync-prompt.sh@@ -3,7 +3,7 @@ set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"-PROMPT_FILE="${REPO_ROOT}/web/src/features/in-app-agent/prompts/in-app-agent-system-prompt.txt"+PROMPT_FILE="${REPO_ROOT}/packages/shared/src/in-app-agent/server/prompts/in-app-agent-system-prompt.ts"PROMPT_NAME="in-app-agent-system-prompt"REGIONS=(STAGING EU US JP HIPAA)BASE_URLS=(@@ -19,7 +19,13 @@ if [[ ! -f "${PROMPT_FILE}" ]]; thenexit 1fi-PROMPT_CONTENT="$(<"${PROMPT_FILE}")"+# The prompt lives in a TS module (plain erasable TS); Node's native type+# stripping loads it without a build step.+PROMPT_CONTENT="$(node -e "+ import(process.argv[1]).then((m) =>+ process.stdout.write(m.IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE),+ );+" "${PROMPT_FILE}")"REQUEST_BODY="$(jq -n \--arg name "${PROMPT_NAME}" \diff --git a/scripts/in-app-agent/sync-raw-skills.mjs b/scripts/in-app-agent/sync-raw-skills.mjsindex 7bd39d7726..80e7cc3815 100644--- a/scripts/in-app-agent/sync-raw-skills.mjs+++ b/scripts/in-app-agent/sync-raw-skills.mjs@@ -14,7 +14,7 @@ import { format as formatWithPrettier } from "prettier";const repoRoot = resolve(new URL("../..", import.meta.url).pathname);const generatedDir = resolve(repoRoot,- "web/src/features/in-app-agent/server/skills/generated",+ "packages/shared/src/in-app-agent/server/skills/generated",);const rawTargetDir = resolve(generatedDir, "raw");const generatedModuleName = "skill-markdown.ts";@@ -154,23 +154,14 @@ const getCurrentManagedFileNames = () =>.map((entry) => entry.name).sort((left, right) => left.localeCompare(right));-const toImportIdentifier = (fileName) =>- `${fileName- .replace(/\.md$/, "")- .replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase())- .replace(/^[A-Z]/, (char) => char.toLowerCase())}Markdown`;-const renderGeneratedModule = async (files) => {- const imports = files- .map(- ({ name }) => `import ${toImportIdentifier(name)} from "./raw/${name}";`,- )- .join("\n");-+ // Markdown is inlined as string literals (instead of raw `.md` imports) so+ // the module compiles under plain tsc in @langfuse/shared without bundler+ // support. The raw/*.md files are still written for reviewable diffs.const entries = files.map(- ({ name }) =>- ` { fileName: ${JSON.stringify(name)}, markdown: ${toImportIdentifier(name)} },`,+ ({ name, content }) =>+ ` { fileName: ${JSON.stringify(name)}, markdown: ${JSON.stringify(content)} },`,).join("\n");@@ -178,8 +169,6 @@ const renderGeneratedModule = async (files) => {`// This file is generated by scripts/in-app-agent/sync-raw-skills.mjs.// Do not edit it manually.-${imports}-export const LANGFUSE_IN_APP_AGENT_SKILL_MARKDOWN = [${entries}] as const;diff --git a/web/.storybook/main.ts b/web/.storybook/main.tsindex 30d3d872cf..ce2db045b7 100644--- a/web/.storybook/main.ts+++ b/web/.storybook/main.ts@@ -161,6 +161,14 @@ const config: StorybookConfig = {find: /^@langfuse\/shared\/query$/,replacement: `${sharedSrc}/features/query`,},+ // Client-safe entry of the in-app-agent module (imported by the agent+ // window components and their stories). Deliberately no rule for the+ // `/server` subpaths: a story that pulls server code should fail the+ // build, not silently resolve.+ {+ find: /^@langfuse\/shared\/in-app-agent$/,+ replacement: `${sharedSrc}/in-app-agent`,+ },{find: /^\.prisma\/client\/index-browser$/,replacement: prismaBrowserStub,diff --git a/web/AGENTS.md b/web/AGENTS.mdindex a2beacd072..606796cac5 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -48,6 +48,11 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.- Use narrower subpaths such as `@langfuse/shared/src/env` or`@langfuse/shared/encryption` only when that focused surface is the clearestdependency.+- The in-app-agent runtime lives in shared:+ `@langfuse/shared/in-app-agent` is the client-safe contracts entry;+ `@langfuse/shared/in-app-agent/server` (and per-module subpaths) is+ server-only. Web keeps only the thin adapters in+ `src/features/in-app-agent/` (handler, router, UI).- See `../packages/shared/AGENTS.md` for the full shared export map and whateach entrypoint contains.- For the higher-level platform topology across web, worker, Postgres,diff --git a/web/package.json b/web/package.jsonindex 3c88ca0a3f..9a0ef61678 100644--- a/web/package.json+++ b/web/package.json@@ -33,7 +33,6 @@"@ag-ui/client": "^0.0.52","@ag-ui/core": "^0.0.52","@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","@aws-crypto/sha256-browser": "^5.2.0",@@ -72,7 +71,6 @@"@opentelemetry/resources": "^2.9.0","@opentelemetry/sdk-node": "^0.220.0","@opentelemetry/sdk-trace-base": "^2.9.0",- "@paralleldrive/cuid2": "^2.2.2","@prisma/instrumentation": "^6.19.3","@radix-ui/react-accordion": "^1.2.12","@radix-ui/react-alert-dialog": "^1.1.15",@@ -107,6 +105,7 @@"@trpc/server": "^11.13.4","@uiw/codemirror-themes": "^4.23.7","@uiw/react-codemirror": "^4.25.8",+ "ai-sdk-amazon-bedrock-v4": "npm:@ai-sdk/[email protected]","bcryptjs": "^2.4.3","bullmq": "^5.76.3","chroma-js": "^3.1.2",diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex bbe5146679..9cdfc7099b 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -1,12 +1,12 @@import { EventType } from "@ag-ui/core";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";-import { filterInAppAgentAvailableLangfuseMcpTools } from "@/src/features/in-app-agent/server/tools";-import { storePendingToolApproval } from "@/src/features/in-app-agent/server/human-in-the-loop";+import { filterInAppAgentAvailableLangfuseMcpTools } from "@langfuse/shared/in-app-agent/server/tools";+import { storePendingToolApproval } from "@langfuse/shared/in-app-agent/server/human-in-the-loop";import type {AgUiEvent,InAppAgentToolApprovalRequest,-} from "@/src/features/in-app-agent/schema";-import { appendRunEvents } from "@/src/features/in-app-agent/server/persistence";+} from "@langfuse/shared/in-app-agent";+import { appendRunEvents } from "@langfuse/shared/in-app-agent/server/persistence";import { env } from "@/src/env.mjs";import { InAppAgentRunStatus } from "@langfuse/shared";import { Prisma, prisma } from "@langfuse/shared/src/db";@@ -77,7 +77,7 @@ vi.mock("@/src/features/public-api/server/RateLimitService", () => ({}),}));-vi.mock("@/src/features/in-app-agent/server/agent", () => ({+vi.mock("@langfuse/shared/in-app-agent/server/agent", () => ({createAgUiStream: agentMocks.createAgUiStream,}));diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex 31c3b85472..ecaef3a262 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -23,8 +23,8 @@ import { env } from "@/src/env.mjs";import {createInAppAgentConversationId,createInAppAgentRunId,-} from "@/src/features/in-app-agent/ids";-import { type AgUiEvent } from "@/src/features/in-app-agent/schema";+} from "@langfuse/shared/in-app-agent";+import { type AgUiEvent } from "@langfuse/shared/in-app-agent";import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";import {createRun,@@ -36,9 +36,9 @@ import {flushPendingRunEvents,shouldFlushPersistedEvent,toPersistableAgentEvent,-} from "@/src/features/in-app-agent/server/persistence";+} from "@langfuse/shared/in-app-agent/server/persistence";import { createInnerTRPCContext } from "@/src/server/api/trpc";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/features/in-app-agent/constants";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";vi.mock("@/src/server/auth", () => ({getServerAuthSession: vi.fn(),diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex f7f138320f..4f0beb18d1 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -4,29 +4,31 @@ import { Agent } from "@mastra/core/agent";import { MCPClient } from "@mastra/mcp";import { describe, expect, it, vi } from "vitest";-import type { AgUiEvent } from "@/src/features/in-app-agent/schema";+import type { AgUiEvent } from "@langfuse/shared/in-app-agent";import {IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER,IN_APP_AGENT_MCP_USER_AGENT,IN_APP_AGENT_REDIRECT_TOOL_NAME,IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,-} from "@/src/features/in-app-agent/constants";-import { patchMastraApprovalChunks } from "@/src/features/in-app-agent/server/agent";+} from "@langfuse/shared/in-app-agent";+import {+ patchMastraApprovalChunks,+ type createAgUiStream,+} from "@langfuse/shared/in-app-agent/server/agent";import {createInAppAgentSandbox,type SandboxProvider,type SandboxSession,-} from "@/src/features/in-app-agent/server/sandbox";-import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES } from "@/src/features/in-app-agent/server/tools";+} from "@langfuse/shared/in-app-agent/server/sandbox";+import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES } from "@langfuse/shared/in-app-agent/server/tools";import {DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS,decodeFiltersGeneric,} from "@langfuse/shared";import "@/src/features/mcp/server/bootstrap";import { toolRegistry } from "@/src/features/mcp/server/registry";-import type { MastraAgent } from "@ag-ui/mastra";import type { Langfuse } from "langfuse";-import type { InAppAgentTracingConfig } from "@/src/features/in-app-agent/server/instrumentation";+import type { InAppAgentTracingConfig } from "@langfuse/shared/in-app-agent/server/instrumentation";// Shape of the tool entries the mocked MCP client feeds into the Agent// constructor. `Agent`'s own `tools` type is a `DynamicArgument` union that@@ -175,7 +177,7 @@ vi.mock("@ag-ui/mastra", () => ({}),}));-vi.mock("@ai-sdk/amazon-bedrock", () => ({+vi.mock("ai-sdk-amazon-bedrock-v4", () => ({createAmazonBedrock: vi.fn(() => vi.fn(() => ({}))),}));@@ -259,7 +261,7 @@ vi.mock("@mastra/mcp", () => ({}),}));-vi.mock("@/src/features/in-app-agent/server/instrumentation", () => ({+vi.mock("@langfuse/shared/in-app-agent/server/instrumentation", () => ({createInAppAgentInstrumentation:instrumentationMocks.createInAppAgentInstrumentation,}));@@ -278,7 +280,12 @@ const createPatchedChunkProcessor = () => {})),};- patchMastraApprovalChunks(adapter as unknown as MastraAgent);+ // Derive the parameter type from the function instead of naming+ // MastraAgent: web and shared can resolve @ag-ui/mastra to different pnpm+ // peer instances, which tsc treats as non-identical types.+ patchMastraApprovalChunks(+ adapter as unknown as Parameters<typeof patchMastraApprovalChunks>[0],+ );const processor = adapter.createChunkProcessor({ onError });@@ -435,7 +442,7 @@ describe("createAgUiStream", () => {it("serializes valid events including adapter snapshots and reasoning messages", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -788,7 +795,7 @@ describe("createAgUiStream", () => {it("does not enable Bedrock reasoning for non-Claude models", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -860,7 +867,7 @@ describe("createAgUiStream", () => {it("executes approved tools manually and continues with tool result history", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = createToolApprovalResumeInput(true);adapterEvents.inputs = [];adapterEvents.items = [@@ -1054,7 +1061,7 @@ describe("createAgUiStream", () => {it("continues approved tools with a tool error result when execution fails", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = createToolApprovalResumeInput(true);const validationErrorMessage ="MCP error -32602: Validation failed: categories: Category must be an array of objects with label value pairs, where labels and values are unique.";@@ -1189,7 +1196,7 @@ describe("createAgUiStream", () => {it("escapes screen context delimiters before compiling prompt instructions", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -1263,7 +1270,7 @@ describe("createAgUiStream", () => {it("continues after rejected tools and asks the user how to proceed", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = createToolApprovalResumeInput(false);const rejectionError = JSON.stringify({code: IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,@@ -1430,7 +1437,7 @@ describe("createAgUiStream", () => {it("uses V4-compatible filters for traces redirect actions", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -1510,7 +1517,7 @@ describe("createAgUiStream", () => {it("lets HttpAgent subscribers observe streamed run errors", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -1566,7 +1573,7 @@ describe("createAgUiStream", () => {},});const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(- new Response(serverStream, {+ new Response(serverStream as unknown as BodyInit, {status: 200,headers: { "Content-Type": "text/event-stream" },}),@@ -1600,7 +1607,7 @@ describe("createAgUiStream", () => {it("does not expose sandbox tools when sandboxing is disabled", async () => {const { createAgUiStream } =- await import("@/src/features/in-app-agent/server/agent");+ await import("@langfuse/shared/in-app-agent/server/agent");const input = {threadId: "conversation-1",runId: "run-1",@@ -1669,7 +1676,9 @@ describe("createAgUiStream", () => {});async function readStream(- stream: ReadableStream<Uint8Array>,+ // Shared compiles without the DOM lib, so createAgUiStream's declared+ // return type is Node's stream/web ReadableStream, not the DOM one.+ stream: Awaited<ReturnType<typeof createAgUiStream>>,onEvent?: (event: AgUiEvent) => void,) {const reader = stream.getReader();diff --git a/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.tsindex d03fae1085..114befcc9b 100644--- a/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts@@ -167,7 +167,7 @@ describe("in-app agent docker sandbox provider", () => {it("recreates the named container when it was manually removed", async () => {const { createDockerSandboxProvider } =- await import("@/src/features/in-app-agent/server/sandbox/providers/docker");+ await import("@langfuse/shared/in-app-agent/server/sandbox/providers/docker");const provider = await createDockerSandboxProvider({image: "langfuse-in-app-agent-sandbox:latest",});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.tsindex 5c7d563de7..d226e11a53 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@@ -3,9 +3,9 @@ import { EventType } from "@ag-ui/core";import {getInAppAgentInstrumentationObservationId,getInAppAgentInstrumentationTraceId,-} from "@/src/features/in-app-agent/constants";-import type { AgUiRunAgentInput } from "@/src/features/in-app-agent/schema";-import { InAppAgentInstrumentation } from "@/src/features/in-app-agent/server/instrumentation";+} from "@langfuse/shared/in-app-agent";+import type { AgUiRunAgentInput } from "@langfuse/shared/in-app-agent";+import { InAppAgentInstrumentation } from "@langfuse/shared/in-app-agent/server/instrumentation";const runId = "run-1";const traceId = getInAppAgentInstrumentationTraceId(runId);diff --git a/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.tsindex 4fcf440351..1abcff0a57 100644--- a/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts@@ -51,7 +51,7 @@ describe("in-app agent lambda microvm sandbox provider", () => {it("uses suspend for suspendSession and terminate for terminateSession", async () => {const { createLambdaMicrovmSandboxProvider } =- await import("@/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm");+ await import("@langfuse/shared/in-app-agent/server/sandbox/providers/lambdaMicrovm");const provider = createLambdaMicrovmSandboxProvider({imageIdentifier: "image-1",@@ -111,7 +111,7 @@ describe("in-app agent lambda microvm sandbox provider", () => {});const { createLambdaMicrovmSandboxProvider } =- await import("@/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm");+ await import("@langfuse/shared/in-app-agent/server/sandbox/providers/lambdaMicrovm");const provider = createLambdaMicrovmSandboxProvider({imageIdentifier: "image-1",executionRoleArn: "arn:aws:iam::123456789012:role/sandbox",@@ -170,7 +170,7 @@ describe("in-app agent lambda microvm sandbox provider", () => {});const { createLambdaMicrovmSandboxProvider } =- await import("@/src/features/in-app-agent/server/sandbox/providers/lambdaMicrovm");+ await import("@langfuse/shared/in-app-agent/server/sandbox/providers/lambdaMicrovm");const provider = createLambdaMicrovmSandboxProvider({imageIdentifier: "image-1",executionRoleArn: "arn:aws:iam::123456789012:role/sandbox",diff --git a/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.tsindex 0e8c1e3bed..c18b616142 100644--- a/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.ts@@ -1,7 +1,7 @@import {createInAppAgentMcpRunOverride,InAppAgentMcpRunOverrideSchema,-} from "@/src/features/in-app-agent/server/human-in-the-loop";+} from "@langfuse/shared/in-app-agent/server/human-in-the-loop";describe("in-app agent MCP run override", () => {it("serializes the override as plain JSON", async () => {diff --git a/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.tsindex b2f48e5ce9..1a20753db8 100644--- a/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.ts@@ -1,4 +1,4 @@-import { getBedrockReasoningProviderOptions } from "@/src/features/in-app-agent/server/agent";+import { getBedrockReasoningProviderOptions } from "@langfuse/shared/in-app-agent/server/agent";describe("getBedrockReasoningProviderOptions", () => {it("sends adaptive thinking with summarized display to Claude models by default", () => {diff --git a/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.tsindex 0e03f2e21c..4af9b4b6ef 100644--- a/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts@@ -1,8 +1,8 @@import { EventType } from "@ag-ui/core";import { describe, expect, it } from "vitest";-import { getSandboxToolCallFiles } from "@/src/features/in-app-agent/server/persistence";-import { createInAppAgentSandbox } from "@/src/features/in-app-agent/server/sandbox";+import { getSandboxToolCallFiles } from "@langfuse/shared/in-app-agent/server/persistence";+import { createInAppAgentSandbox } from "@langfuse/shared/in-app-agent/server/sandbox";describe("in-app agent sandbox", () => {it("persists sandbox session state when a turn ends", async () => {diff --git a/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.ts b/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.tsindex 4088966b7b..716c29f607 100644--- a/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.ts+++ b/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.ts@@ -1,8 +1,8 @@-import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/features/in-app-agent/constants";+import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@langfuse/shared/in-app-agent";import {createInAppAgentMcpRunOverride,InAppAgentMcpRunOverrideSchema,-} from "@/src/features/in-app-agent/server/human-in-the-loop";+} from "@langfuse/shared/in-app-agent/server/human-in-the-loop";import { getInAppAgentContext } from "@/src/pages/api/public/mcp";import type { NextApiRequest, NextApiResponse } from "next";import { createMocks } from "node-mocks-http";diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.tsxindex 96397f7d45..f5341bc970 100644--- a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx@@ -30,7 +30,7 @@ import {type InAppAgentMessageFeedback,type InAppAgentMessageFeedbackValue,type InAppAgentMessageSource,-} from "@/src/features/in-app-agent/schema";+} from "@langfuse/shared/in-app-agent";import {Popover,PopoverAnchor,diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsxindex 06a8219a7c..cc04c4c23a 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx@@ -41,7 +41,7 @@ import {type InAppAgentMessageContent,type InAppAgentMessageRole,} from "./InAppAgentMessage";-import type { InAppAgentMessageFeedbackValue } from "@/src/features/in-app-agent/schema";+import type { InAppAgentMessageFeedbackValue } from "@langfuse/shared/in-app-agent";import type { InAppAgentScreenContextDescription } from "@/src/features/in-app-agent/context";import { InAppAgentToolCallCard } from "@/src/features/in-app-agent/components/InAppAgentToolCallCard";import {diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.ts b/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.tsindex 607860c1dc..7197468fdc 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.ts+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.ts@@ -1,4 +1,4 @@-import type { AgUiMessage } from "@/src/features/in-app-agent/schema";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";import {createInAppAgentDisplayState,projectInAppAgentMessagesForDisplay,diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex f4dab6716e..5f9a291c53 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -21,8 +21,8 @@ import {createInAppAgentConversationId,createInAppAgentMessageId,createInAppAgentRunId,-} from "@/src/features/in-app-agent/ids";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/features/in-app-agent/constants";+} from "@langfuse/shared/in-app-agent";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";import {AgUiMessageSchema,type AgUiMessage,@@ -30,7 +30,7 @@ import {type InAppAgentMessageFeedbackValue,type InAppAgentRuntimeState,type InAppAgentToolApprovalRequest,-} from "@/src/features/in-app-agent/schema";+} from "@langfuse/shared/in-app-agent";import type { InAppAgentError } from "@/src/features/in-app-agent/components/utils/utils";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showErrorToast } from "@/src/features/notifications/showErrorToast";diff --git a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsxindex 9c9dd238bb..1d887d7067 100644--- a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx+++ b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx@@ -2,7 +2,7 @@ import { act, render, screen } from "@testing-library/react";import { StrictMode } from "react";import type { InAppAgentPendingToolApproval } from "./InAppAiAgentProvider";-import type { AgUiMessage } from "@/src/features/in-app-agent/schema";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";import { useSmoothStreamingMessages } from "./useSmoothStreamingMessages";const userMessage = {diff --git a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.tsindex 3eea262965..9fb9ccad08 100644--- a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts+++ b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts@@ -1,8 +1,8 @@import { useEffect, useEffectEvent, useReducer } from "react";import type { InAppAgentPendingToolApproval } from "./InAppAiAgentProvider";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/features/in-app-agent/constants";-import type { AgUiMessage } from "@/src/features/in-app-agent/schema";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";import { assertUnreachable } from "@/src/utils/types";const FRAME_DURATION_MS = 40;diff --git a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/features/in-app-agent/components/utils/utils.clienttest.tsindex 1668442f86..94a703e68d 100644--- a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts+++ b/web/src/features/in-app-agent/components/utils/utils.clienttest.ts@@ -1,4 +1,4 @@-import type { AgUiMessage } from "@/src/features/in-app-agent/schema";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";import {extractLangfuseDocsSources,getDrawerMessages,diff --git a/web/src/features/in-app-agent/components/utils/utils.ts b/web/src/features/in-app-agent/components/utils/utils.tsindex 1d0f31a581..38c768bcf6 100644--- a/web/src/features/in-app-agent/components/utils/utils.ts+++ b/web/src/features/in-app-agent/components/utils/utils.ts@@ -7,7 +7,7 @@ import { safeJsonParse, stableJsonStringify } from "@langfuse/shared";import {IN_APP_AGENT_REDIRECT_TOOL_NAME,IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,-} from "@/src/features/in-app-agent/constants";+} from "@langfuse/shared/in-app-agent";import {AgUiMessageSchema,type AgUiMessage,@@ -15,7 +15,7 @@ import {type InAppAgentMessageSource,InAppAgentRedirectActionToolResultSchema,InAppAgentMessageSourceSchema,-} from "@/src/features/in-app-agent/schema";+} from "@langfuse/shared/in-app-agent";export type InAppAgentError =| { type: "generic"; message: string }diff --git a/web/src/features/in-app-agent/context.ts b/web/src/features/in-app-agent/context.tsindex 2f13c86f94..1d04a5be97 100644--- a/web/src/features/in-app-agent/context.ts+++ b/web/src/features/in-app-agent/context.ts@@ -1,4 +1,4 @@-import type { AgUiRunAgentInput } from "@/src/features/in-app-agent/schema";+import type { AgUiRunAgentInput } from "@langfuse/shared/in-app-agent";import {isInAppAgentQuickActionContext,type InAppAgentQuickActionAttribution,diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.tsindex 58e3ffa5a2..b1820785f6 100644--- a/web/src/features/in-app-agent/server/handler.ts+++ b/web/src/features/in-app-agent/server/handler.ts@@ -6,13 +6,13 @@ import { env } from "@/src/env.mjs";import {createInAppAgentMessageId,createInAppAgentRunId,-} from "@/src/features/in-app-agent/ids";+} from "@langfuse/shared/in-app-agent";import {getInAppAgentMessageEntryPointTraceMetadata,getInAppAgentQuickActionTraceMetadata,sanitizeInAppAgentContext,} from "@/src/features/in-app-agent/context";-import { getInAppAgentInstrumentationTraceId } from "@/src/features/in-app-agent/constants";+import { getInAppAgentInstrumentationTraceId } from "@langfuse/shared/in-app-agent";import {AgUiRunAgentInputSchema,type AgUiRunAgentInput,@@ -21,19 +21,21 @@ import {type AgUiMessage,ResumeForwardedPropsSchema,type ResumeForwardedProps,-} from "@/src/features/in-app-agent/schema";-import { createAgUiStream } from "@/src/features/in-app-agent/server/agent";+} from "@langfuse/shared/in-app-agent";+import { createAgUiStream } from "@langfuse/shared/in-app-agent/server/agent";import {consumeAndValidatePendingToolApproval,createInAppAgentMcpRunOverride,parseInAppAgentInterruptEvent,storePendingToolApproval,validatePendingToolApproval,-} from "@/src/features/in-app-agent/server/human-in-the-loop";+} from "@langfuse/shared/in-app-agent/server/human-in-the-loop";import {+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES,isMcpToolName,+ type InAppAgentLangfuseMcpToolName,type InAppAgentUserAccess,-} from "@/src/features/in-app-agent/server/tools";+} from "@langfuse/shared/in-app-agent/server/tools";import type { McpToolName } from "@/src/features/mcp/server/bootstrap";import {createRun,@@ -47,12 +49,12 @@ import {flushPendingRunEvents,shouldFlushPersistedEvent,toPersistableAgentEvent,-} from "@/src/features/in-app-agent/server/persistence";-import { createInAppAgentSandbox } from "@/src/features/in-app-agent/server/sandbox";+} from "@langfuse/shared/in-app-agent/server/persistence";+import { createInAppAgentSandbox } from "@langfuse/shared/in-app-agent/server/sandbox";import {createInAppAgentSandboxProvider,getDefaultInAppAgentSandboxProviderType,-} from "@/src/features/in-app-agent/server/sandbox/config";+} from "@langfuse/shared/in-app-agent/server/sandbox/config";import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";import { getAuthOptions } from "@/src/server/auth";import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";@@ -91,6 +93,15 @@ import {deleteApiKeyFromDb,} from "@langfuse/shared/src/server/auth/apiKeys";+// Compile-time exhaustiveness contract between web's MCP tool registry and the+// shared runtime's tool policies (the runtime can no longer import the+// registry type): every registry tool must be classified in the policies map,+// and every policy key must still exist in the registry.+IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES satisfies Record<McpToolName, unknown>;+type AssertPolicyKeysInRegistry<T extends McpToolName = McpToolName> = T;+export type _InAppAgentPolicyKeysAreRegistryTools =+ AssertPolicyKeysInRegistry<InAppAgentLangfuseMcpToolName>;+const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";const MAX_IN_APP_AGENT_INPUT_BYTES = 1024 * 1024;const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =@@ -601,7 +612,10 @@ export default async function handler(request: Request) {});streamCreated = true;- return new Response(stream, {+ // Shared compiles without the DOM lib; its declared stream type is+ // Node's stream/web ReadableStream, which is what Response accepts+ // at runtime.+ return new Response(stream as unknown as BodyInit, {headers: {"Content-Type": "text/event-stream; charset=utf-8","Content-Encoding": "none",diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.tsindex e13e1111d2..df4d5d5daa 100644--- a/web/src/features/in-app-agent/server/router.ts+++ b/web/src/features/in-app-agent/server/router.ts@@ -18,8 +18,8 @@ import { env } from "@/src/env.mjs";import {getInAppAgentInstrumentationObservationId,getInAppAgentInstrumentationTraceId,-} from "@/src/features/in-app-agent/constants";-import { InAppAgentMessageFeedbackValueSchema } from "@/src/features/in-app-agent/schema";+} from "@langfuse/shared/in-app-agent";+import { InAppAgentMessageFeedbackValueSchema } from "@langfuse/shared/in-app-agent";import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";import {createTRPCRouter,@@ -33,7 +33,7 @@ import {getOwnedConversationOrThrow,isInAppAgentConversationWriteLocked,serializeConversation,-} from "@/src/features/in-app-agent/server/persistence";+} from "@langfuse/shared/in-app-agent/server/persistence";const CONVERSATION_LIST_LIMIT = 50;diff --git a/web/src/features/in-app-agent/server/skills/generated/skill-markdown.ts b/web/src/features/in-app-agent/server/skills/generated/skill-markdown.tsdeleted file mode 100644index 9e4ad9514b..0000000000--- a/web/src/features/in-app-agent/server/skills/generated/skill-markdown.ts+++ /dev/null@@ -1,14 +0,0 @@-// This file is generated by scripts/in-app-agent/sync-raw-skills.mjs.-// Do not edit it manually.--import cliMarkdown from "./raw/cli.md";-import errorAnalysisMarkdown from "./raw/error-analysis.md";-import promptEngineeringMarkdown from "./raw/prompt-engineering.md";-import v4ProjectMigrationMarkdown from "./raw/v4-project-migration.md";--export const LANGFUSE_IN_APP_AGENT_SKILL_MARKDOWN = [- { fileName: "cli.md", markdown: cliMarkdown },- { fileName: "error-analysis.md", markdown: errorAnalysisMarkdown },- { fileName: "prompt-engineering.md", markdown: promptEngineeringMarkdown },- { fileName: "v4-project-migration.md", markdown: v4ProjectMigrationMarkdown },-] as const;diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.tsindex fcdfdce4e0..1ea3c8d826 100644--- a/web/src/pages/api/public/mcp/index.ts+++ b/web/src/pages/api/public/mcp/index.ts@@ -45,8 +45,8 @@ import {} from "@langfuse/shared";import { ZodError } from "zod";import { isUserInputError } from "@/src/features/mcp/core/errors";-import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/features/in-app-agent/constants";-import { InAppAgentMcpRunOverrideSchema } from "@/src/features/in-app-agent/server/human-in-the-loop";+import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@langfuse/shared/in-app-agent";+import { InAppAgentMcpRunOverrideSchema } from "@langfuse/shared/in-app-agent/server/human-in-the-loop";// Bootstrap MCP features - registers all tools at module load timeimport "@/src/features/mcp/server/bootstrap";diff --git a/web/src/utils/base-url.ts b/web/src/utils/base-url.tsindex 2491f5ea7f..18be831c56 100644--- a/web/src/utils/base-url.ts+++ b/web/src/utils/base-url.ts@@ -1,9 +1,9 @@import { env } from "@/src/env.mjs";// Mirrors getBaseUrl/getProductBaseUrl in @langfuse/shared-// (src/server/utils/baseUrl.ts), which shared server code such as productUrl-// uses. Web keeps its own copy so callers read the validated web env (and-// tests can mock @/src/env.mjs as the seam).+// (src/server/utils/baseUrl.ts), which the shared in-app-agent runtime uses.+// Web keeps its own copy so callers read the validated web env (and tests can+// mock @/src/env.mjs as the seam).const LOCALHOST_HOST_PATTERN = /^(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i;export const getBaseUrl = () => {diff --git a/web/vitest.config.mts b/web/vitest.config.mtsindex 3036ec6c48..da5a9962ea 100644--- a/web/vitest.config.mts+++ b/web/vitest.config.mts@@ -64,6 +64,100 @@ function markdownRawPlugin() {export default defineConfig({plugins: [markdownRawPlugin(), tsconfigPaths(), react()],+ resolve: {+ // The in-app-agent runtime lives in @langfuse/shared. Its built dist is+ // CJS, whose require() calls bypass vitest's mocker — so tests that mock+ // the runtime's dependencies (@mastra/*, instrumentation, …) would hit+ // the real modules. Alias the runtime subpaths to shared *source* so+ // vite processes it as ESM and mocks intercept.+ alias: [+ {+ find: /^@langfuse\/shared\/in-app-agent\/server\/(.+)$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/in-app-agent/server/$1",+ ),+ },+ {+ find: /^@langfuse\/shared\/in-app-agent\/server$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/in-app-agent/server/index.ts",+ ),+ },+ {+ find: /^@langfuse\/shared\/in-app-agent$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/in-app-agent/index.ts",+ ),+ },+ // The runtime source reaches the rest of shared via relative imports+ // (../../../server etc.), so shared's other entry points must resolve+ // to the same source files — otherwise tests would load a second dist+ // copy of shared (split singletons, vi.mock("@langfuse/shared/src/+ // server") missing the runtime's imports).+ {+ find: /^@langfuse\/shared\/src\/(.+)$/,+ replacement: join(import.meta.dirname, "../packages/shared/src/$1"),+ },+ {+ find: /^@langfuse\/shared\/encryption$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/encryption/index.ts",+ ),+ },+ {+ find: /^@langfuse\/shared\/query$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/features/query/index.ts",+ ),+ },+ {+ find: /^@langfuse\/shared\/query\/server$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/features/query/server/index.ts",+ ),+ },+ {+ find: /^@langfuse\/shared\/monitors$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/features/monitors/index.ts",+ ),+ },+ {+ find: /^@langfuse\/shared\/monitors\/server$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/features/monitors/server.ts",+ ),+ },+ {+ find: /^@langfuse\/shared$/,+ replacement: join(+ import.meta.dirname,+ "../packages/shared/src/index.ts",+ ),+ },+ ],+ // The runtime source resolves Mastra/AG-UI/Bedrock through shared's+ // node_modules symlinks — a different module id than the test files'+ // vi.mock registrations, which resolve through web's. Dedupe forces a+ // single resolution so the mocks intercept the runtime's imports.+ dedupe: [+ "@mastra/core",+ "@mastra/mcp",+ "@ag-ui/core",+ "@ag-ui/client",+ "@ag-ui/mastra",+ "ai-sdk-amazon-bedrock-v4",+ "langfuse",+ ],+ },test: {reporters: process.env.CI? ["default", new VitestCiReporter()]