Blog/Reading the web, and agents
25 min read

How to Build an Always-On Personal AI Agent: The Full Guide

Grok Bot, Instinct, Poke and OpenClaw share one stack. Build yours: agent loop, sub-agents, iMessage and Slack, browser, tools, memory and dreaming.

How to Build an Always-On Personal AI Agent: The Full Guide

Personal agents like Grok Bot, Instinct, Poke and OpenClaw feel like magic, but under the hood they’re built from the same handful of parts. This guide walks through each part from the video, shows you which service to use for it, and gives you code you can paste. At the end there’s a Claude skill that teaches Claude Code to scaffold the whole thing for you.

What you’ll build

An agent that:

  • chats in a web app and over iMessage, Slack, Telegram or WhatsApp
  • plans with a smart model and hands grunt work to cheaper sub-agents
  • has its own cloud browser and its own sandboxed terminal, so it keeps working when your laptop is shut
  • finds and pays for the data tools it needs on its own
  • remembers you through plain Markdown files, and cleans those memories up every night (“dreaming”)
  • messages you first when something needs attention

1. The mental model: model + harness

Every personal agent is a model wrapped in a harness. The model is the brain you rent (Claude, GPT, Grok). The harness is everything you build around it:

  • Agent loop: the code that lets the model think, call tools, read results and keep going.
  • Context: what goes into the prompt each turn (instructions, memories, chat history, tool results).
  • Tools: browser, terminal, email, data APIs.
  • Memory: what the agent keeps between conversations.

Every AI agent has its own harness: context, tools, memory and the agent loop around a model
Every AI agent has its own harness: context, tools, memory and the agent loop around a model

Two products on the same model can feel completely different because their harnesses are different. That’s the part you’re building.

2. The agent loop

Context windows, and why the harness exists

Every model has a context window: the maximum amount of text it can read in one call. Today’s frontier Claude models take 1M tokens (Anthropic models overview). But bigger isn’t free. Chroma tested 18 models and found that performance gets less reliable as input length grows, even on simple tasks where difficulty is held constant (Chroma, “Context Rot”).

Every model has a context window; near the upper limit, accuracy and instruction following go down
Every model has a context window; near the upper limit, accuracy and instruction following go down

So a good harness spends context carefully: it loads only the memories that matter, trims tool output, and pushes big jobs into sub-agents with their own fresh context (section 3).

The loop itself

Chatbots answer once. Agents loop. Each turn, the agent gets its memories, the prompt and its tools. It then alternates between thinking, calling tools and responding until the model stops asking for tools. That’s the “stop” you see in the diagram.

The agent loop in Python: load memories and prompt, call the model with tools, run tool calls, repeat until no more tool calls
The agent loop in Python: load memories and prompt, call the model with tools, run tool calls, repeat until no more tool calls

The agent loop as a cycle: think, tool call, result, back to think; respond and stop when there are no tool calls
The agent loop as a cycle: think, tool call, result, back to think; respond and stop when there are no tool calls

Here’s the same loop in plain Python, with a stand-in llm() function so you can see every moving part:

def run_agent(user_message):
    messages = [
        {"role": "system", "content": load_memories() + SYSTEM_PROMPT},
        {"role": "user", "content": user_message},
    ]
    while True:
        reply = llm(messages, tools=TOOLS)        # think
        messages.append(reply)
        if not reply.tool_calls:                  # no tool calls = done
            return reply.content                  # respond
        for call in reply.tool_calls:             # act
            result = TOOLS[call.name](**call.args)
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})

You rarely need to write this by hand. The Vercel AI SDK ships it as ToolLoopAgent. The loop ends when the model finishes without tool calls, a tool needs approval, or a stop condition hits. The default stop condition is 20 steps (AI SDK loop control).

// lib/agent.ts
import { ToolLoopAgent, isStepCount } from 'ai';
import { buildTools } from './tools';

export function createAgent(userId: string, memoryContext: string) {
  return new ToolLoopAgent({
    model: 'anthropic/claude-opus-5.5',     // via Vercel AI Gateway
    instructions: `${memoryContext}\n\nYou are this user's personal agent. ...`,
    tools: buildTools(userId),               // per-user tools (memory, email...)
    stopWhen: isStepCount(40),               // a budget, not a target
  });
}

3. Orchestrator and executors

The most common harness pattern is orchestrator-executor (Anthropic calls it orchestrator-worker). One smart model reads the request, makes a plan and delegates each piece to a sub-agent. Each sub-agent works in its own context window and hands back only a short summary.

