Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(agent): load managed skills from Langfuse (#19148)

tobi_kl1b35681f9d56
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.md
index 55420dfd8c..29d7acbf0f 100644
--- a/.agents/skills/seed-test-data/SKILL.md
+++ b/.agents/skills/seed-test-data/SKILL.md
@@ -28,6 +28,7 @@ this.
| I need... | Command |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Managed in-app assistant skills | `pnpm run seed -- assistant-skills` (imports bundled SKILL.md files through the synthetic seed key; production label, in-app-agent tag; reuses unchanged versions) |
| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |
| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |
| Async parents whose subtree outlives their own span (subtree wall-clock duration badge) | add `--async-parents` to `trace-tree` (root + hub end immediately while children keep running) |
@@ -79,6 +80,15 @@ for batch IDs, dataset contents, and clustering settings.
## Contract
+For managed in-app assistant skills, run `pnpm run seed -- assistant-skills`.
+It imports the bundled catalog through the synthetic seed API key, reuses
+unchanged versions, labels them `production`, and adds the `in-app-agent` tag
+(`--tag` overrides it). See the [local assistant setup](../../../packages/shared/scripts/seeder/README.md#managed-assistant-skills)
+for the worker configuration.
+Add `--demo` for an instructions-only `local-assistant-check` skill;
+ask the assistant "Run the local assistant check skill." and expect
+"Hosted skills are connected."
+
- Last stdout line is a JSON summary: `traceIds`, `sessionIds`, `counts`,
`verified` (ClickHouse readback), `links` (UI deep links). Use `--json` to
suppress progress logs. Non-zero exit = data did not land; the error
diff --git a/.env.dev.example b/.env.dev.example
index 99846ade5d..eab3db383b 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -362,6 +362,10 @@ LANGFUSE_AI_SMALL_MODEL="eu.anthropic.claude-haiku-5-5"
# Self-hosted Assistant instance switch. Unset or "false" hides Assistant.
# Cloud is on unless this is "false".
# LANGFUSE_IN_APP_AGENT_ENABLED="true"
+# Merge production skills tagged in-app-agent from the AI-features project.
+# Remote skills take precedence over bundled skills on an exact name match.
+# Seed them first: pnpm run seed -- assistant-skills
+# LANGFUSE_IN_APP_AGENT_SKILLS_TAG="in-app-agent"
# Evaluator media transport: url, inline, or disabled. Unset defaults to
# inline locally and url in DEV previews. Disabled keeps media references as text.
diff --git a/.env.prod.example b/.env.prod.example
index 0b4dacf7d1..c7d9b3e880 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -350,6 +350,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# Langfuse Assistant (beta). Hidden unless this is true, on web and worker.
# See https://langfuse.com/self-hosting/configuration/langfuse-assistant
# LANGFUSE_IN_APP_AGENT_ENABLED=true
+# Optional production skills from the AI-features project, merged with bundled skills.
+# Remote skills take precedence on an exact name match.
+# LANGFUSE_IN_APP_AGENT_SKILLS_TAG=in-app-agent
# Evaluator media transport: url, inline, or disabled. Unset defaults to inline
# for self-hosted deployments and url for DEV previews and Langfuse Cloud.
diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.md
index d48fac19ef..a2cd22ebd8 100644
--- a/packages/shared/scripts/seeder/AGENTS.md
+++ b/packages/shared/scripts/seeder/AGENTS.md
@@ -35,6 +35,8 @@ pnpm run seed -- experiment-io # one v4 experiment with three chat/nested JSON
pnpm run seed -- experiment-filters # three v4 runs over 60 items, shifted numeric/categorical/boolean scores, status, metadata and missing results
pnpm run seed -- experiment-io --compare # same dataset plus a second run with a long chat output, for the comparison table
NEXTAUTH_URL=https://pr-<N>.preview.langfuse.com pnpm run seed -- evaluator-gallery --count 200 # project-owned evaluators via the seeded public API key
+pnpm run seed -- assistant-skills # bundled assistant skills as production versions tagged in-app-agent; unchanged versions are reused
+pnpm run seed -- assistant-skills --demo # adds an instructions-only local-assistant-check skill with a fixed response
```
The last stdout line of a run is a JSON summary with `traceIds`,
diff --git a/packages/shared/scripts/seeder/README.md b/packages/shared/scripts/seeder/README.md
index 75d57e1d3a..a6ce9255e2 100644
--- a/packages/shared/scripts/seeder/README.md
+++ b/packages/shared/scripts/seeder/README.md
@@ -51,6 +51,7 @@ programmatic calls from the dx seed chain.
| `annotation-queue` | two human-annotation queues for the annotate UI: a "core types" queue with one of every score-field render path (categorical toggle/combobox, boolean, ranged/decimal/unranged numeric, text) over fresh trace items, and an "edge cases" queue adding archived/stale/partial scores, comments, and observation/session/deleted/completed items | `--core-items`, `--v4` (default true) |
| `custom-models` | project-level model definitions (one tiered with a condition-gated second tier and a usage type priced at 0, one single-tier) plus a trace whose generations link to them, and one generation whose model matches no definition so its badge opens the create dialog | β€” |
| `evaluator-gallery` | project-owned code evaluators for gallery pagination and infinite-scroll testing; reconciles deterministic names through the seeded public API key so local and PR preview environments are supported | `--count` |
+| `assistant-skills` | bundled assistant skills imported through the seeded public API key, with production labels and an assistant catalog tag; unchanged versions are reused | `--tag`, `--demo` |
| `support-agent` | one demo-grade, fully handcrafted trace: a customer-support copilot resolving a duplicate-charge refund β€” input guardrail β†’ intent classification β†’ parallel context fan-out (CRM/billing/tickets) β†’ 3-turn ReAct loop (llm.chat + Stripe tools) β†’ drafted reply β†’ output guardrail β†’ send | β€” |
| `incident-session` | one demo-grade, fully handcrafted multi-user v4 session: an on-call copilot and four engineers work a checkout-latency incident over seven turns β€” parallel, untraced and failing tool calls, a nested sub-agent, reasoning, markdown answers, a guardrail-flagged refusal, typed session scores and comments | `--v4` (default true) |
| `timeline-shapes` | a dozen SMALL traces (4-25 observations each), one per timeline morphology: rag answer, streamed chat, parallel fan-out, retry backoff with widening gaps, a 13-minute wait on a human, one slow tool dwarfing everything, an error cascade with failover, in-flight spans, zero-duration checkpoints, a ten-level ladder, 24 flat siblings, and a three-turn agent loop | `--shape all\|rag-answer\|streaming-chat\|parallel-fanout\|retry-backoff\|waiting-on-approval\|slow-tool\|error-cascade\|still-running\|checkpoint-marks\|deep-ladder\|flat-siblings\|mixed-loop` |
@@ -78,6 +79,47 @@ Scenarios compose: e.g. a session where one trace has zero observations is
two `long-session` runs sharing a `--session-id` with different
`--id-prefix` values.
+### Managed assistant skills
+
+With the seeded local web app running, import the checked-in assistant catalog:
+
+```bash
+pnpm run seed -- assistant-skills
+```
+
+This writes `SKILL.md` files through `/api/public/skills` using the synthetic
+seed API key, adds the `in-app-agent` tag, and labels each imported version
+`production`. Re-running reuses unchanged versions. Names match the bundled
+skills, so `--seed` and `--id-prefix` do not create independent copies. The
+scenario verifies the production contents through the API and prints UI links.
+Use `--dry-run` to inspect the catalog without writing, or `--tag <tag>` to
+select a different catalog tag.
+
+For a distinct end-to-end check, run `pnpm run seed -- assistant-skills --demo`.
+It also creates an instructions-only `local-assistant-check` skill. Open the
+seeded project, open the assistant, start a new chat and send:
+"Run the local assistant check skill." The expected response is exactly
+"Hosted skills are connected." Open Skills β†’ local-assistant-check to inspect
+its `SKILL.md` instructions.
+
+To use these skills in the local assistant, set the following worker environment
+and restart the worker:
+
+```dotenv
+LANGFUSE_AI_FEATURES_HOST=http://localhost:3000
+LANGFUSE_AI_FEATURES_PUBLIC_KEY=pk-lf-1234567890
+LANGFUSE_AI_FEATURES_SECRET_KEY=sk-lf-1234567890
+LANGFUSE_IN_APP_AGENT_SKILLS_TAG=in-app-agent
+```
+
+The keys above are the public synthetic development fixtures. The assistant
+merges tagged production versions from this project with the bundled catalog;
+remote skills take precedence on an exact name match. Edit an imported skill
+in Skills, create a version and assign `production`, then start a new assistant
+run to use it. Leaving the tag setting unset keeps the bundled catalog.
+If managed loading fails, the worker logs a warning and uses the complete
+bundled catalog for that run.
+
### Experiment filter fixture
`NEXTAUTH_URL=http://localhost:3010 pnpm run seed -- experiment-filters --id-prefix experiment-targets`
diff --git a/packages/shared/scripts/seeder/scenarios/assistant-skills.ts b/packages/shared/scripts/seeder/scenarios/assistant-skills.ts
new file mode 100644
index 0000000000..f5b706560c
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/assistant-skills.ts
@@ -0,0 +1,219 @@
+import { createHash } from "node:crypto";
+import { createRequire } from "node:module";
+import { resolve } from "node:path";
+import { z } from "zod";
+import {
+ SkillDescriptionSchema,
+ SkillNameSchema,
+ SkillTagsSchema,
+ SkillVersionSchema,
+} from "../../../src/features/skills/types";
+import { DEFAULT_SEED_API_KEY } from "../utils/postgres-seed-constants";
+import {
+ type ScenarioContext,
+ type ScenarioDefinition,
+ SeedError,
+ type SeedSummary,
+} from "./types";
+
+const BundledSkillsSchema = z.object({
+ LANGFUSE_SKILLS: z.array(
+ z.object({
+ name: SkillNameSchema,
+ description: SkillDescriptionSchema,
+ instructions: z.string().min(1),
+ }),
+ ),
+});
+
+const SkillWithContentSchema = SkillVersionSchema.extend({
+ files: z.array(
+ SkillVersionSchema.shape.files.element.extend({
+ content: z.string().optional(),
+ }),
+ ),
+});
+
+const request = async (
+ ctx: ScenarioContext,
+ path: string,
+ init?: RequestInit,
+): Promise<Response> => {
+ const response = await fetch(`${ctx.baseUrl}/api/public${path}`, {
+ ...init,
+ headers: {
+ Authorization: `Basic ${Buffer.from(
+ `${DEFAULT_SEED_API_KEY.public}:${DEFAULT_SEED_API_KEY.secret}`,
+ ).toString("base64")}`,
+ "Content-Type": "application/json",
+ },
+ });
+ if (!response.ok && !(response.status === 404 && !init?.method)) {
+ throw new SeedError(
+ `Skills API ${init?.method ?? "GET"} ${path} returned ${response.status}: ${(await response.text()).slice(0, 500)}`,
+ "target a running seeded local or preview environment with the default synthetic API key",
+ );
+ }
+ return response;
+};
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const tag = SkillTagsSchema.parse([params.tag])[0]!;
+ // This repository-only fixture does not add a runtime dependency to shared.
+ const bundle: unknown = createRequire(__filename)(
+ resolve(__dirname, "../../../../langfuse-skills"),
+ );
+ const definitions = BundledSkillsSchema.parse(bundle).LANGFUSE_SKILLS;
+ if (params.demo === true) {
+ definitions.push({
+ name: "local-assistant-check",
+ description:
+ "Verify hosted assistant skills. Use when asked to run the local assistant check.",
+ instructions: 'Reply with exactly: "Hosted skills are connected."',
+ });
+ }
+ const skills = definitions.map(({ name, description, instructions }) => {
+ const content = `---\nname: ${JSON.stringify(name)}\ndescription: ${JSON.stringify(description)}\n---\n\n${instructions}\n`;
+ return {
+ name,
+ files: [
+ {
+ path: "SKILL.md",
+ content,
+ sha256Hash: createHash("sha256").update(content).digest("base64"),
+ },
+ ],
+ };
+ });
+ const links = skills.map(
+ ({ name }) => `${ctx.baseUrl}/project/${ctx.projectId}/skills/${name}`,
+ );
+ const summary: SeedSummary = {
+ scenario: "assistant-skills",
+ target: "api",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [],
+ sessionIds: [],
+ counts: { skills: skills.length, created: 0 },
+ verified: {},
+ links,
+ dryRun: ctx.dryRun,
+ durationMs: 0,
+ };
+ if (ctx.dryRun) {
+ return { ...summary, durationMs: Date.now() - startedAt };
+ }
+
+ const projects = z
+ .object({ data: z.array(z.object({ id: z.string() })) })
+ .parse(await (await request(ctx, "/projects")).json());
+ if (!projects.data.some(({ id }) => id === ctx.projectId)) {
+ throw new SeedError(
+ "The synthetic API key does not belong to --project",
+ "use the default seeded project (or its matching synthetic API key environment)",
+ );
+ }
+
+ for (const skill of skills) {
+ const path = `/skills/${skill.name}`;
+ const response = await request(ctx, `${path}?label=latest`);
+ let version = response.ok
+ ? SkillVersionSchema.parse(await response.json())
+ : undefined;
+ if (
+ version?.files.length !== skill.files.length ||
+ skill.files.some(
+ (file) =>
+ version?.files.find(({ path }) => path === file.path)?.sha256Hash !==
+ file.sha256Hash,
+ )
+ ) {
+ version = SkillVersionSchema.parse(
+ await (
+ await request(ctx, "/skills", {
+ method: "POST",
+ body: JSON.stringify({
+ files: skill.files.map(({ path, content }) => ({
+ path,
+ content,
+ })),
+ commitMessage: "Import bundled Langfuse assistant skill",
+ }),
+ })
+ ).json(),
+ );
+ summary.counts.created++;
+ }
+ if (!version.tags.includes(tag)) {
+ await request(ctx, path, {
+ method: "PATCH",
+ body: JSON.stringify({ tags: [...version.tags, tag] }),
+ });
+ }
+ if (!version.labels.includes("production")) {
+ await request(ctx, `${path}/versions/${version.version}`, {
+ method: "PATCH",
+ body: JSON.stringify({
+ labels: [
+ ...version.labels.filter((label) => label !== "latest"),
+ "production",
+ ],
+ }),
+ });
+ }
+ const readback = SkillWithContentSchema.parse(
+ await (
+ await request(ctx, `${path}?label=production&includeContent=true`)
+ ).json(),
+ );
+ if (
+ readback.projectId !== ctx.projectId ||
+ readback.version !== version.version ||
+ !readback.tags.includes(tag) ||
+ readback.files.length !== skill.files.length ||
+ skill.files.some(
+ (file) =>
+ readback.files.find(({ path }) => path === file.path)?.content !==
+ file.content,
+ )
+ ) {
+ throw new SeedError(`Readback mismatch for skill ${skill.name}`);
+ }
+ ctx.log(`${skill.name} v${version.version}: production, tag ${tag}`);
+ }
+
+ return {
+ ...summary,
+ verified: { skills: skills.length },
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const assistantSkillsScenario: ScenarioDefinition = {
+ name: "assistant-skills",
+ description:
+ "Import bundled Langfuse assistant skills into skill management through the seeded public API key. Reuses unchanged versions and applies the production label and assistant tag.",
+ supportsV4: false,
+ target: "api",
+ flags: [
+ {
+ flag: "demo",
+ type: "boolean",
+ default: false,
+ description: "include a local check skill with a fixed response",
+ },
+ {
+ flag: "tag",
+ type: "string",
+ default: "in-app-agent",
+ description: "tag used to select the assistant's managed skills",
+ },
+ ],
+ run,
+};
diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.ts
index f79db8056b..2c303d79c8 100644
--- a/packages/shared/scripts/seeder/scenarios/index.ts
+++ b/packages/shared/scripts/seeder/scenarios/index.ts
@@ -1,6 +1,7 @@
import { agentGraphScenario } from "./agent-graph";
import { agentTimelineScenario } from "./agent-timeline";
import { annotationQueueScenario } from "./annotation-queue";
+import { assistantSkillsScenario } from "./assistant-skills";
import { customModelsScenario } from "./custom-models";
import { deepChainScenario } from "./deep-chain";
import { evaluatorGalleryScenario } from "./evaluator-gallery";
@@ -28,6 +29,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {
"trace-tree": traceTreeScenario,
"agent-timeline": agentTimelineScenario,
"agent-graph": agentGraphScenario,
+ "assistant-skills": assistantSkillsScenario,
"deep-chain": deepChainScenario,
"evaluator-gallery": evaluatorGalleryScenario,
"experiment-io": experimentIoScenario,
diff --git a/packages/shared/src/server/llm/internalTraceEvents.ts b/packages/shared/src/server/llm/internalTraceEvents.ts
index 0096715bdb..379169808c 100644
--- a/packages/shared/src/server/llm/internalTraceEvents.ts
+++ b/packages/shared/src/server/llm/internalTraceEvents.ts
@@ -2,6 +2,7 @@ import type {
SkillsAvailableInput,
SkillsResourceLoaded,
} from "../../features/skills/trace";
+import { SkillsAvailableInputSchema } from "../../features/skills/trace";
import {
asBoolean,
asNumberRecord,
@@ -135,6 +136,7 @@ type InternalTraceSnapshot = {
modelParameters?: Record<string, unknown>;
providedUsageDetails?: Record<string, number>;
providedCostDetails?: Record<string, number>;
+ skillsAvailable?: SkillsAvailableInput;
input?: unknown;
output?: unknown;
metadata: Record<string, unknown>;
@@ -235,6 +237,9 @@ function mergeSnapshotEvent(
const timestamp =
asIsoTimestamp(body.timestamp) ?? asIsoTimestamp(event.timestamp);
const metadata = asRecord(body.metadata);
+ const skillsAvailable = SkillsAvailableInputSchema.safeParse(
+ body.skillsAvailable,
+ );
return {
...snapshot,
@@ -266,6 +271,9 @@ function mergeSnapshotEvent(
snapshot.providedUsageDetails,
providedCostDetails:
asNumberRecord(body.costDetails) ?? snapshot.providedCostDetails,
+ skillsAvailable: skillsAvailable.success
+ ? skillsAvailable.data
+ : snapshot.skillsAvailable,
input:
body.input !== undefined && body.input !== null
? body.input
@@ -413,6 +421,7 @@ export function buildInternalTraceEventInputs(params: {
modelParameters: snapshot.modelParameters,
providedUsageDetails: snapshot.providedUsageDetails,
providedCostDetails: snapshot.providedCostDetails,
+ skillsAvailable: snapshot.skillsAvailable,
toolDefinitions: convertDefinitionsToMap(toolDefinitions),
toolCalls: toolCalls.tool_calls,
toolCallNames: toolCalls.tool_call_names,
diff --git a/packages/shared/src/server/otel/internalTraceOtelWriter.ts b/packages/shared/src/server/otel/internalTraceOtelWriter.ts
index c83ea68bd3..b2b5e97386 100644
--- a/packages/shared/src/server/otel/internalTraceOtelWriter.ts
+++ b/packages/shared/src/server/otel/internalTraceOtelWriter.ts
@@ -65,6 +65,7 @@ export function internalTraceEventToOtelAttributes(
| "providedCostDetails"
| "promptName"
| "promptVersion"
+ | "skillsAvailable"
| "completionStartTime"
| "userId"
| "sessionId"
@@ -143,6 +144,12 @@ export function internalTraceEventToOtelAttributes(
eventInput.promptVersion,
}
: {}),
+ ...(eventInput.skillsAvailable !== undefined
+ ? {
+ [LangfuseOtelSpanAttributes.OBSERVATION_SKILLS_AVAILABLE]:
+ JSON.stringify(eventInput.skillsAvailable),
+ }
+ : {}),
...(eventInput.completionStartTime !== undefined
? {
[LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME]:
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 82f90c6212..8bdf3c5ad7 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -409,6 +409,8 @@ const EnvSchema = z.object({
LANGFUSE_IN_APP_AGENT_RETENTION_CLEANER_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ // Opt in to the AI-features project's production skills with this tag.
+ LANGFUSE_IN_APP_AGENT_SKILLS_TAG: z.string().trim().min(1).optional(),
LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER: z
.enum(["dangerous-docker", "lambda-microvm"])
.optional(),
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
index 3f1c1c43de..35a7ba1ea0 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -15,6 +15,7 @@ import {
} from "@langfuse/shared/rbac";
import { ResumeForwardedPropsSchema } from "./runtime/types";
import { env } from "../../env";
+import { LANGFUSE_IN_APP_AGENT_SKILLS } from "./runtime/skills";
const createConversationId = () => `aconv_${randomUUID()}`;
const createRunId = () => `arun_${randomUUID()}`;
@@ -24,6 +25,7 @@ vi.hoisted(() => {
// provider. Keep its provider selection explicit rather than inheriting the
// developer's root .env.
delete process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER;
+ delete process.env.LANGFUSE_IN_APP_AGENT_SKILLS_TAG;
if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {
process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
}
@@ -63,6 +65,7 @@ type AgentScenario = (ctx: {
awsProfile?: string;
langfuseClient?: unknown;
useLocalPrompt: boolean;
+ skills: Array<{ name: string }>;
langfuseMcp: {
toolPolicy: {
available: ReadonlySet<string>;
@@ -358,6 +361,19 @@ describe("executeInAppAgentRun", () => {
observabilityRef.traceException.mockClear();
});
+ it("passes bundled skills from the loader when no managed tag is configured", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+ let selectedSkills: unknown;
+ scenarioRef.current = async (params) => {
+ selectedSkills = params.options.skills;
+ await completingScenario(params);
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ expect(selectedSkills).toBe(LANGFUSE_IN_APP_AGENT_SKILLS);
+ });
+
it("does not regenerate the conversation title after executing a user-message run", async () => {
const { projectId, run } = await seedBackgroundRun();
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index 1d2dfb3e66..6d82a03053 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -70,6 +70,8 @@ import {
import { createInAppAgentSandbox } from "./runtime/sandbox";
import { createAgUiStream } from "./runtime/agent";
import { getInAppAgentPromptClient } from "./runtime/promptClient";
+import { loadInAppAgentSkills } from "./runtime/skills";
+import { env as sharedEnv } from "@langfuse/shared/src/env";
import { resolveLangfuseMcpUrl } from "./resolveLangfuseMcpUrl";
import type { AgUiRunAgentInput } from "./runtime/types";
@@ -620,6 +622,7 @@ export async function executeInAppAgentRun(params: {
isV4Enabled: access.v4BetaEnabled,
},
useLocalPrompt: useBundledPrompt,
+ ...(await loadSkills(abortController.signal)),
...(useBundledPrompt
? {}
: { langfuseClient: getInAppAgentPromptClient() }),
@@ -680,6 +683,16 @@ export async function executeInAppAgentRun(params: {
}
}
+async function loadSkills(signal: AbortSignal) {
+ return loadInAppAgentSkills({
+ tag: env.LANGFUSE_IN_APP_AGENT_SKILLS_TAG,
+ baseUrl: sharedEnv.LANGFUSE_AI_FEATURES_HOST,
+ publicKey: sharedEnv.LANGFUSE_AI_FEATURES_PUBLIC_KEY,
+ secretKey: sharedEnv.LANGFUSE_AI_FEATURES_SECRET_KEY,
+ signal,
+ });
+}
+
async function resolveUserProjectAccess(params: {
userId: string;
projectId: string;
diff --git a/worker/src/features/in-app-agent/runtime/agent.test.ts b/worker/src/features/in-app-agent/runtime/agent.test.ts
index 8bf1f1c1bc..0a60dcac55 100644
--- a/worker/src/features/in-app-agent/runtime/agent.test.ts
+++ b/worker/src/features/in-app-agent/runtime/agent.test.ts
@@ -1,6 +1,7 @@
import { EventType } from "@ag-ui/core";
import { MastraAgent } from "@ag-ui/mastra";
import { Agent } from "@mastra/core/agent";
+import { createSkill } from "@mastra/core/skills";
import { MCPClient } from "@mastra/mcp";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -14,6 +15,7 @@ import {
import { createInAppAgentToolPolicy } from "@langfuse/shared/in-app-agent/server/mcpPolicy";
import { IN_APP_AGENT_MAX_STEPS } from "@langfuse/shared/in-app-agent/server/tunables";
import { patchMastraApprovalChunks, type createAgUiStream } from "./agent";
+import { loadInAppAgentSkills } from "./skills";
import {
createInAppAgentSandbox,
type SandboxProvider,
@@ -160,6 +162,7 @@ const instrumentationMocks = vi.hoisted(() => {
const instrumentation = {
recordEvents: vi.fn(),
recordAvailableTools: vi.fn(),
+ recordAvailableSkills: vi.fn(),
recordToolCallApproval: vi.fn(),
recordToolExecutionStart: vi.fn(),
recordToolExecutionEnd: vi.fn(),
@@ -588,6 +591,7 @@ describe("createAgUiStream", () => {
model = testBedrockModel("test-model"),
onComplete?: (outcome?: unknown) => void,
context: Array<{ description: string; value: string }> = [],
+ skills: ReturnType<typeof createSkill>[] = [],
) => {
const { createAgUiStream } = await import("./agent");
const input = {
@@ -635,6 +639,7 @@ describe("createAgUiStream", () => {
getPrompt: promptMocks.getPrompt,
} as unknown as Langfuse,
useLocalPrompt: false,
+ skills,
langfuseTracing: createTestTracingConfig(),
},
});
@@ -652,6 +657,29 @@ describe("createAgUiStream", () => {
};
};
+ it("uses the supplied managed skills for Mastra and tracing", async () => {
+ const skills = [
+ createSkill({
+ name: "local-guide",
+ description: "Local published guide",
+ instructions: "Follow the local guide.",
+ }),
+ ];
+
+ await initializeBasicTracedAgent(
+ "managed-skills-run",
+ undefined,
+ undefined,
+ [],
+ skills,
+ );
+
+ expect(vi.mocked(Agent).mock.calls.at(-1)?.[0].skills).toBe(skills);
+ expect(
+ instrumentationMocks.instrumentation.recordAvailableSkills,
+ ).toHaveBeenCalledWith(skills);
+ });
+
it("uses the shared Bedrock default-credential auth", async () => {
const { createAmazonBedrock } = await import("ai-sdk-amazon-bedrock-v4");
@@ -1301,6 +1329,7 @@ describe("createAgUiStream", () => {
sandbox: sandboxState.sandbox,
onFinish: sandboxState.onTurnEnded,
useLocalPrompt: false,
+ skills: (await loadInAppAgentSkills({})).skills,
langfuseTracing: createTestTracingConfig(),
},
});
@@ -1613,6 +1642,7 @@ describe("createAgUiStream", () => {
getPrompt: promptMocks.getPrompt,
} as unknown as Langfuse,
useLocalPrompt: false,
+ skills: [],
langfuseTracing: createTestTracingConfig(),
},
});
@@ -1685,6 +1715,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
},
});
@@ -1755,6 +1786,7 @@ describe("createAgUiStream", () => {
sandbox: sandboxState.sandbox,
sandboxWorkspaceWasReset: sandboxState.workspaceWasReset,
useLocalPrompt: false,
+ skills: [],
},
});
@@ -1856,6 +1888,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
},
});
@@ -1925,6 +1958,7 @@ describe("createAgUiStream", () => {
redirectAction: { projectId: "project-1", isV4Enabled: false },
langfuseClient,
useLocalPrompt: false,
+ skills: [],
},
});
@@ -1989,6 +2023,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
langfuseTracing: createTestTracingConfig(),
},
});
@@ -2283,6 +2318,7 @@ describe("createAgUiStream", () => {
langfuseClient,
sandbox: (await createTestSandbox()).sandbox,
useLocalPrompt: false,
+ skills: [],
},
});
const streamedText = await readStream(stream);
@@ -2364,6 +2400,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
langfuseTracing: createTestTracingConfig(),
},
});
@@ -2528,6 +2565,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
},
});
await readStream(stream);
@@ -2612,6 +2650,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
langfuseTracing: createTestTracingConfig(),
},
});
@@ -2778,6 +2817,7 @@ describe("createAgUiStream", () => {
},
langfuseClient,
useLocalPrompt: false,
+ skills: [],
},
});
await readStream(stream);
@@ -2867,6 +2907,7 @@ describe("createAgUiStream", () => {
getPrompt: promptMocks.getPrompt,
} as unknown as Langfuse,
useLocalPrompt: false,
+ skills: [],
},
});
diff --git a/worker/src/features/in-app-agent/runtime/agent.ts b/worker/src/features/in-app-agent/runtime/agent.ts
index ed729e3750..b99b5ae2df 100644
--- a/worker/src/features/in-app-agent/runtime/agent.ts
+++ b/worker/src/features/in-app-agent/runtime/agent.ts
@@ -2,6 +2,7 @@ import { EventType } from "@ag-ui/core";
import { MastraAgent } from "@ag-ui/mastra";
import { IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE } from "@langfuse/shared/in-app-agent/server/systemPrompt";
import { Agent } from "@mastra/core/agent";
+import type { InlineSkill } from "@mastra/core/skills";
import { RequestContext } from "@mastra/core/request-context";
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
@@ -54,7 +55,6 @@ import {
withInAppAgentToolApproval,
withInAppAgentToolApprovalSidecars,
} from "@langfuse/shared/in-app-agent/server/mcpPolicy";
-import { LANGFUSE_IN_APP_AGENT_SKILLS } from "./skills";
import type { InAppAgentSandbox } from "./sandbox";
import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
@@ -265,6 +265,7 @@ type CreateAgUiStreamOptions = {
};
langfuseClient?: Langfuse;
useLocalPrompt: boolean;
+ skills: InlineSkill[];
langfuseTracing?: InAppAgentTracingConfig;
sandbox?: InAppAgentSandbox;
/** Adds a run instruction telling the model its earlier workspace files are gone. */
@@ -278,6 +279,7 @@ export async function createAgUiStream(params: {
}) {
const encoder = new TextEncoder();
const awsProfile = params.options.awsProfile;
+ const skills = params.options.skills;
const runContext = formatRunContext(params.input.context);
const langfuseMcpAuthHeader = `Basic ${Buffer.from(
@@ -336,7 +338,7 @@ export async function createAgUiStream(params: {
}
};
recordInstrumentation("recordAvailableSkills", (instrumentation) =>
- instrumentation.recordAvailableSkills?.(LANGFUSE_IN_APP_AGENT_SKILLS),
+ instrumentation.recordAvailableSkills?.(skills),
);
const stepLimitState: StepLimitState = {
iteration: 0,
@@ -636,6 +638,7 @@ export async function createAgUiStream(params: {
options: params.options,
awsProfile,
instructions,
+ skills,
onToolsAvailable: (tools) =>
recordInstrumentation("recordAvailableTools", (instrumentation) =>
instrumentation.recordAvailableTools?.(tools),
@@ -717,6 +720,7 @@ export async function createAgUiStream(params: {
},
awsProfile,
instructions,
+ skills,
onModelCallStart,
onModelStreamPart,
onToolExecutionStart,
@@ -1083,6 +1087,7 @@ async function createMastraAdapter(params: {
options: CreateAgUiStreamOptions;
awsProfile?: string;
instructions: string;
+ skills: InlineSkill[];
onToolsAvailable?: (tools: Record<string, unknown>) => void;
onModelCallStart?: (options: unknown) => void;
onModelStreamPart?: (part: unknown) => void;
@@ -1244,7 +1249,7 @@ async function createMastraAdapter(params: {
.filter(Boolean)
.join("\n\n"),
model,
- skills: LANGFUSE_IN_APP_AGENT_SKILLS,
+ skills: params.skills,
tools,
maxRetries: 2,
inputProcessors: [
diff --git a/worker/src/features/in-app-agent/runtime/instrumentation.ts b/worker/src/features/in-app-agent/runtime/instrumentation.ts
index 28e2ab126b..bbf8b1232e 100644
--- a/worker/src/features/in-app-agent/runtime/instrumentation.ts
+++ b/worker/src/features/in-app-agent/runtime/instrumentation.ts
@@ -19,7 +19,11 @@ import {
import { ResumeForwardedPropsSchema, type AgUiRunAgentInput } from "./types";
import { compactTextMessageChunks } from "@langfuse/shared/in-app-agent/server/eventCompaction";
import type { InAppAgentUserAccess } from "@langfuse/shared/in-app-agent/server/mcpPolicy";
-import { assertUnreachable } from "@langfuse/shared";
+import {
+ assertUnreachable,
+ SkillsAvailableInputSchema,
+ type SkillsAvailableInput,
+} from "@langfuse/shared";
export type InAppAgentTracingConfig = {
environment: string;
@@ -106,6 +110,7 @@ type ObservationBody = {
promptVersion?: number;
userId?: string;
sessionId?: string;
+ skillsAvailable?: SkillsAvailableInput;
};
type ToolCallApprovalStatus = "approved" | "rejected";
type AgentRunToolSpan = {
@@ -207,6 +212,8 @@ export class InAppAgentInstrumentation {
private openModelObservationId?: string;
private lastModelObservationId?: string;
private readonly metadata: Record<string, unknown>;
+ private readonly targetProjectId: string;
+ private skillsAvailable: SkillsAvailableInput = [];
private readonly agentRunOutputMessages: AgentRunChatMessage[] = [];
private readonly agentRunToolCalls: AgentRunToolCall[] = [];
private output = "";
@@ -254,6 +261,7 @@ export class InAppAgentInstrumentation {
this.agentRunInput = getAgentRunInput(params.input);
this.wrappingRootInput = getWrappingRootUserText(params.input);
this.prompt = params.prompt;
+ this.targetProjectId = params.targetProjectId;
this.model = params.model;
this.runId = params.runId;
this.userId = params.userId;
@@ -446,6 +454,23 @@ export class InAppAgentInstrumentation {
return;
}
+ const catalogue = SkillsAvailableInputSchema.safeParse(
+ skills.flatMap((skill) => {
+ if (!isRecord(skill)) return [];
+ const metadata = isRecord(skill.metadata) ? skill.metadata : {};
+ const reference = SkillsAvailableInputSchema.element.safeParse({
+ name: skill.name,
+ // Foreign-project skills remain visible without resolving to a local version.
+ version:
+ metadata.langfuseProjectId === this.targetProjectId
+ ? metadata.langfuseSkillVersion
+ : undefined,
+ });
+ return reference.success ? [reference.data] : [];
+ }),
+ );
+ this.skillsAvailable = catalogue.success ? catalogue.data : [];
+
const availableSkills = getAgentRunAvailableSkills(skills);
if (availableSkills.length === 0) {
@@ -919,6 +944,10 @@ export class InAppAgentInstrumentation {
}
).enqueue(type, {
...body,
+ ...((type === "generation-create" || type === "tool-create") &&
+ this.skillsAvailable.length > 0
+ ? { skillsAvailable: this.skillsAvailable }
+ : {}),
userId: this.userId,
sessionId: this.sessionId,
metadata: { ...this.metadata, ...body.metadata },
diff --git a/worker/src/features/in-app-agent/runtime/skills.ts b/worker/src/features/in-app-agent/runtime/skills.ts
index d611025ad6..fca245c421 100644
--- a/worker/src/features/in-app-agent/runtime/skills.ts
+++ b/worker/src/features/in-app-agent/runtime/skills.ts
@@ -1,7 +1,158 @@
import { createSkill } from "@mastra/core/skills";
+import pLimit from "p-limit";
+import { z } from "zod/v4";
+import { ListSkillsResponseSchema, SkillVersionSchema } from "@langfuse/shared";
+import { getProductBaseUrl, logger } from "@langfuse/shared/src/server";
import { LANGFUSE_SKILLS } from "@repo/langfuse-skills";
export const LANGFUSE_IN_APP_AGENT_SKILLS = LANGFUSE_SKILLS.map((skill) =>
createSkill(skill),
);
+
+const skillWithContentsSchema = SkillVersionSchema.extend({
+ files: z.array(
+ SkillVersionSchema.shape.files.element.extend({ content: z.string() }),
+ ),
+});
+
+type SkillsConfig = {
+ tag?: string;
+ baseUrl?: string;
+ publicKey?: string;
+ secretKey?: string;
+ signal?: AbortSignal;
+};
+
+/** Merge hosted instructions into bundled skills, with hosted names taking precedence. */
+export async function loadInAppAgentSkills(config: SkillsConfig): Promise<{
+ skills: typeof LANGFUSE_IN_APP_AGENT_SKILLS;
+}> {
+ if (!config.tag) return { skills: LANGFUSE_IN_APP_AGENT_SKILLS };
+
+ const controller = new AbortController();
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ timeout = setTimeout(
+ () => controller.abort(new Error("Managed assistant skills timed out")),
+ 5_000,
+ );
+ const signal = config.signal
+ ? AbortSignal.any([config.signal, controller.signal])
+ : controller.signal;
+ const { skills: managedSkills } = await loadManagedCatalogue(
+ { ...config, signal },
+ config.tag,
+ );
+ signal.throwIfAborted();
+ return {
+ skills: [
+ ...new Map(
+ [...LANGFUSE_IN_APP_AGENT_SKILLS, ...managedSkills].map((skill) => [
+ skill.name,
+ skill,
+ ]),
+ ).values(),
+ ],
+ };
+ } catch (error) {
+ logger.warn(
+ "Failed to load managed assistant skills; using bundled skills",
+ {
+ error: error instanceof Error ? error.message : "Unknown error",
+ },
+ );
+ return { skills: LANGFUSE_IN_APP_AGENT_SKILLS };
+ } finally {
+ clearTimeout(timeout);
+ controller.abort();
+ }
+}
+
+async function loadManagedCatalogue(config: SkillsConfig, tag: string) {
+ if (!config.publicKey || !config.secretKey) {
+ throw new Error(
+ "Managed assistant skills require AI-features project credentials",
+ );
+ }
+
+ const host = config.baseUrl ?? getProductBaseUrl().toString();
+ const baseUrl = new URL(`${host.replace(/\/+$/, "")}/api/public/skills`);
+ const headers = {
+ Authorization: `Basic ${Buffer.from(`${config.publicKey}:${config.secretKey}`).toString("base64")}`,
+ };
+ const read = async (url: URL): Promise<unknown> => {
+ config.signal?.throwIfAborted();
+ const response = await fetch(url, {
+ headers,
+ // A configured host must not forward project credentials to a redirect target.
+ redirect: "error",
+ signal: config.signal,
+ });
+ if (!response.ok) {
+ throw new Error(
+ `Could not load managed assistant skills (HTTP ${response.status})`,
+ );
+ }
+ return response.json();
+ };
+
+ const limit = pLimit(5);
+ let skills: ReturnType<typeof createSkill>[] = [];
+ for (let page = 1; ; page++) {
+ const listUrl = new URL(baseUrl);
+ listUrl.search = new URLSearchParams({
+ tag,
+ page: String(page),
+ limit: "100",
+ }).toString();
+ const catalogue = ListSkillsResponseSchema.parse(await read(listUrl));
+ const batch = await Promise.all(
+ catalogue.data
+ .filter((entry) => entry.productionVersion !== null)
+ .map((entry) =>
+ limit(async () => {
+ const url = new URL(baseUrl);
+ url.pathname += `/${encodeURIComponent(entry.name)}`;
+ url.search = new URLSearchParams({
+ version: String(entry.productionVersion),
+ includeContent: "true",
+ }).toString();
+ const version = skillWithContentsSchema.parse(await read(url));
+ if (
+ version.name !== entry.name ||
+ version.version !== entry.productionVersion
+ ) {
+ throw new Error(
+ "Managed assistant skill did not match its selected version",
+ );
+ }
+ const skillMd = version.files.find(
+ (file) => file.path === "SKILL.md",
+ );
+ const frontmatter = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.exec(
+ skillMd?.content ?? "",
+ );
+ if (!skillMd || !frontmatter) {
+ throw new Error(
+ `Managed assistant skill ${entry.name} is missing a valid SKILL.md`,
+ );
+ }
+ return createSkill({
+ name: version.name,
+ description: version.description,
+ instructions: skillMd.content.slice(frontmatter[0].length),
+ metadata: {
+ langfuseProjectId: version.projectId,
+ langfuseSkillId: version.id,
+ langfuseSkillVersion: version.version,
+ },
+ });
+ }),
+ ),
+ );
+ skills = skills.concat(batch);
+ if (!catalogue.meta.hasNextPage) break;
+ }
+ return { skills };
+}