> ## Documentation Index
> Fetch the complete documentation index at: https://docs.langchain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Dream over traces

> Schedule an agent to review a person's traces each night and update their memory.

Dreaming is a scheduled review of an agent's past work. In this example, a nightly schedule runs as each opted-in user, reads their recent traces, and updates their user memory.

> [!NOTE]
>
> Managed Deep Agents is in **public [beta](https://docs.langchain.com/langsmith/release-stages.md)** on [LangSmith Cloud](https://docs.langchain.com/langsmith/cloud.md) and [Bring Your Own Cloud (BYOC)](https://docs.langchain.com/langsmith/byoc.md). Use Managed Deep Agents CLI and SDK v0.10 or later for BYOC.

> [!NOTE]
>
> This TypeScript example requires `managed-deepagents` version 0.10.4 or later, the matching `mda` CLI, and `langsmith` version 0.11.7 or later. Self-hosted LangSmith must be v0.16 or later.

![Mock private assistant chat alongside memory files showing an approved nightly dreaming schedule running at 03:00 UTC, updating /memories/user/AGENTS.md, and writing a skill proposal to dreaming-proposals.md.](https://mintcdn.com/langchain-5e9cc07a/bdTAbHGS6Uo5z-4d/langsmith/images/managed-deep-agents-dreaming-light.png?fit=max\&auto=format\&n=bdTAbHGS6Uo5z-4d\&q=85\&s=a34b5ef5b2eaf0f3ec29cae9d77455b9)

## Before you start

* Configure [identity](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-identity.md) so each person signs in as themselves. User memory and per-user trace lookups require a signed-in person.
* Route each person's traces to their own LangSmith tracing project.
* Add `DREAM_TRACE_PROJECTS` to `.env` wrapped in single quotes so `mda deploy` preserves the JSON double quotes. Map MDA principal IDs to project IDs, and ensure the deployment's LangSmith credentials have read access to those projects:

```text .env theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
DREAM_TRACE_PROJECTS='{"<principal-id>": "<project-id>"}'
```

## Add personal memory

Declare [user memory](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-memory.md) at the project root:

```ts memory.ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { defineMemory, memoryLayer } from "managed-deepagents";

export const memory = defineMemory({ user: memoryLayer() });
```

Scheduled runs have no channel event, so select user memory in the agent factory when a run has no channel origin (such as scheduled runs and Studio). Omitting `memory` on channel runs keeps MDA's default access rules, which mount user memory in Slack direct messages and keep it off in shared channels. Requiring an interrupt on `schedule_dreaming` prompts for approval before creating a schedule:

```ts agent.ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import {
  defineDeepAgent,
  defineMemory,
  memoryLayer,
  type ManagedServerRuntime,
} from "managed-deepagents";

import { recentUserTraces, scheduleDreaming } from "./tools/dreaming";

export function agent(runtime: ManagedServerRuntime) {
  return defineDeepAgent({
    name: "private-assistant",
    model: "openai:gpt-6.1-sol",
    tools: [recentUserTraces, scheduleDreaming],
    memory: runtime.thread?.origin ? undefined : defineMemory({ user: memoryLayer() }),
    interruptOn: { schedule_dreaming: true },
  });
}
```

MDA always mounts the signed-in person's memory, so a prompt cannot read someone else's.

## Add the tools

`recent_user_traces` reads up to 25 of the current person's traces from the last day. `schedule_dreaming` creates a nightly schedule that runs as that person.

With `managed-deepagents` 0.10.4, use npm: pnpm can resolve incompatible LangChain versions. Install the tools' dependencies and the model provider package (factory definitions do not auto-install provider packages):

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
npm install langchain zod langsmith @langchain/openai
```

```ts tools/dreaming.ts expandable theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { tool } from "langchain";
import { Client } from "langsmith";
import type { ManagedDeepAgentRuntime } from "managed-deepagents";
import { z } from "zod";

type DreamRuntime = Pick<ManagedDeepAgentRuntime, "serverInfo" | "thread" | "schedules">;

const DREAM_PROMPT = `Read your recent traces with recent_user_traces. Save useful
preferences and recurring context to /memories/user/AGENTS.md, without secrets.
Write ideas for improving your instructions or skills to
/memories/user/dreaming-proposals.md.`;

function traceProject(runtime: DreamRuntime): string | undefined {
  const principal = runtime.serverInfo?.principal;
  if (principal?.kind !== "person") return undefined;
  return JSON.parse(process.env.DREAM_TRACE_PROJECTS ?? "{}")[principal.id];
}

export const recentUserTraces = tool(
  async (_input, runtime) => {
    const managed = runtime as typeof runtime & DreamRuntime;
    if (managed.thread?.origin) return "Ask outside Slack or other channels, including DMs.";
    const project = traceProject(managed);
    if (!project) return "No trace project for this person.";
    const records: string[] = [];
    for await (const run of new Client().runs.query({
      project_ids: [project],
      min_start_time: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
      is_root: true,
      selects: ["INPUTS", "OUTPUTS"],
      page_size: 25,
    })) {
      records.push(JSON.stringify([run.inputs, run.outputs]).slice(0, 6000));
      if (records.length === 25) break;
    }
    return records.join("\n") || "No recent traces.";
  },
  {
    name: "recent_user_traces",
    description: "Read the current person's traces from the last day.",
    schema: z.object({}),
  },
);

export const scheduleDreaming = tool(
  async (_input, runtime) => {
    const managed = runtime as typeof runtime & DreamRuntime;
    if (managed.thread?.origin) return "Ask outside Slack or other channels, including DMs.";
    if (!traceProject(managed)) return "No trace project for this person.";
    const item = await managed.schedules!.create({
      owner: { type: "user" },
      cron: "0 3 * * *",
      timezone: "UTC",
      prompt: DREAM_PROMPT,
    });
    return `Created nightly dreaming schedule ${item.id}.`;
  },
  {
    name: "schedule_dreaming",
    description: "Schedule a nightly trace review for the current person.",
    schema: z.object({}),
  },
);
```

Trace contents reach the model, so configure [trace masking](https://docs.langchain.com/langsmith/mask-inputs-outputs.md) for anything it should not see.

## Start dreaming

[Deploy the agent](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-deploy.md), sign in, and ask it to schedule nightly dreaming from a direct conversation outside channels (such as LangSmith Studio or your own signed-in app, not Slack DMs). Approve the `schedule_dreaming` call. Each night at 03:00 UTC, the agent reviews your traces and updates `/memories/user/AGENTS.md`.

Deployed instructions and skills are read-only at runtime. To apply an idea from `/memories/user/dreaming-proposals.md`, edit `instructions.md` or the skill in your project and redeploy. To stop dreaming, [delete the schedule](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-schedules.md#manage-schedules).

## Extend the pattern

* Review a week of traces instead of a day by changing the cron and the query window.
* Test proposed instruction changes with [evals](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-evals.md) before deploying.
* Add a [skill](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-skills.md) defining what is worth remembering so reviews stay consistent.

## See also

* [Schedules](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-schedules.md): manage recurring user-owned runs.
* [Memory](https://docs.langchain.com/langsmith/javascript/managed-deep-agents-memory.md): configure durable memory and access policies.
* [Export traces](https://docs.langchain.com/langsmith/export-traces.md): query and paginate trace data.

***

[Connect these docs](https://docs.langchain.com/use-these-docs.md) to your agent of choice via MCP for real-time answers.

[Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/managed-deep-agents-dreaming.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