Orchestrator-executor: a user request goes to the orchestrator, which delegates to research, browser, code and email sub-agents and gets results back
Orchestrator-executor: a user request goes to the orchestrator, which delegates to research, browser, code and email sub-agents and gets results back

Why it works:

  • Clean context. A sub-agent can burn through hundreds of thousands of tokens and return a 1,000-token summary, so the orchestrator stays sharp (AI SDK subagents).
  • Parallelism. Anthropic’s research system uses a lead agent that spawns parallel sub-agents. In their internal eval, Opus 4 leading Sonnet 4 sub-agents beat a single Opus 4 agent by 90.2% (Anthropic, multi-agent research system).
  • Cost. The orchestrator can be a frontier model while executors run on cheaper ones.

Grok Bot users do this at the product level. xAI’s design post says some users made a “Chief of Staff Bot responsible for coordinating several specialists” (xAI, Designing Grok Bot).

Picking models (Claude prices, December 2026)

RoleModelInput / output per 1M tokens
OrchestratorClaude Opus 5.5$4 / $20
ExecutorsClaude Sonnet 5.5$2 / $10
Background jobs (memory, dreaming, routing)Claude Haiku 5.5from $0.10 / $0.50

Source: Anthropic pricing. Haiku 5.5’s price rises above 100K-token prompts, so keep background jobs small.

Sub-agents in code

A sub-agent is just another agent that the orchestrator calls through a tool. Use toModelOutput to control what the orchestrator sees:

// lib/subagents.ts
import { ToolLoopAgent, tool, isStepCount } from 'ai';
import { z } from 'zod';
import { browseWeb } from './tools/browser';
import { monidTools } from './tools/monid';

const researcher = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5',
  instructions: `You are a research executor. Use your tools, then finish with
a summary under 200 words: what you found, sources, and anything unresolved.`,
  tools: { browseWeb, ...monidTools },
  stopWhen: isStepCount(30),
});

export const research = tool({
  description: 'Delegate a research task. Returns a short summary.',
  inputSchema: z.object({ task: z.string() }),
  execute: async ({ task }, { abortSignal }) => {
    const result = await researcher.generate({ prompt: task, abortSignal });
    return result.text;
  },
  toModelOutput: ({ output }) => ({ type: 'text', value: output }),
});

Make one executor per kind of work (research, browser, code, email) and give each only the tools it needs.

4. The interface: chat and generative UI

Chat UIs are a solved problem, so don’t build one from scratch.

  • Vercel Chatbot template: a free, open-source Next.js app on the AI SDK with streaming, generative UI, auth, saved chat history and model routing through AI Gateway (Vercel blog).
  • CopilotKit: a frontend + runtime that talks to any agent backend over the open AG-UI protocol, and renders generative UI specs such as A2UI and MCP Apps.

Generative UI

Generative UI means the agent answers with a component instead of a paragraph. When Grok Bot drafts an email, you get an email card with a Send button. xAI says early versions “responded to almost every request with prose”, so they built inline cards and widgets (xAI).

Generative UI: the agent writes JSON, the app renders it as an email card, and clicking Send calls the send_email tool
Generative UI: the agent writes JSON, the app renders it as an email card, and clicking Send calls the send_email tool

The mechanics are simple: the agent calls a tool, the tool returns data, and your app maps that tool’s output to a React component (AI SDK generative UI).

// lib/tools/email.ts
import { tool } from 'ai';
import { z } from 'zod';

export const draftEmail = tool({
  description: 'Draft an email for the user to review. Never sends.',
  inputSchema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
  execute: async (draft) => draft,   // the draft itself is the UI payload
});

export const sendEmail = tool({
  description: 'Send an email the user has approved.',
  inputSchema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
  execute: async (email) => gmail.send(email),   // your email provider
});
// components/message.tsx (inside your useChat render)
{message.parts.map((part, i) => {
  if (part.type === 'text') return <p key={i}>{part.text}</p>;
  if (part.type === 'tool-draftEmail' && part.state === 'output-available') {
    return (
      <EmailCard
        key={i}
        {...part.output}
        onSend={() => sendMessage({ text: `Send the draft to ${part.output.to}` })}
      />
    );
  }
  return null;
})}

Put sendEmail behind approval so nothing goes out without a click. ToolLoopAgent supports this with toolApproval: { sendEmail: 'user-approval' } (AI SDK building agents).

5. Messaging channels: iMessage, Slack and friends

A web app is a good start, but the products that took off went where users already are. Instinct, Poke and OpenClaw all live in messaging apps. Your agent server stays the same; you add channels.

