Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

On first run, `memclaw` launches a setup wizard: it asks which front-end you want (Telegram, WhatsApp, Slack or Terminal) and which agent backend, prompts only for the keys those need, and saves them to `~/.memclaw/.env`. Run `memclaw configure` anytime to switch platform or backend, or to update keys.

You can also set keys via environment variables or a `.env` in the current directory — these take the usual precedence over the saved config.
You can also set any of them as environment variables. Where a value comes from, highest first:

1. The environment of the shell that runs `memclaw`.
2. A `.env` in the folder Memclaw is installed in or any folder above it (python-dotenv searches upward from the installed `memclaw` package, not from the folder you run `memclaw` in). In practice this only matters for a development install from a clone, where the clone's `.env` is picked up.
3. `~/.memclaw/.env`, written by the wizard.

A `.env` in the current folder is not read; to use one, export its variables into your shell first (e.g. `set -a; . ./.env; set +a`).

```bash
memclaw --memory-dir ~/my-vault # override storage location
Expand Down Expand Up @@ -53,11 +59,11 @@ Via [`cursor-sdk`](https://pypi.org/project/cursor-sdk/). Install with `pip inst
| `CURSOR_EFFORT` | Optional | Cursor reasoning level, for models that have one (set by `/effort`) |
| `MEMCLAW_MCP_PORT` | For Cursor backend | Local MCP HTTP port (defaults to `17373`) |
| `TELEGRAM_BOT_TOKEN` | For Telegram bot | Your Telegram bot token |
| `ALLOWED_USER_IDS` | For Telegram bot | Comma-separated Telegram user IDs |
| `ALLOWED_USER_IDS` | For Telegram bot | Comma-separated Telegram user IDs allowed to use the bot (empty = nobody) |
| `SLACK_BOT_TOKEN` | For Slack bot | Slack bot token (`xoxb-...`) |
| `SLACK_APP_TOKEN` | For Slack bot | Slack app-level token for Socket Mode (`xapp-...`) |
| `SLACK_ALLOWED_CHANNELS` | For Slack bot | Comma-separated Slack channel IDs (optional) |
| `SLACK_ALLOWED_USERS` | For Slack bot | Comma-separated Slack user IDs (optional — restricts who can DM/mention the bot) |
| `SLACK_ALLOWED_CHANNELS` | Optional | Comma-separated Slack channel IDs the bot answers in (empty = any channel the allowed users write in, DMs included) |
| `SLACK_ALLOWED_USERS` | For Slack bot | Comma-separated Slack user IDs who can DM/mention the bot (empty = nobody) |