Where your users actually are: one agent connects through a messaging layer to iMessage, Slack, Discord and Telegram
Where your users actually are: one agent connects through a messaging layer to iMessage, Slack, Discord and Telegram

Your options

ChannelGood optionNotes
iMessage + SMSLinqPartner API with managed iMessage lines and webhooks. Linq’s customer page lists Poke, Town, Tomo and others (linqapp.com/customers). Bearer token comes from a Linq rep.
iMessage, WhatsApp Business, Telegram, Slack, voicePhoton SpectrumOpen-source TypeScript SDK (spectrum-ts) with one message stream across providers. Discord is a custom provider today (GitHub).
Slack, Teams, Discord, Telegram, WhatsApp, GitHub, Linear, web, plus iMessage via LinqVercel Chat SDKOne Chat instance, one adapter per platform. Linq publishes an official adapter, @linqapp/chat-sdk-adapter.

A note on Instinct: it’s often said to run on Linq, but neither company has said so publicly. The only public mention is a reply from a Linq salesperson. Linq’s own posts and customer page name Poke, DoorDash, Town and others, not Instinct.

One bot, many channels (Chat SDK)

// lib/bot.ts
import { Chat } from 'chat';
import { createSlackAdapter } from '@chat-adapter/slack';
import { createTelegramAdapter } from '@chat-adapter/telegram';
import { createLinqAdapter } from '@linqapp/chat-sdk-adapter';
import { createRedisState } from '@chat-adapter/state-redis';
import { handleMessage } from './handle-message';

export const bot = new Chat({
  userName: 'my-agent',
  adapters: {
    slack: createSlackAdapter(),          // SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET
    telegram: createTelegramAdapter(),
    linq: createLinqAdapter({
      apiKey: process.env.LINQ_API_KEY!,
      signingSecret: process.env.LINQ_WEBHOOK_SECRET!,
    }),
  },
  state: createRedisState({ url: process.env.REDIS_URL! }),
});

bot.onDirectMessage(async (thread, message) => {
  await thread.subscribe();
  await handleMessage(thread, message);   // runs your agent, then thread.post(...)
});
bot.onNewMention(async (thread, message) => {
  await thread.subscribe();
  await handleMessage(thread, message);
});
bot.onSubscribedMessage(handleMessage);
// lib/handle-message.ts
import type { Message, Thread } from 'chat';
import { createAgent } from './agent';
import { loadMemoryContext } from './memory';
import { resolveUserId } from './users';   // phone number / Slack ID -> your user ID

export async function handleMessage(thread: Thread, message: Message) {
  const userId = await resolveUserId(thread, message);
  const agent = createAgent(userId, await loadMemoryContext(userId));
  const result = await agent.stream({ prompt: message.text });
  await thread.post(result.textStream);
}
// app/api/webhooks/[platform]/route.ts
import { after } from 'next/server';
import { bot } from '@/lib/bot';

type Platform = keyof typeof bot.webhooks;

export async function POST(request: Request, context: { params: Promise<{ platform: string }> }) {
  const { platform } = await context.params;
  const handler = bot.webhooks[platform as Platform];
  if (!handler) return new Response('Unknown platform', { status: 404 });
  return handler(request, { waitUntil: (task) => after(() => task) });
}

after lets the route answer the webhook immediately while the agent keeps working. Slack retries events that take longer than three seconds (Chat SDK with Next.js). Each adapter verifies its platform’s webhook signatures. Linq uses the Standard Webhooks spec (Linq webhooks).

Channel gotchas

  • iMessage has no buttons. The Linq adapter flattens cards to text plus images, and button clicks never fire. Ask for a text reply like “reply YES to send” instead (adapter README).
  • Streaming is buffered on iMessage and WhatsApp, so the user sees one final message. Send a quick “on it” first for long jobs.
  • Map every channel identity (phone number, Slack user ID) to one internal user ID so memory follows the person, not the app.

6. Give it a computer: cloud browser + sandbox

To work while your laptop is shut, the agent needs its own computer. In practice that’s two separate hosted services:

Your agent’s computer is two separate services: a cloud browser (Browserbase, Browser Use) and a sandbox terminal (E2B, Vercel Sandbox)
Your agent’s computer is two separate services: a cloud browser (Browserbase, Browser Use) and a sandbox terminal (E2B, Vercel Sandbox)

  • A cloud browser turns the whole internet into an API. Your agent can get through messy government sites, check you in for a flight or fill a 10-page form.
  • A sandbox is an isolated Linux machine where the agent runs code and shell commands without touching your servers.

You can run a headless browser inside a sandbox, but Browserbase and Browser Use are their own browser clouds. They handle stealth, CAPTCHAs, proxies and session recordings, and you call them over their own APIs.

Cloud browsers

Browser Use Cloud is the fastest start. You give it a goal and get back a result, because it runs its own browser agent.

// lib/tools/browser.ts
import { tool } from 'ai';
import { z } from 'zod';
import { BrowserUse } from 'browser-use-sdk/v4';

const bu = new BrowserUse();   // reads BROWSER_USE_API_KEY

export const browseWeb = tool({
  description: 'Do a task on a real website (log in, fill forms, read pages). Describe the goal, not the clicks.',
  inputSchema: z.object({ task: z.string() }),
  execute: async ({ task }) => {
    const run = await bu.runs.create({ task });
    const result = await bu.runs.waitForCompletion(run.id);
    return result.result;
  },
});

Browserbase gives you the raw browser for step-by-step control with Playwright or its Stagehand framework:

import Browserbase from '@browserbasehq/sdk';
import { chromium } from 'playwright-core';

const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY });
const session = await bb.sessions.create({ api_timeout: 600 });
const browser = await chromium.connectOverCDP(session.connectUrl);
const page = browser.contexts()[0].pages()[0];
await page.goto('https://example.gov/form');
// ...fill fields, screenshot, extract
await browser.close();

Browserbase sessions can persist logins through browserSettings.context with persist: true, so the agent doesn’t sign in every time. You must connect within 5 minutes of creating a session (Browserbase docs).

Sandboxes

E2B is the popular choice. A sandbox boots in a few lines and runs any command:

// lib/tools/sandbox.ts
import { tool } from 'ai';
import { z } from 'zod';
import { Sandbox } from 'e2b';

export const runCommand = tool({
  description: 'Run a shell command in an isolated Linux sandbox. Python and Node are available.',
  inputSchema: z.object({ command: z.string() }),
  execute: async ({ command }) => {
    const sbx = await Sandbox.create();             // reads E2B_API_KEY
    try {
      const r = await sbx.commands.run(command, { timeoutMs: 120_000 });
      return { exitCode: r.exitCode, stdout: r.stdout.slice(-8000), stderr: r.stderr.slice(-4000) };
    } finally {
      await sbx.kill();
    }
  },
});

Vercel Sandbox is the alternative if you already deploy on Vercel. It runs microVMs that are persistent by default: a stopped sandbox snapshots its filesystem and restores it on resume.

import { Sandbox } from '@vercel/sandbox';

const sandbox = await Sandbox.create({ name: `user-${userId}` });   // persistent by default
const result = await sandbox.runCommand('python3', ['analyze.py']);
console.log(await result.stdout());

Tips

  • Truncate tool output before it goes back to the model (see the .slice() calls above). Raw HTML and logs eat context fast.
  • One long-lived sandbox per user is handy for files the agent builds over time. A throwaway sandbox per task is safer.
  • Never put your production secrets inside the sandbox. Pass only what that one task needs.

7. Tools and goal engineering with Monid

Goal engineering

The best human hires don’t need to be told which tool to use. Goal engineering gives the agent the goal and access to all the tools it might need, and lets it decide how to do the job. It’s the opposite of hand-holding prompts like “use tool X, then tool Y”.

Goal engineering: give the agent the goal, and it picks the right tools from all of the tools
Goal engineering: give the agent the goal, and it picks the right tools from all of the tools

The hard part is “all the tools”. Competitor ads, Instagram posts and contact data each normally mean a separate vendor, key and monthly subscription.

Monid: one key for thousands of tools

Monid is a tool gateway for agents: 4,300+ tools from 111+ providers behind one key and one balance, paid per call, with no subscription. New accounts get $1 of free credit with no card (monid.ai). Your agent searches the catalog in plain language, checks the input schema and price, then runs the call:

  1. Discover finds endpoints for a need. Free.
  2. Inspect returns the endpoint’s inputs and current price. Free.
  3. Run executes the call. This is the only billed step.

Give my agent a tool like Monid: one request fans out to Meta, Instagram and Apollo endpoints, each priced per call
Give my agent a tool like Monid: one request fans out to Meta, Instagram and Apollo endpoints, each priced per call

Here’s what the live catalog returned on December 1, 2026 for the social media campaign example from the video. Prices change, so inspect is the source of truth.

NeedProvider and endpointPrice
Competitor Meta adsApify /curious_coder/facebook-ads-library-scraper$0.00075 per result
Ads a company is runningAnyAPI /facebook.company_adsabout $0.0011 per call
Popular Instagram posts on a topicLitescrape /instagram/search-popular$0.00015 per call
Company search (Apollo)Apollo /mixed_companies/search$0.026 per call
Enrich one person (Apollo)Apollo /people/match$0.026 per call (more if you reveal a phone number)