Search and memory tuning (weights, decay, chunk sizes) is listed in the [Memory Architecture](memory-architecture.md#configuration-reference) doc.

Expand Down
7 changes: 4 additions & 3 deletions docs/memory-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Daily files accumulate over time. Consolidation is a periodic process that disti

**When it runs:**

- Automatically, in the background after a reply, once a past day has notes that aren't consolidated yet — in practice after your first message of the next day you wrote in (days without notes cost nothing; after a few quiet days it catches up in one call). `consolidation_threshold` (default 1) raises the number of pending days to wait for. At most one consolidation runs at a time; a failure is logged and retried after a reply an hour or more later. A failed backend call (network down, auth, rate limit) is a failure, not a reply: the error text the CLI returns is never written to MEMORY.md, and the consolidation marker doesn't move.
- Automatically, in the background after a reply, once a past day has notes that aren't consolidated yet — in practice after your first message of the next day you wrote in (days without notes cost nothing; after a few quiet days it catches up in one call). `consolidation_threshold` (default 1) raises the number of pending days to wait for. At most one consolidation runs at a time; a failure is logged and retried after a reply an hour or more later. A failed backend call (network down, auth, rate limit) is a failure, not a reply: the error text the CLI returns is never written to MEMORY.md, and the consolidation marker doesn't move. The same goes for a reply that isn't a MEMORY.md (see step 4).
- Manually, via the `memclaw consolidate` CLI command (which forces it regardless of count).

Today's file is never consolidated: it is still being written to, and marking it done would skip everything saved later that day. It is picked up once the day is over.
Expand All @@ -125,8 +125,9 @@ Today's file is never consolidated: it is still being written to, and marking it
- left out entirely: expired one-offs (verification codes, past events, finished trips' bookings), links saved to read later (they stay searchable), instructions for the assistant (they belong in AGENTS.md), small talk.

A wrapping ```` ``` ```` fence in the reply is stripped, and every reference is checked: one to a note that doesn't exist is dropped, one whose note shares no word with the line is logged as unconfirmed (`memclaw/memory/refs.py`).
4. Saves a dated copy of the previous MEMORY.md in `.history/` (the last 60 are kept; the hidden directory isn't indexed or reachable by the file tools), then overwrites MEMORY.md with the result. Lines appended by hand while the backend was working are carried over below the result; if MEMORY.md was otherwise edited meanwhile, nothing is written and consolidation retries later.
5. Records the date of the last file it included in `meta.json` so those files aren't processed again.
4. Checks the reply is a MEMORY.md: it must start with `# Personal Memory` and have a `## Index` heading, as the prompt requires (it asks for the index even when there's nothing to index yet). Anything else (error text a backend returned instead of failing, such as "API Error: Connection refused" or Cursor's "I couldn't generate a response.", an empty or cut-off reply) is logged with a short preview and treated as a failed call: nothing is written, and the background run waits an hour.
5. Saves a dated copy of the previous MEMORY.md in `.history/` (the last 60 are kept; the hidden directory isn't indexed or reachable by the file tools), then overwrites MEMORY.md with the result. Lines appended by hand while the backend was working are carried over below the result; if MEMORY.md was otherwise edited meanwhile, nothing is written and consolidation retries later.
6. Records the date of the last file it included in `meta.json` so those files aren't processed again.

All of this is `Consolidator` in `memclaw/memory/consolidation.py`, the only code that writes MEMORY.md. The agent creates it and calls `schedule()` after each reply; `memclaw consolidate` creates one through `MemoryVault` with the configured backend, without starting the agent, and calls `consolidate(force=True, since=...)`.

Expand Down
8 changes: 4 additions & 4 deletions docs/platforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Commands: `/new` starts a fresh conversation, `/model` shows the available model

1. Create a bot via [@BotFather](https://t.me/BotFather) and copy the token.
2. Get your Telegram user ID (e.g. via [@userinfobot](https://t.me/userinfobot)).
3. Run `memclaw`, pick **Telegram**, and enter the token and your user ID when asked.
3. Run `memclaw`, pick **Telegram**, and enter the token and your user ID when asked. Only the IDs in `ALLOWED_USER_IDS` can use the bot; if it's empty, nobody can (the bot warns about it at start).

## WhatsApp

Expand Down Expand Up @@ -92,9 +92,9 @@ Connects via **Socket Mode** (WebSocket) — no public URL or webhook server nee

2. **Install to Workspace** and copy the **Bot Token** (`xoxb-...`).
3. Under **Basic Information → App-Level Tokens**, generate a token with `connections:write` scope and copy it (`xapp-...`).
4. Run `memclaw`, pick **Slack**, and enter both tokens.
4. Run `memclaw`, pick **Slack**, and enter both tokens and the users who may use it (`SLACK_ALLOWED_USERS`; find your Slack ID via **Profile → ••• → Copy member ID**).

DM the bot directly or mention it in channels (`@Memclaw save this...`). Optionally restrict it to specific channels with `SLACK_ALLOWED_CHANNELS`, or to specific users with `SLACK_ALLOWED_USERS` (find your Slack ID via **Profile → ••• → Copy member ID**).
DM the bot directly or mention it in channels (`@Memclaw save this...`). Only the users in `SLACK_ALLOWED_USERS` get an answer; if it's empty, nobody does (the bot warns about it at start). Optionally restrict it to specific channels with `SLACK_ALLOWED_CHANNELS`; left empty, the allowed users can use it in any channel and in DMs.

## Terminal

Expand Down Expand Up @@ -126,4 +126,4 @@ memclaw status # vault overview
memclaw doctor # check your OpenAI key can reach every model Memclaw uses
```

If voice messages aren't transcribed or link summaries come back empty, run `memclaw doctor`. It probes `text-embedding-3-small` (search), `gpt-5-mini` (link summaries) and `whisper-1` (voice) and tells you which ones your OpenAI project can use. The same check runs at the end of the setup wizard.
If voice messages aren't transcribed or links arrive without a summary, run `memclaw doctor`. It probes `text-embedding-3-small` (search), `gpt-5-mini` (link summaries) and `whisper-1` (voice) and tells you which ones your OpenAI project can use. The same check runs at the end of the setup wizard.
32 changes: 32 additions & 0 deletions memclaw/bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

from __future__ import annotations

import asyncio
import sys
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
Expand Down Expand Up @@ -86,6 +88,36 @@ def require_setting(value: str, env_var: str) -> None:
raise SystemExit(1)


def allowlist_label(allowlist: list, env_var: str) -> str:
"""How the start banner shows an allowlist. An empty one lets nobody in,
so it also prints a warning naming the setting to fill in."""
if allowlist:
return ", ".join(str(who) for who in allowlist)
console.print(
f"[yellow]Warning:[/yellow] {env_var} is empty, so nobody can use the bot. "
f"Set it to a comma-separated list of IDs with [bold]memclaw configure[/bold] "
f"(or in ~/.memclaw/.env) and restart."
)
return "nobody"


def run_until_stopped(start: Callable[[], Awaitable[object]], aclose: Callable[[], Awaitable[object]],
name: str) -> None:
"""Run *start* until it returns or Ctrl+C, then always await *aclose*
(the bot's async shutdown: consolidation, the AI backend, reminders)."""
async def main() -> None:
try:
await start()
finally:
await aclose()

try:
asyncio.run(main())
except KeyboardInterrupt:
pass
console.print(f"\nMemclaw {name} bot shut down.")


def log_to(log_file: Path | None = None) -> None:
"""Log INFO to the terminal and, with a *log_file*, DEBUG to it (rotated)."""
logger.remove()
Expand Down
12 changes: 3 additions & 9 deletions memclaw/bot/inbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@
SendText = Callable[[str, str], Awaitable[None]] # (chat id, text)


def is_allowed(who: object, allowlist: Collection, *, empty_allows_all: bool) -> bool:
"""Whether *who* may use the bot. The platforms disagree on what an
empty allowlist means, so each one says (see their access checks)."""
if not allowlist:
return empty_allows_all
def is_allowed(who: object, allowlist: Collection) -> bool:
"""Whether *who* may use the bot: only those on the allowlist, so an
empty allowlist lets nobody in (on every platform that has one)."""
return who in allowlist


Expand Down Expand Up @@ -150,7 +148,3 @@ async def start(self) -> None:
async def aclose(self) -> None:
await self.agent.aclose()
self.scheduler.close()

def close(self) -> None:
self.scheduler.close()
self.agent.close()
13 changes: 9 additions & 4 deletions memclaw/bot/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ def _extract_text(html: str, max_chars: int = 5000) -> str:
text = re.sub(r"\s+", " ", text).strip()
return text[:max_chars]

async def summarize(self, content: str, url: str) -> str:
async def summarize(self, content: str, url: str) -> str | None:
"""The page's summary, or None if the summary call failed (logged),
the same as for a page that couldn't be fetched: the agent gets no
summary rather than the error text presented as one."""
try:
return await self.openai.chat([
{
Expand All @@ -85,11 +88,13 @@ async def summarize(self, content: str, url: str) -> str:
},
{"role": "user", "content": f"Summarize content from {url}:\n\n{content}"},
])
except Exception as e:
return f"Could not summarize: {e}"
except Exception as exc:
logger.warning("summarize failed for {url}: {exc}", url=url, exc=exc)
return None

async def process_links(self, text: str) -> list[dict]:
"""Extract URLs, fetch content, summarize. Returns [{url, summary}]."""
"""Extract URLs, fetch content, summarize. Returns [{url, summary}];
the summary is None when the page couldn't be fetched or summarized."""
urls = self.extract_urls(text)
results: list[dict] = []

Expand Down
28 changes: 11 additions & 17 deletions memclaw/bot/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from __future__ import annotations

import asyncio
import re
from dataclasses import dataclass
from pathlib import Path
Expand All @@ -18,7 +17,7 @@
from slack_bolt.async_app import AsyncApp

from ..config import MemclawConfig
from . import console, log_to, mask_user_id, require_setting
from . import allowlist_label, console, log_to, mask_user_id, require_setting, run_until_stopped
from .inbound import TRANSCRIPTION_FAILED, Inbound, is_allowed, save_media

# Image MIME types we handle
Expand Down Expand Up @@ -78,13 +77,15 @@ async def handle_mention(event, say, client):
await self._route_event(event, say)

# ── Access control ───────────────────────────────────────────────
# An empty SLACK_ALLOWED_CHANNELS / SLACK_ALLOWED_USERS lets everyone in.
# Only the users in SLACK_ALLOWED_USERS (empty lets nobody in), in the
# channels in SLACK_ALLOWED_CHANNELS (empty = any channel, DMs included).

def _check_channel(self, channel: str) -> bool:
return is_allowed(channel, self.config.slack.allowed_channels_list, empty_allows_all=True)
channels = self.config.slack.allowed_channels_list
return not channels or is_allowed(channel, channels)

def _check_user(self, user: str) -> bool:
return is_allowed(user, self.config.slack.allowed_users_list, empty_allows_all=True)
return is_allowed(user, self.config.slack.allowed_users_list)

# ── Event routing ────────────────────────────────────────────────

Expand All @@ -95,6 +96,7 @@ async def _route_event(self, event: dict, say):

channel = event.get("channel", "")
if not self._check_channel(channel):
logger.info("Ignoring Slack message in channel {c} (not in SLACK_ALLOWED_CHANNELS)", c=channel)
return

user = event.get("user", "unknown")
Expand Down Expand Up @@ -262,18 +264,10 @@ def run(config: MemclawConfig) -> None:

bot = SlackBot(config)

users = allowlist_label([mask_user_id(u) for u in config.slack.allowed_users_list], "SLACK_ALLOWED_USERS")
channels = ", ".join(config.slack.allowed_channels_list) or "any"
console.print(
f"[green]Starting Memclaw Slack bot (Socket Mode)...[/green] "
f"(allowed channels: {config.slack.allowed_channels_list or 'all'})"
f"(allowed users: {users}; allowed channels: {channels})"
)

async def _run():
try:
await bot.start()
except KeyboardInterrupt:
pass
finally:
await bot.aclose()
console.print("\nMemclaw Slack bot shut down.")

asyncio.run(_run())
run_until_stopped(bot.start, bot.aclose, "Slack")
18 changes: 5 additions & 13 deletions memclaw/bot/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from ..backends import AgentBackend
from ..backends.base import ToolStep
from ..config import MemclawConfig
from . import console, log_to, mask_user_id, require_setting
from . import allowlist_label, console, log_to, mask_user_id, require_setting
from .commands import (
load_models,
resolve_model_arg,
Expand Down Expand Up @@ -160,9 +160,7 @@ async def send(chat_id: str, text: str) -> None:
def _allowed(self, update: Update) -> bool:
"""Only the users in ALLOWED_USER_IDS; an empty list lets nobody in."""
user = update.effective_user
return user is not None and is_allowed(
user.id, self.config.telegram.allowed_user_ids_list, empty_allows_all=False,
)
return user is not None and is_allowed(user.id, self.config.telegram.allowed_user_ids_list)

def _message(self, update: Update) -> Message | None:
"""The update's message, if it comes from an allowed user."""
Expand Down Expand Up @@ -377,9 +375,6 @@ async def handle_voice(self, update: Update, context: ContextTypes.DEFAULT_TYPE)
async def aclose(self):
await self.inbound.aclose()

def close(self):
self.inbound.close()


Handler = Callable[[TelegramBot, Update, ContextTypes.DEFAULT_TYPE], Awaitable[None]]

Expand Down Expand Up @@ -458,10 +453,7 @@ def run(config: MemclawConfig) -> None:

app = build_application(config)

allowed = config.telegram.allowed_user_ids_list
masked = [mask_user_id(u) for u in allowed] if allowed else "all"
console.print(
f"[green]Starting Memclaw Telegram bot...[/green] "
f"(allowed users: {masked})"
)
masked = [mask_user_id(u) for u in config.telegram.allowed_user_ids_list]
users = allowlist_label(masked, "ALLOWED_USER_IDS")
console.print(f"[green]Starting Memclaw Telegram bot...[/green] (allowed users: {users})")
app.run_polling(allowed_updates=["message", "callback_query"])
14 changes: 4 additions & 10 deletions memclaw/bot/whatsapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from __future__ import annotations

import asyncio
from pathlib import Path

from loguru import logger
Expand All @@ -19,7 +18,7 @@
from neonize.utils.jid import build_jid

from ..config import MemclawConfig
from . import console, log_to, mask_user_id
from . import console, log_to, mask_user_id, run_until_stopped
from .inbound import TRANSCRIPTION_FAILED, Inbound, save_media

_MIME_TO_EXT = {
Expand Down Expand Up @@ -221,8 +220,8 @@ async def start(self):
await self.client.connect()
await self.client.idle()

def close(self):
self.inbound.close()
async def aclose(self):
await self.inbound.aclose()


def run(config: MemclawConfig) -> None:
Expand All @@ -238,9 +237,4 @@ def run(config: MemclawConfig) -> None:
"Open WhatsApp → Settings → Linked Devices → Link a Device, and scan it."
)

try:
asyncio.run(bot.start())
except KeyboardInterrupt:
pass
finally:
bot.close()
run_until_stopped(bot.start, bot.aclose, "WhatsApp")
4 changes: 3 additions & 1 deletion memclaw/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,12 @@ class SlackSettings(Settings):
app_token: str = setting(
"SLACK_APP_TOKEN", secret=True, required=True,
prompt="Slack app-level token for Socket Mode (xapp-...)")
# Empty = any channel (DMs included) the allowed users write in.
allowed_channels: str = setting(
"SLACK_ALLOWED_CHANNELS", prompt="Allowed Slack channel IDs (comma-separated)")
# Like ALLOWED_USER_IDS, an empty list lets nobody in.
allowed_users: str = setting(
"SLACK_ALLOWED_USERS", prompt="Allowed Slack user IDs (comma-separated)")
"SLACK_ALLOWED_USERS", required=True, prompt="Allowed Slack user IDs (comma-separated)")

@property
def allowed_channels_list(self) -> list[str]:
Expand Down
Loading
Loading