Monid is read-focused: search, scraping, enrichment, social, market data and more. To write into SaaS apps (post to Slack, create a CRM record), Monid itself recommends an action platform such as Composio or Zapier (monid.ai/llms.txt).

Hooking Monid into your agent

In Claude Code or another MCP client (for prototyping): claude mcp add --transport http monid https://mcp.monid.ai/v1, then authenticate with /mcp (Monid MCP quickstart).

In your own agent server, call the REST API with an API key from app.monid.ai (API quickstart, run reference):

// lib/tools/monid.ts
import { tool } from 'ai';
import { z } from 'zod';

const BASE = 'https://api.monid.ai/v1';
async function monid(method: 'GET' | 'POST', path: string, body?: unknown) {
  const res = await fetch(`${BASE}${path}`, {
    method,
    headers: { Authorization: `Bearer ${process.env.MONID_API_KEY}`, 'Content-Type': 'application/json' },
    body: body ? JSON.stringify(body) : undefined,
  });
  return res.json();
}

export const monidTools = {
  monidDiscover: tool({
    description: 'Search thousands of paid data tools (scraping, enrichment, social, search, maps...) by what you need. Free.',
    inputSchema: z.object({ q: z.string().describe("Short need, e.g. 'meta ads library'") }),
    execute: ({ q }) => monid('POST', '/discover/endpoints', { q, limit: 5 }),
  }),
  monidInspect: tool({
    description: 'Get an endpoint input schema and live price. Free. Always call before monidRun.',
    inputSchema: z.object({ provider: z.string(), endpoint: z.string() }),
    execute: (args) => monid('POST', '/inspect', args),
  }),
  monidRun: tool({
    description: 'Run a Monid endpoint. Billed. Match the input to monidInspect.',
    inputSchema: z.object({
      provider: z.string(),
      endpoint: z.string(),
      input: z.object({
        body: z.record(z.string(), z.unknown()).optional(),
        queryParams: z.record(z.string(), z.unknown()).optional(),
        pathParams: z.record(z.string(), z.unknown()).optional(),
      }),
    }),
    execute: async (args) => {
      let run = await monid('POST', '/run', { ...args, maxCost: 0.25 });   // per-call cost cap
      while (run.status === 'READY' || run.status === 'RUNNING') {           // async endpoints
        await new Promise((r) => setTimeout(r, 3000));
        run = await monid('GET', `/runs/${run.runId}`);
      }
      return JSON.stringify(run.output ?? run).slice(0, 12_000);
    },
  }),
};

Guardrails worth having

  • maxCost on every run. A run estimated above the cap is refused before anything is charged.
  • A workspace budget or run cap in the Monid dashboard. Over-budget runs come back BLOCKED with a reason the agent can relay to you.
  • Tell the agent in its instructions: “Check Monid before writing a scraper or saying you can’t access something.”

8. Proactivity: routines and look-ahead

This is where the product starts to feel like a person. The best hires don’t just do what you ask; they go above and beyond. For a personal agent, that might mean checking you in for a flight before you remember to.

Agent proactivity: the agent looks ahead at emails and calendar invites and checks you in for Friday’s flight
Agent proactivity: the agent looks ahead at emails and calendar invites and checks you in for Friday’s flight

Mechanically, proactivity is a scheduled or event-triggered agent run with a standing goal. Grok Bot calls these Routines: “a standing responsibility that runs on a schedule or in response to an event” (xAI).

Two easy wins:

  1. Look-ahead: each morning, scan the week’s email and calendar, and act on or flag anything time-sensitive (check-ins, renewals, RSVPs).
  2. Goal check-ins: give the agent a standing goal (“get me to $10K MRR”) and let it do one useful thing per day toward it, using the tools from section 7.

Schedule it

On Vercel, use Schedules. Cron Jobs are now the legacy option (migration guide).

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "schedules": {
    "morning-look-ahead": {
      "schedule": "0 8 * * *",
      "timezone": "America/Vancouver",
      "path": "/api/routines/look-ahead",
      "requestMethod": "POST"
    },
    "nightly-dream": {
      "schedule": "0 3 * * *",
      "timezone": "America/Vancouver",
      "path": "/api/routines/dream",
      "requestMethod": "POST"
    }
  }
}

A path target is a public URL, so check CRON_SECRET in the handler. For new projects Vercel recommends targeting a private function instead (see the configuration reference).

// app/api/routines/look-ahead/route.ts
import { createAgent } from '@/lib/agent';
import { loadMemoryContext } from '@/lib/memory';
import { notifyUser, listActiveUsers } from '@/lib/users';

export async function POST(req: Request) {
  if (req.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response('Unauthorized', { status: 401 });
  }
  for (const user of await listActiveUsers()) {
    const agent = createAgent(user.id, await loadMemoryContext(user.id));
    const { text } = await agent.generate({
      prompt: `Routine: morning look-ahead. Check the next 7 days of email and calendar.
Do anything safe and reversible yourself. For anything else, draft it for approval.
If nothing needs the user, reply exactly NOTHING.`,
    });
    if (text.trim() !== 'NOTHING') await notifyUser(user, text);   // iMessage/Slack via the bot
  }
  return Response.json({ ok: true });
}

Don’t be annoying. Proactive messages are the fastest way to get muted. Last Thanksgiving weekend showed both sides, sometimes from the same agent:

  • The pitch that backfired (Instinct, Thanksgiving Day, Nov 26, 2026). Instinct texted users: “Black Friday is tomorrow. Anything you’ve been meaning to buy? I can also help you get ahead of holiday shopping if you tell me who you’re buying for.” The next morning it followed up offering to “hunt down a deal on anything”. Mark Pincus posted the screenshot with “Is Instinct getting desperate?” (X post). Alex Kehr got the same Thanksgiving text, after earlier unprompted pings, and noted it had also messaged him about his bank account even though he’d told it to disconnect everything (X post). Another reply said Grok Bot had sent the same kind of message, so this wasn’t unique to Instinct (davidlee).
  • The same agent getting it right (Instinct, same weekend). Olivia Moore’s Instinct pulled her family’s wishlists out of email into a shared gift tracker, updated it from receipts, answered family members’ “what’s left to buy?” questions, and refused to tell her what had been bought off her own list: “Still no. You set that rule yourself and I’m keeping it, even with begging.” (X post).
  • An earlier example (Poke, Thanksgiving 2025). Users got long personal notes that remembered their workout streaks, new hires and research deadlines, and posted the screenshots with thanks (for example luckyprime and kai).

The difference: the Black Friday text was a generic, calendar-driven prompt that could have gone to anyone. The gift tracker and the Poke notes used something the agent knew about this person and saved them time. Rule of thumb: every proactive message should pass that test. Let the agent return “nothing to say”, respect “stop” and disconnect instructions everywhere (including memory), and cap messages per day.

9. Memory files

Memory is what makes a personal agent feel like it knows you. The surprising part is how simple the popular version is: Markdown files that get injected into the prompt.

OpenClaw, which GitHub calls the fastest-growing project in its history (GitHub blog), keeps these files in the agent’s workspace (OpenClaw agent workspace):

FileWhat it holds
SOUL.mdPersona, tone and boundaries
IDENTITY.mdThe agent’s name, vibe and emoji
USER.mdStable facts and preferences about the user
MEMORY.mdCurated long-term facts and decisions
AGENTS.mdOperating rules and how to use memory
memory/YYYY-MM-DD.mdDaily log, searched on demand rather than injected

On the first turn of a session, OpenClaw injects these files into the system prompt’s project context, with per-file and total size caps (20,000 and 60,000 characters by default) (OpenClaw agent runtime).

Memory files ride along with every prompt: SOUL, IDENTITY, USER and MEMORY files are injected as project context before the chat history
Memory files ride along with every prompt: SOUL, IDENTITY, USER and MEMORY files are injected as project context before the chat history

Build it

// lib/memory.ts
import { store } from './store';   // read / write / append / backup over Blob, Postgres or the filesystem

const CORE = ['SOUL.md', 'IDENTITY.md', 'USER.md', 'MEMORY.md'] as const;
const MAX_CHARS = 20_000;

export async function loadMemoryContext(userId: string) {
  const parts: string[] = [];
  for (const name of CORE) {
    const text = await store.read(`memory/${userId}/${name}`);
    if (text?.trim()) parts.push(`## ${name}\n${text.slice(0, MAX_CHARS)}`);
  }
  return `# Project context (memory)\n${parts.join('\n\n')}`;
}

export async function appendDailyNote(userId: string, note: string) {
  const day = new Date().toISOString().slice(0, 10);
  await store.append(`memory/${userId}/daily/${day}.md`, `- ${note}\n`);
}
// lib/tools/memory.ts
import { tool } from 'ai';
import { z } from 'zod';
import { appendDailyNote } from '../memory';

export const memoryTools = (userId: string) => ({
  remember: tool({
    description: 'Save a durable fact, preference or correction about the user. One short sentence. Not for one-off details.',
    inputSchema: z.object({ note: z.string().max(300) }),
    execute: async ({ note }) => {
      await appendDailyNote(userId, note);
      return 'saved';
    },
  }),
});

Serverless functions can’t write to the local filesystem permanently, so in production store these files in Vercel Blob, Postgres or an S3 bucket. Keep the file shape; it’s easy to read, diff and edit by hand.

Three rules that keep memory healthy:

  1. Write memories as lessons, not transcripts. Devin’s memories “are not summaries of sessions”; they’re short notes with a link back to where they were learned (Cognition).
  2. Inject a small index, search the rest. Devin injects a short MEMORY.md and searches the other notes on demand (Cognition). OpenClaw does the same with its daily logs.
  3. Scope it. Keep one memory per user. If you run several specialist agents, give each its own memory, the way Grok Bot keeps memory per Bot while sharing tools across the account (xAI).

Don’t want to run the memory layer yourself? Supermemory is a hosted memory API: add() content per user and search() it back.

10. Dreaming

If you chat with your agent eight hours a day, memories pile up, duplicate and go stale, and they start stuffing your context window. Dreaming fixes that with a background job that reviews recent memories, merges duplicates, drops stale notes and promotes what matters.

Dreaming runs in the background about once a day: nine messy memories become four clean ones, plus a new lesson
Dreaming runs in the background about once a day: nine messy memories become four clean ones, plus a new lesson

How the leaders do it:

  • Devin (Cognition): “a daily background session” that consolidates overlapping notes, removes transient details, finds lessons it missed, and removes stale memories no session used (Cognition, Oct 5, 2026).
  • OpenClaw: dreaming is on by default and runs light, REM and deep phases. Only the deep phase writes to MEMORY.md, and the previous version is backed up so every rewrite can be reviewed (OpenClaw dreaming).

Run it on a cheap, fast model. Haiku 5.5 is built for high-volume background and sub-agent work and costs a fraction of Opus (Anthropic).

// app/api/routines/dream/route.ts
import { generateText, Output } from 'ai';
import { z } from 'zod';
import { store } from '@/lib/store';
import { readDailyNotes } from '@/lib/memory';
import { listActiveUsers } from '@/lib/users';

const Dream = z.object({
  memory_md: z.string().describe('The full new MEMORY.md, under 150 lines'),
  user_md: z.string().describe('The full new USER.md'),
  changes: z.array(z.string()).describe('One line per add, merge or removal'),
});

export async function POST(req: Request) {
  if (req.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response('Unauthorized', { status: 401 });
  }
  for (const user of await listActiveUsers()) {
    const [memory, profile, recent] = await Promise.all([
      store.read(`memory/${user.id}/MEMORY.md`),
      store.read(`memory/${user.id}/USER.md`),
      readDailyNotes(user.id, { days: 7 }),
    ]);
    const { output } = await generateText({
      model: 'anthropic/claude-haiku-5.5',
      output: Output.object({ schema: Dream }),
      prompt: `You are consolidating an assistant's memory about one user.
Merge duplicates. Drop transient details (ports, one-off meetings). Keep explicit
preferences and corrections. Add any lesson the notes imply but never stated.
Never invent facts.

MEMORY.md:\n${memory}\n\nUSER.md:\n${profile}\n\nLast 7 days of notes:\n${recent}`,
    });
    await store.backup(`memory/${user.id}/MEMORY.md`);   // keep the previous version
    await store.write(`memory/${user.id}/MEMORY.md`, output.memory_md);
    await store.write(`memory/${user.id}/USER.md`, output.user_md);
    await store.append(`memory/${user.id}/DREAMS.md`, `## ${new Date().toISOString()}\n${output.changes.join('\n')}\n`);
  }
  return Response.json({ ok: true });
}

The DREAMS.md log matters. When the agent forgets something, you can see exactly which night it was dropped.

11. Step-by-step build plan

Copy this into your Claude to build everything we mentioned. Each phase ships something you can use, and the later phases plug in without rewrites.

Phase 1: a web agent that loops

  1. Start from the Vercel Chatbot template, or npx create-next-app plus npm i ai @ai-sdk/react zod.
  2. Set up AI Gateway (or a direct provider key) and pick your orchestrator model.
  3. Replace the chat route with a ToolLoopAgent (section 2) and return createAgentUIStreamResponse({ agent, uiMessages: messages }).
  4. Add one harmless tool (weather, time) and confirm the loop calls it.

Phase 2: memory

  1. Create SOUL.md, IDENTITY.md, USER.md and MEMORY.md for yourself and inject them (section 9).
  2. Add the remember tool and a daily-notes file.

Phase 3: tools and a computer

  1. Add Monid’s three tools (section 7) with a maxCost cap and a workspace budget.
  2. Add a browser tool (Browser Use or Browserbase) and a sandbox tool (E2B or Vercel Sandbox).
  3. Move heavy tools into executor sub-agents (section 3) so the orchestrator’s context stays clean.

Phase 4: interface polish

  1. Render draftEmail and other tool outputs as cards (generative UI) and gate every outbound action behind approval.

Phase 5: go where users are

  1. Add Chat SDK with Slack or Telegram first (instant setup), then iMessage through Linq or Photon (section 5).
  2. Map every channel identity to one user ID and reuse the same agent function.

Phase 6: always-on

  1. Add the morning look-ahead routine and the nightly dream on Vercel Schedules (sections 8 and 10).
  2. Add per-user caps for proactive messages and a “NOTHING” exit.

Phase 7: harden

  1. Work through the production checklist below.

Suggested project layout

my-agent/
├── app/
│   ├── api/chat/route.ts                  # web chat (useChat)
│   ├── api/webhooks/[platform]/route.ts   # Slack, Telegram, iMessage (Linq)...
│   └── api/routines/
│       ├── look-ahead/route.ts            # proactive routine
│       └── dream/route.ts                 # nightly memory consolidation
├── lib/
│   ├── agent.ts                           # orchestrator
│   ├── subagents.ts                       # executors exposed as tools
│   ├── bot.ts                             # Chat SDK instance + handlers
│   ├── memory.ts                          # load / append / store
│   └── tools/{monid,browser,sandbox,email,memory}.ts
├── memory-templates/{SOUL,IDENTITY,USER,MEMORY}.md
├── vercel.json                            # schedules
└── .env.example

Environment variables

# Models
AI_GATEWAY_API_KEY=            # not needed on Vercel (OIDC)
# Tools
MONID_API_KEY=
BROWSER_USE_API_KEY=           # or BROWSERBASE_API_KEY
E2B_API_KEY=                   # or use Vercel Sandbox via OIDC
# Channels
SLACK_BOT_TOKEN=
SLACK_SIGNING_SECRET=
TELEGRAM_BOT_TOKEN=
LINQ_API_KEY=
LINQ_WEBHOOK_SECRET=
REDIS_URL=                     # Chat SDK state
# Routines
CRON_SECRET=

12. Production checklist

Safety

  • Every outbound action (send, post, buy, book) needs approval, or a strict allow-list the user turned on.
  • Treat web pages, emails and tool output as untrusted. Never let them change instructions or approve actions (prompt injection).
  • Webhook signatures verified for every channel (the Chat SDK adapters do this when configured).
  • Routine endpoints check CRON_SECRET, or run as private scheduled functions.

Cost

  • stopWhen step limits on every agent.
  • Monid maxCost per run plus a workspace budget.
  • Sandboxes and browser sessions always closed in finally, with timeouts.
  • Background jobs on Haiku-class models and kept under 100K-token prompts.

Quality

  • Tool outputs truncated before they reach the model.
  • Executors return summaries, not raw data.
  • Memory files capped in size, with a nightly dream and a DREAMS.md log.
  • Log each run’s steps, tools and tokens (the AI SDK onStepEnd and onEnd callbacks).

Respect

  • A daily cap on proactive messages, and an easy “pause” or “stop” command.
  • Users can see and edit what the agent remembers about them.

13. The Claude skill

This guide comes with a ready-to-use Claude skill: always-on-agent in the Monid skills repo on GitHub. It asks you a short brief, then scaffolds the project above phase by phase, using the same stack and guardrails, and checks each phase before moving on. Starting code for every file is in its reference.md.

Install it

npx skills add monid-ai/skills -s always-on-agent

This works with Claude Code, Codex, Cursor and other agents that read skills. Then type /always-on-agent in Claude Code, or just ask "scaffold an always-on agent with iMessage and Slack". Claude loads the skill on its own when the request matches its description (Claude Code skills docs).

Optional: give Claude Code Monid too, so it can test real tool calls while it builds: claude mcp add --transport http monid https://mcp.monid.ai/v1.

14. Sources

Architecture and research

Agent loop and UI

Channels

Browser and sandbox

Tools

Proactivity, memory and dreaming

Skills

always-on ai agentpersonal ai agenthow to build an ai agentproactive ai agentai agent memory