# Alvin Bot Handbook

> A complete, standalone reference for everything Alvin Bot can do — installation, architecture, providers, sub-agents, cron jobs, plugins, MCP, platforms, security, and troubleshooting. Written for users who want to understand the whole system, not just the quick-start.

---

## Table of contents

1. [What Alvin Bot is](#1-what-alvin-bot-is)
2. [Installation](#2-installation)
3. [First run: the setup wizard](#3-first-run-the-setup-wizard)
4. [Architecture at a glance](#4-architecture-at-a-glance)
5. [AI providers](#5-ai-providers)
6. [The chat session model](#6-the-chat-session-model)
7. [Sub-agents](#7-sub-agents)
8. [Cron jobs](#8-cron-jobs)
9. [Commands reference](#9-commands-reference)
10. [Platforms: Telegram, WhatsApp, Discord, Signal, Web, TUI](#10-platforms)
11. [Plugins and MCP servers](#11-plugins-and-mcp-servers)
12. [Skills](#12-skills)
13. [Security](#13-security)
14. [Running in production](#14-running-in-production)
15. [Troubleshooting](#15-troubleshooting)
16. [Upgrading](#16-upgrading)

---

## 1. What Alvin Bot is

Alvin Bot is a self-hosted AI agent that lives where you chat. Instead of being a single-purpose chatbot, it connects a multi-model engine (an Agent SDK, OpenAI, Gemini, Groq, NVIDIA NIM, Ollama, OpenRouter, or any OpenAI-compatible endpoint) to every messaging platform you care about (Telegram, WhatsApp, Discord, Signal, Web UI, terminal), plus a set of superpowers: persistent memory, cron jobs, file access, skill files, MCP tool use, sub-agents for parallel work, and a comprehensive security audit.

The design goal is **"the assistant that actually lives on your machine"**: it has real tool access (not a sandboxed chat), it remembers across sessions, it runs scheduled tasks, and you talk to it through whatever app you already have open.

**Alvin Bot is the bot process.** Your identity — what it calls you, your preferences, long-running context — lives in `~/.alvin-bot/memory/` and is independent of the bot version.

---

## 2. Installation

### 2.1 Quickest path — npm

```bash
npm install -g alvin-bot
alvin-bot setup
alvin-bot start
```

Requirements:
- Node.js 22 or newer (18 and 20 need a C++ compiler for the database module)
- A Telegram bot token (free from [@BotFather](https://t.me/BotFather))
- Your Telegram user ID (from [@userinfobot](https://t.me/userinfobot))

Everything else — an AI provider key — the setup wizard walks you through.

### 2.2 One-line install script

```bash
curl -fsSL https://unpkg.com/alvin-bot/install.sh | bash
```

Downloads, builds, and runs the setup wizard in one shot. Linux and macOS only.

### 2.3 Desktop app (macOS)

The desktop app wraps the bot in an Electron shell with a system tray icon, auto-updater, and the embedded web UI.

Current build: Apple Silicon (arm64). Windows and Linux desktop builds are on the roadmap.

### 2.4 Docker

```bash
docker compose up -d
```

Use this for headless servers. See `docker-compose.yml` for the expected environment variables.

### 2.5 The data directory

Alvin Bot stores all user data under `~/.alvin-bot/` (overridable via the `ALVIN_DATA_DIR` environment variable):

```
~/.alvin-bot/
├── .env                  # bot token, API keys, config
├── memory/               # long-term memory (vector-indexed)
├── sessions/             # session transcripts
├── cron-jobs.json        # scheduled jobs
├── sub-agents.json       # sub-agent config (maxParallel, visibility)
├── delivery-queue.json   # pending outgoing messages with retry
├── logs/                 # stdout/stderr if running under launchd
├── custom-models.json    # user-added OpenAI-compatible providers
├── users/                # multi-user approval + preferences
└── whatsapp-groups.json  # WhatsApp group allowlist
```

The bot code itself lives wherever you installed it (`/usr/local/lib/node_modules/alvin-bot` for an npm-global install). The data directory is portable: copy it between machines and the bot comes up with the same memories, jobs, and settings.

---

## 3. First run: the setup wizard

Running `alvin-bot setup` walks you through four screens:

1. **AI provider** — pick one of the supported providers. Free options first (Groq, Gemini, NVIDIA NIM, Ollama, an SDK-vendor subscription via the CLI). The wizard validates the API key with a test call before saving.
2. **Telegram bot token** — paste the token from BotFather. The wizard calls `getMe` to confirm it's valid and shows you the bot's handle.
3. **Authorized user ID** — paste your Telegram user ID. Only users listed in `ALLOWED_USERS` can chat with the bot; everyone else gets a silent deny.
4. **Optional platforms** — Slack, WhatsApp, Discord, Signal. Each is configured independently; skip any you don't use.

All values land in `~/.alvin-bot/.env` so you can edit them later.

---

## 4. Architecture at a glance

```
┌─────────────────────────────────────────────────────────────┐
│ Platform layer                                              │
│ Telegram · WhatsApp · Discord · Signal · Slack · TUI · Web  │
└──────────────────────────┬──────────────────────────────────┘
                           │
                     platform-message
                           │
┌──────────────────────────▼──────────────────────────────────┐
│ Handler layer                                               │
│ handleMessage · handleVoice · handlePhoto · handleDocument  │
└──────────────────────────┬──────────────────────────────────┘
                           │
                     Engine.query()
                           │
┌──────────────────────────▼──────────────────────────────────┐
│ Provider registry                                           │
│ Agent SDK · OpenAI-compat · Codex CLI · Ollama · custom...  │
│ Heartbeat monitor · fallback chain · retry on transient     │
└──────────────────────────┬──────────────────────────────────┘
                           │
┌──────────────────────────▼──────────────────────────────────┐
│ Services                                                    │
│ Memory · Sub-agents · Cron · Skills · MCP · Plugins · Queue │
└─────────────────────────────────────────────────────────────┘
```

Everything is wired together in `src/index.ts`. The process boots by:

1. Creating `~/.alvin-bot/` and migrating any legacy data
2. Validating the `.env` against the chosen provider
3. Initializing the provider registry
4. Loading plugins and MCP servers
5. Creating the grammy bot instance and attaching the sub-agent delivery router
6. Starting the web server, cron scheduler, delivery queue, and heartbeat
7. Starting optional platform adapters
8. Beginning Telegram polling

A `shutdown()` function in the same file runs in reverse: cancel all running sub-agents (with Telegram notifications), stop the scheduler, drain the delivery queue, unload plugins, disconnect MCP, tear down provider lifecycles (Ollama, LM Studio), then exit cleanly.

---

## 5. AI providers

Alvin Bot supports a multi-provider registry with a fallback chain. You pick a primary, optionally define fallbacks, and the bot picks the best available provider per request.

### 5.1 Built-in providers

| Registry key | Source | Auth | Cost | Notes |
|---|---|---|---|---|
| `claude-sdk` | Agent SDK | OAuth (subscription with the SDK vendor) or API key | Subscription or per-token | Full tool use: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, Task. Needs the SDK vendor's CLI installed. |
| `codex-cli` | OpenAI Codex CLI | Local CLI | Per-token | Needs the `codex` CLI installed. |
| `google` | Google Gemini 2.5 Flash | `GOOGLE_API_KEY` | Free tier available | Vision + embeddings. |
| `ollama` | Local Ollama daemon | none | Free | Auto-detected. Bot can start/stop the Ollama daemon on demand. |
| `claude-sdk-ollama` | Agent SDK, pointed at a local Ollama | none | Free | The same Agent SDK machinery as `claude-sdk`, without an account with the SDK vendor. See 5.6 for the context-window requirement. |

### 5.2 Custom providers

Any OpenAI-compatible endpoint (Groq, NVIDIA NIM, OpenRouter, LM Studio, vLLM, any self-hosted LLM server) goes into `~/.alvin-bot/custom-models.json`:

```json
[
  {
    "key": "groq",
    "name": "Groq (Llama 3.3 70B)",
    "model": "llama-3.3-70b-versatile",
    "baseUrl": "https://api.groq.com/openai/v1",
    "apiKeyEnv": "GROQ_API_KEY",
    "supportsVision": false,
    "supportsStreaming": true,
    "maxTokens": 32768
  }
]
```

Set `PRIMARY_PROVIDER=groq` in `.env` and add `GROQ_API_KEY`. The setup wizard writes this for you for the common providers.

### 5.3 The fallback chain

`.env` can define a fallback order:

```
PRIMARY_PROVIDER=claude-sdk
FALLBACK_PROVIDERS=google,groq
```

On every query, the registry tries the primary first. If it's unavailable (auth fails, rate-limited, service down), it cascades through the fallback list in order. The registry also learns — a provider that fails twice in a row gets temporarily deprioritized until the heartbeat monitor confirms it's healthy again.

### 5.4 The heartbeat monitor

Every 5 minutes, the heartbeat monitor pings each configured provider with a tiny probe. Providers that fail twice in a row are marked unhealthy and get skipped until they recover. You see the current state in `/status` and in the web UI's Dashboard.

### 5.5 Model switching from chat

Two commands, two levels:

- `/provider` — the **global** choice: which provider is primary, and — for the Agent SDK provider — which sub-model it runs. The sub-model row offers the aliases `opus`, `sonnet`, `haiku` and `fable`, plus whatever else the agent CLI itself lists, with the CLI's own value: a new alias as an alias, and a model family the CLI has no alias for yet under its full id (the way the newest family first appeared) — the CLI passes a full id through unchanged, while a made-up short word would not exist. It applies wherever the Agent SDK provider runs without its own model: workspaces and lanes without a pin, background agents, cron jobs set to `claude-sdk`. The default is `opus`.
- `/model` — the model of **the lane you are in** (main included). It never changes the global setting. A provider that is exactly one model (an entry from `custom-models.json`, e.g. a GLM tag in Ollama) has nothing to choose; `/model` says so and names `/lane model <lane> <provider>` for switching the lane's provider instead. If an earlier version pinned another model on such a lane, `/model` names it and `/model default` removes it.

Aliases resolve to the newest model of their tier on the agent CLI — a new top model reaches the bot with the next CLI update, without a bot release or a configuration change. Pin a full model id in `CLAUDE_SDK_MODEL` (in `.env`) only if you want to stay on one version.

`/fallback` — rearrange the fallback chain from Telegram.
`/effort low|medium|high|xhigh|max` — reasoning depth for this conversation (where supported). Without a choice a conversation runs at `medium`; a workspace `effort:` sets its own starting point. The same rule applies to text, photos, voice, video, documents and the other chat platforms; in the web dashboard the Effort menu starts at *Default*, which applies it too (with the workspace the message actually runs in), and picking a level overrides it for your messages. Background agents started from a conversation (`dispatch_agent`) run at the depth that turn actually used; `/gauntlet` runs at least at `high`, deeper if the conversation asks for `xhigh` or `max`.

Cron jobs carry their own model and depth: the web editor has a *Model* and an *Effort* field per AI job, and `scripts/cron-manage.js` takes `--provider <key>` and `--effort <level>` on `add` and `update`; `--provider default` (also through the web API) means no pin of its own, and on `update`, `--effort default` removes the job's own depth. A job without its own depth runs at `medium`.

In the web dashboard, the selector in the chat header is labelled *Provider (global)*: like `/provider`, it switches the global provider, not the lane's model.

### 5.6 The Agent SDK lane without a vendor account

The `claude-sdk` lane is the one with the full machinery — tools, sub-agents, project rules from `CLAUDE.md`, streaming — and it normally talks to the SDK vendor. It can also be pointed at any endpoint that speaks the Agent SDK's native messages protocol, and a local Ollama (0.33 and newer) serves exactly that at `POST <base>/v1/messages`. The `claude-sdk-ollama` provider is that lane, pre-pointed at a local daemon. It is always registered, so `/provider` lists it without any prior setup.

Two settings, both optional:

```
CLAUDE_SDK_OLLAMA_URL=http://127.0.0.1:11434
CLAUDE_SDK_OLLAMA_MODEL=gemma4:e2b
```

- **The address is the daemon's root**, not the `/v1` path used by the OpenAI-compatible lane — the CLI appends `/v1/messages` itself. A copied `/v1` suffix is stripped rather than turned into a 404.
- **The model name is the one the endpoint knows** (`ollama list`), e.g. `gemma4:e2b`. It is passed to the CLI as `--model` and reaches the daemon verbatim. Setting this lane's model to `inherit` does not work against Ollama: with no `--model`, the CLI substitutes its own default model id and the daemon answers `404 not_found_error`. Name a model the endpoint serves.
- **No key is needed.** A placeholder is supplied so the CLI stops asking for a login. Nothing of your SDK-vendor setup travels to the redirected endpoint: the key, the OAuth token and the CLI's custom-header variable (which the CLI forwards verbatim, and which is the documented place for a gateway `Authorization` header) are removed from the child process, as are the CLI's switches that would override the address (cloud-gateway and socket settings) and its model overrides that would put a vendor alias in the request. On the ordinary Agent SDK lane every one of them keeps working exactly as before.
- **Plain address only** — scheme, host, optional path. Credentials (`user:pass@`) and a query string (`?key=…`) are dropped, because neither can work here: the CLI sends no `Authorization` header at all, and it string-concatenates its own path onto the base, so a query turns the call into `/?key=abc%2Fv1%2Fmessages…` and the run fails. An endpoint that *requires* a key is therefore not reachable on this lane.

**Give the daemon at least 32k of context.** A single agent turn's prompt weighs about 22k tokens, tools included — measured at 22,456 input tokens for the first turn of a small write-one-file task, with the CLI's tool catalogue in the prompt. Ollama truncates an over-long input silently and still answers `200`, so with the default 8k — or even 16k — the run ends with exit 0, no work done, and a reply like "Please provide a task or question". Set `OLLAMA_CONTEXT_LENGTH=32768` for the daemon, or use a derived model with `num_ctx`:

```
OLLAMA_CONTEXT_LENGTH=32768 ollama serve
```

A local model is far smaller than the vendor's hosted models, so expect it to work on small, well-defined tasks — a single file edit, a lookup, a short script — and to need several minutes per turn on laptop hardware. Nothing changes for the ordinary Agent SDK lane itself: without an endpoint configured on a lane, no redirection happens.

**What the lane looks like once it runs.** `/status` names the local endpoint instead of reporting a CLI login. `/model` lists the models the endpoint actually serves (`ollama list`), not the vendor's model aliases, and a pick there is stored as a pin on the conversation lane you are in (§6.3), like every `/model` pick; `CLAUDE_SDK_OLLAMA_MODEL` stays the model wherever no pin applies. The ordinary Agent SDK lane's own model setting is left alone, so switching lanes never reconfigures the other one. Turns served locally are booked at `0` in `/cost` and count nothing against `MAX_BUDGET_USD`. Detached background sub-agents follow the same redirect, and no separate install is needed for it: the CLI binary ships inside the Agent SDK dependency (`@anthropic-ai/claude-agent-sdk`), and the binary lookup falls back to it when nothing is on `PATH`. They also follow the lane you are actually in — a lane pin or a workspace `provider:` decides, not the globally active provider — so a locally served conversation never starts a paid background agent beside itself, and a lane on a vendor account is never quietly downgraded to the local model.

**Switching the lane on runs a check first.** `/provider use claude-sdk-ollama` (and the same switch in the web setup) asks three things before accepting: is a daemon answering, does it serve `POST /v1/messages` in the Agent SDK's native format, and is the context window at least 32,768? A failing answer refuses the switch and names the fix — start the daemon, update it (that route exists from Ollama 0.33), `ollama pull` the missing model, or raise `OLLAMA_CONTEXT_LENGTH`. The protocol question is settled with a deliberately unknown model name, which loads nothing, but **reading the window does load the model**: it is read from `/api/ps`, which only reports a *loaded* model, so switching this lane on warms the model up first (measured: 0.8–2.1 s for models of 270M and 7 GB). `/api/show` is not used for it, because it reports the model's own maximum (measured: 131,072 for a model running at 16,384). The model name is matched the way the daemon resolves it, so a name without a tag matches the `:latest` entry `ollama list` prints. The measured window is then written onto the lane, so the watch below judges against the daemon's real edge rather than the lane's 32,768 preset — a daemon running at 128k is not warned about at 30k.

Two answers do not refuse. If the endpoint is not Ollama at all and has no `/api/tags`, the switch is allowed and the window is reported as unknown rather than assumed. If it *is* Ollama but the window could not be read — the model failed to load (an embedding-only model answers `400 does not support generate`), or `/api/ps` did not list it — the switch is allowed **with a warning naming `ollama ps`**, because refusing would leave no way back through `/provider use`, and staying quiet would be exactly the silent all-clear this check exists to abolish. In that case the watch falls back to the lane's preset window.

**During an interactive run the prompt is watched.** Once a turn's prompt passes 85% of the lane's window, the answer says so — once per run, in the reply itself and in the log — instead of the conversation quietly losing its beginning on the next turn. That threshold is measured, not guessed: against a daemon at 16,384, prompts of 10,422 and 16,172 tokens both arrived intact, and the next step up came back as a normal `200` that had silently kept 8,195 — half the window plus three. Truncation therefore starts at the *whole* window, and what is reported after it *falls* rather than rises, which is why the watch reads each turn and not the run's final tally (measured on one turn: 22,726 sent, 8,195 reported at the end). The count is `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`: Ollama reports read cache *beside* the input count rather than inside it, and never sends the third field, but another compatible endpoint does. If you see the notice, start a fresh session with `/new` or give the daemon a larger window. This watch exists only on a lane with a configured endpoint — the ordinary Agent SDK lane against the SDK vendor is not touched, and does not need it, because the vendor rejects an over-long prompt visibly with a `400`.

**The watch covers the conversation, not detached background agents.** A detached sub-agent (`dispatch_agent`, cron work) follows the same redirect but runs its own independent CLI subprocess and reports only a final result, with no per-turn accounting to hold against the window — so on a daemon whose window is too small it still ends the documented way: exit 0, no work done, and a reply like "Please provide a task or question". The preflight above is the protection that covers it, and it is worth switching the lane on by hand once before relying on background work.

**If the address is wrong**, the lane says so and stops rather than falling through to a paid lane behind it in the fallback chain — a silent switch would have billed a vendor account for work you believe is running locally. Two things to check first: the value must start with `http://` or `https://`, and it must be the daemon's root, not its `/v1` path. If the daemon is simply not running, the lane reports itself unavailable and the chain moves on as usual.

### 5.7 Eyes, documents and the tool path

Three things a lane outside the Agent SDK used to lack: a way to know what a local model can actually do with tools, a way to look at a picture, and a way to read a PDF. Since v5.133.0 all three are built in, and all three are switchable.

**The tool path is measured.** A model served by a local Ollama (`localhost:11434` or `127.0.0.1:11434`, cloud tags excluded) is measured once, on the first turn in which it reaches for a tool: can it call tools natively, does it only manage the text protocol, and does a read-then-write chain succeed in the plain tool loop or only inside the offline harness? Afterwards the lane takes the simplest path that passed — `nativ`, `protokoll` or `harness`. The measurement takes a few minutes at worst and says so while it runs; it starts only on a turn you typed, never on a heartbeat or a background beat, and it never happens for a remote endpoint. The result is stored in `<data dir>/faehigkeiten.json` and applies to the local lane alone. A measurement that got no answer from the model at all is not stored, so the next turn tries again. `/status` and `alvin-bot doctor` show the current path as a `🖐 Hands:` line, and `/model test <name>` measures again.

**Layers of the eyes.** When a model without image support is handed a picture — a photo in chat, a `read_image` call, or a `look_again` question about the last image — the bot looks at it instead:

- **Layer 0 — macOS Vision framework** (`assets/augen/vision.jxa`): text with a confidence value per line, plus scene labels. Nothing to install, no dependency, no network.
- **Layer 1 — a local vision model in Ollama**: scene description and an answer to the question asked about the image. Only models served by the local daemon qualify; a cloud-proxied model is skipped, so the picture never leaves the machine. On Linux and Windows this layer is the whole of the eyes — `ollama pull gemma4:e4b` is enough to enable it.
- **Layer 3 — a cloud description**: reserved, and empty in this release. `AUGEN_CLOUD` exists for it and does nothing today.

What the layers report is combined into one finding and passed to the model as fenced, untrusted text, together with the sources it came from. A model with vision of its own is not affected by any of this and receives the picture as before. `alvin-bot doctor` and `/status` name the layers that are actually available on the machine.

**Layers of the document reader.** A PDF, DOCX, PPTX or XLSX becomes text — on upload, and on demand through `read_document`, which takes a path (or, without one, the session's last document) and pages through long text with `offset` and `limit`:

- **PDF on macOS** — PDFKit (`assets/augen/pdf.jxa`) reads the text layer page by page; a page without one is rendered and read by the Vision framework.
- **PDF elsewhere** — `pdftotext`, then `pypdf`, then `pdftoppm` plus OCR, whichever is installed.
- **DOCX** — `textutil` on macOS, otherwise the ZIP XML. `.doc`, `.rtf` and `.odt` go through `textutil` as well.
- **PPTX and XLSX** — read out of the ZIP XML.

The extract names its source (`Source: pdfkit`, `Source: textutil`, …), the page count, and any page it could not read. The uploaded file stays on disk and its path is named in the prompt, so a long document can be read further in the same session.

**The switches, all of them:**

| Variable | Effect |
|---|---|
| `WERKZEUGWEG=nativ\|protokoll\|harness` | Forces the tool path and skips the measurement entirely. |
| `FAEHIGKEITSPROBE=off` | No measurement at all; the lane runs on its configured capabilities. |
| `OFFLINE_AGENT_LOOP=off` | Switches the offline harness off; a model that would need it runs in the plain tool loop instead. |
| `OFFLINE_LOOP_MAX_STEPS` | Step budget of the harness. Default 32. |
| `OFFLINE_LOOP_MAX_SECONDS` | Time budget of the harness. Default 1800 (30 minutes). |
| `AUGEN_CLOUD=1` | Reserved for the cloud layer of the eyes, which is empty in 5.133 — no effect today. |
| `OFFLINE_STRUCTURED_TOOLS` | No effect since 5.133: the broker it used to enable now lives inside the harness only. |
| `ALVIN_TMP_DIR` | Directory for uploads, renders and recordings, and the one the sweeper clears. Defaults to `<system temp>/alvin-bot`. |

---

## 6. The chat session model

Alvin Bot separates **sessions** from **users**. Every platform identity maps to a session, and sessions carry:

- Current provider and fallback chain
- Conversation history (bounded — older messages age out)
- Active skills and personality flags
- Working directory (from `/dir`)
- Locale (`/language`)

Session isolation is configurable via the `SESSION_MODE` env var:

- `per-user` (default) — one shared session per authorized user across all their platform identities. `/new` on Telegram wipes the history for the TUI too.
- `per-channel` — each platform gets its own session. `/new` on Telegram leaves the TUI untouched.
- `per-channel-peer` — each platform × user combo gets its own session. Useful when you share a bot between family members.

Memory (the long-term knowledge base at `~/.alvin-bot/memory/`) is **always** per-user, regardless of session mode.

### 6.1 Long-running sessions

Alvin Bot's defining feature is that **he can think for as long as he needs**. There is no absolute timeout on a query — the only cap is an adaptive "stuck" detector that fires if there's no progress (no text, no tool calls) for `ALVIN_STUCK_TIMEOUT_MINUTES` (default: 10). A legitimate 40-minute reasoning run with continuous tool use never gets killed.

This is deliberate and different from most AI chat wrappers. It means Alvin can work overnight on a research task and deliver the answer when you wake up.

### 6.2 Mid-stream abort and resume

If a provider drops the connection mid-stream (network blip, provider restart), the registry silently retries the **same** provider once. If visible text was already streamed to the user, mid-stream failover is disabled — we don't fail over to a different provider mid-answer because that would jumble the response.

### 6.3 Lanes — parallel workstreams

A **lane** is a named, isolated conversation that runs *in parallel* with your others. One Alvin, several separate threads at once: keep a long work task running in `arbeit` while you start something in `privat`, instead of waiting for the first to finish.

Each lane has its own:
- **conversation and memory** — a lane's session history and its day-to-day recall are isolated (your global long-term memory stays shared);
- **workspace** — bind a persona/folder/model to a lane so it always runs in the right context;
- **daily budget** — an optional per-lane spend cap that blocks only that lane.

**Commands**

| Command | What it does |
|---|---|
| `/lanes` | Dashboard: active lane, status (🔵 working / 🟢 idle / ⏸ waiting), spend today |
| `/lane <name>` | Switch to a lane (creates it if new) |
| `/focus <name>` | Alias for `/lane <name>` |
| `@name: <message>` | Fire a message at an existing lane **without** switching to it |
| `/lane <name> in <workspace>` | Bind a lane to a workspace |
| `/lane budget <name> <usd\|off>` | Set/clear a lane's daily spend cap |
| `/lane rm <name>` | Remove a lane: buttons to archive it (preselected) or delete it for good (second confirmation) |

Lanes process concurrently, bounded by `LANE_MAX_CONCURRENT` (default 3) so N parallel model subprocesses don't overwhelm the machine. The cap counts **named lanes only** — `main` is never gated, so ordinary (lane-less) use is completely unaffected. A lane over the limit waits and its message starts automatically when a slot frees (several messages to a waiting lane are merged, none are lost). Background results are labelled with their lane so you always know which thread a reply belongs to.

Details worth knowing:
- **Lanes are DM-only** in this version — in group chats the lane commands politely decline and everything runs in the normal shared conversation.
- **Media follows the lane**: a voice note/photo/document sent while a lane is active runs in that lane, tagged like text.
- `@name:` addresses an **existing** lane — create one first with `/lane <name>`. An arbitrary `@word: …` text (e.g. quoting a handle) stays a normal message.
- `/stopall` stops **all** lanes of the chat, not just the active one; the ⛔ button and `/cancel` target their own lane.
- A lane that is currently working can't be removed — stop it first, then `/lane rm`. Removing a lane ends its autopilot too; jobs and agents its runs left running are listed with buttons to stop them (§8.3).
- Lane budgets must be above 0 (`off` disables the cap).

**Lane titles.** A lane without a name you gave it gets a short title that says what it is about right now — in the web board's column header and in `/lanes`. A name you typed (renaming in the board) always wins and is never touched; clear it to get automatic titles back. How it works:
- **After the answer, never during it.** Nothing happens while a lane is working; a new message in the same lane cancels any title work for it at once.
- **Once per topic.** A local check without any model call compares each turn with the lane's current topic. The title stays while the topic stays; a single side question doesn't change it. Only when two consecutive turns clearly share a new topic (or you write "new topic") is the model asked — once — whether the title still fits. Returning to an earlier topic brings its title back without asking.
- **The lane's own model, the lightest way.** The model that answered the lane titles it: on the Agent SDK provider an isolated call without tools, settings or session file (about 800 input tokens), on GLM and other OpenAI-compatible providers a single request without tools. Titles never go through the fallback chain; if the lane's provider is rate-limited, titles pause until it resets.
- `LANE_TITLES=off` turns them off; `LANE_TITLE_MAX_PER_LANE_DAY` (default 12) and `LANE_TITLE_MAX_PER_DAY` (default 60) cap the calls.

The default lane is called `main`. **If you never use a lane command, you are always in `main` and everything behaves exactly as before** — no migration, existing history untouched. Lanes, their bindings, budgets and daily spend survive a restart; only a not-yet-started waiting message does not (just resend it).

---

**Restoring an archived lane (v5.157.0).** Archiving moves `memory/lane-<name>/` to `memory/archiv/lane-<name>-<YYYY-MM-DD>/` (`-2`, `-3` … if that name is taken); only the main lane sees it in searches. The web UI's Memory page lists archived lanes (name, date, workspace, size) with Restore and Delete for good; Restore brings the lane back under its name, or asks for another one if the name is taken, with its workspace if that still exists. By hand: make sure the lane is not working, create it again with `/lane <name>`, then move the folder back: `mv ~/.alvin-bot/memory/archiv/lane-<name>-<date> ~/.alvin-bot/memory/lane-<name>`. If `memory/lane-<name>/` exists already, move the archived files into it instead. The next reindex files them under the lane again.

## 7. Sub-agents

**Sub-agents are parallel isolated workers that run in the background.** Use them when you have multiple independent tasks, when you need to keep a long-running task from blocking your main chat, or when you want to dispatch work from a cron job.

The system distinguishes three sources:

| Source | Origin | Delivery |
|---|---|---|
| `implicit` | The main agent calls the SDK `Task` tool | Parent stream (no separate delivery) |
| `user` | You ask the bot to spawn a sub-agent | Banner + final to your chat |
| `cron` | Scheduled job uses `ai-query` | Banner + final to `chatId` in the cron job's target |

### 7.1 Spawning

From chat, the easiest way is to ask the main agent to spawn one:

> *spawne einen sub-agent der mir in einem Wort 'pong' zurückgibt*

The agent invokes the SDK `Task` tool, which runs as `source: "implicit"`. The result streams back into the parent message.

From a cron job of type `ai-query`, the scheduler calls `spawnSubAgent({ source: "cron" })` internally. The cron job's `target.chatId` becomes the `parentChatId` so the delivery lands in the right chat.

### 7.2 The `/subagents` command

| Command | Effect |
|---|---|
| `/subagents` | Show status: max parallel, visibility mode, running list |
| `/subagents max <n>` | Set max parallel (0 = auto = min(cpu, 16)) |
| `/subagents visibility auto\|banner\|silent` | Default delivery mode for new spawns |
| `/subagents list` | Tree view with depth indent and source badges |
| `/subagents cancel <name\|id>` | Cancel a running sub-agent |
| `/subagents result <name\|id>` | Show a completed sub-agent's stored result |

### 7.3 Name-first addressing

Sub-agents are addressable by name, not just UUID. If you spawn three agents called `code-review` in quick succession, they appear as `code-review`, `code-review#2`, `code-review#3` in `/subagents list`. The name-resolver handles collisions automatically.

`/subagents cancel code-review#2` cancels the second one specifically. `/subagents cancel code-review` on an unambiguous base name cancels that one. On an ambiguous base name, the bot replies with a disambiguation list.

### 7.4 Depth cap (F2)

Nested spawning is allowed up to depth 2:

- depth 0 = root (spawned by main thread)
- depth 1 = spawned by a depth-0 agent
- depth 2 = spawned by a depth-1 agent
- depth 3 = rejected

This allows the "scatter-gather" pattern (main → orchestrator → 10 workers) without runaway recursion.

### 7.5 Visibility modes

- `auto` (default) — source-based routing: implicit stays in the parent stream, user and cron get a banner+final delivery.
- `banner` — always send a banner+final, even for implicit spawns.
- `silent` — never send. The result is still stored in the activeAgents map for 30 minutes and pullable via `/subagents result <name>`.
- **`live`** — stream incremental updates into a single Telegram message as the agent thinks. Only applies to `source: "user"` spawns with a `parentChatId`. The live message is plain text (so half-formed markdown during streaming can't break the edit), updates are throttled to 800 ms between edits, and a separate banner message is posted at the end so you get a completion notification. If the bot API doesn't support `editMessageText` or the live setup fails, we fall through to `banner` mode automatically.

### 7.6 Inheritance

Sub-agents inherit from the spawning context:

- **Working directory** — the parent's `cwd` (from `/dir`). Opt out with `inheritCwd: false`.
- **Project rules file** — `CLAUDE.md`, via the Agent SDK's `settingSources: ["project"]`. Loads automatically if the cwd is inside a project with such a file.
- **Model and tools** — inherited via the provider registry.
- **Conversation history** — **not inherited.** Sub-agents receive only their own prompt. This forces clean, self-describing spawn requests.

### 7.7 Bounded priority queue

When the running pool hits `maxParallel`, new spawn requests land in a bounded queue instead of being rejected immediately.

- **Default cap:** 20 slots. Configure via `/subagents queue <n>` (clamped to 0–200).
- **Disable:** `/subagents queue 0` — restores the old reject-on-full behavior.
- **Priority order on drain:** `user > cron > implicit`. Within each priority class, FIFO.
- **`/subagents list`** shows queued entries with a `#N` suffix indicating their position.
- **Cancel a queued entry** with `/subagents cancel <name>` — it's removed from the queue without ever starting.

Reject is only triggered when the pool **and** the queue are both full. The reject message is priority-aware and names who's holding the slots.

### 7.8 Stats

`/subagents stats` shows a summary of the last 24 hours of sub-agent runs:

- Total runs + total tokens + total wall time
- Runs per source (user / cron / implicit)
- Runs per status (completed / cancelled / timeout / error)

The backing data is an append-only JSON ring buffer at `~/.alvin-bot/subagent-stats.json`. Entries older than 24 hours are pruned automatically. A hard cap of 5000 entries protects against runaway growth on very busy bots.

### 7.9 Shutdown notifications

When you restart the bot (SIGTERM), any still-running sub-agents get a cancellation delivery before the process exits:

> ⚠️ `<name>` cancelled · `<duration>` · 0 in / 0 out
> ⚠️ Agent wurde durch Bot-Restart unterbrochen. Bitte neu triggern.

The shutdown phase is capped at 5 seconds total so a hanging Telegram send can't block the restart.

---

## 8. Cron jobs

Scheduled tasks that run regardless of whether you're chatting with the bot. Use them for daily news digests, weekly reports, periodic health checks, or any recurring automation.

### 8.1 Job types

| Type | Payload | Execution |
|---|---|---|
| `reminder` | `text` | Sends the text to the target chat at the scheduled time |
| `message` | `text` | Same as reminder |
| `shell` | `command` | Runs the shell command, sends the output |
| `http` | `url`, `method`, `headers`, `body` | Fires an HTTP request, sends the response |
| `ai-query` | `prompt` | Spawns a sub-agent with `source: "cron"`, result delivered via I3 |

### 8.2 Scheduling syntax

Supports two formats:

- **Interval** — `30s`, `5m`, `1h`, `6h`, `1d`
- **Cron** — standard 5-field (`MIN HOUR DAY MONTH WEEKDAY`, 0 = Sunday)

### 8.3 Managing jobs

From Telegram:

```
/cron              — list all jobs
/cron add          — create a new one (interactive)
/cron delete <id>  — remove a job
/cron toggle <id>  — enable/disable
/cron run <id>     — trigger a job immediately, outside its schedule
```

From the web interface (**Cron** page): a filter bar searches names, tasks and commands and narrows the list by status (active, paused, failing, one-time — each with its count), type, model, origin (created by the bot, by you, or by an autopilot) and lane; the browser remembers it. Tick jobs — or "select all shown" — to pause, resume or delete them together. Deleting asks first and names the jobs; only selected jobs that are currently shown are touched, and pausing an already paused job leaves it paused. Scripts can do the same with `POST /api/cron/bulk` and `{"ids": [...], "action": "pause" | "resume" | "delete"}` (up to 500 ids, one write).

From the command line (useful for scripts):

```
node scripts/cron-manage.js add \
  --name "Daily email summary" \
  --type ai-query \
  --schedule "0 8 * * *" \
  --prompt "Check my inbox and summarize unread messages" \
  --chatId <your-telegram-id>

node scripts/cron-manage.js list
node scripts/cron-manage.js delete --id <job-id>
```

The scheduler polls `~/.alvin-bot/cron-jobs.json` every 30 seconds, so hand-edited jobs come into effect at the next tick without a bot restart.

**Where a job came from.** A job created by the bot's own tools records its `origin`: the chat, the lane and, from an autopilot, the run (`autopilotLauf`, the time the run started). Every tool a turn starts — the Agent SDK's tools, shell and Python on OpenAI-compatible providers, Codex and background agents — sees it as `ALVIN_ORIGIN_SCOPE`, `ALVIN_ORIGIN_LANE` and `ALVIN_ORIGIN_AUTOPILOT` in its environment, and `scripts/cron-manage.js add` stores it with the job. A job that a tool writes straight into `cron-jobs.json` gets its origin from the bot at the next scheduler tick: the turn or background agent that was working in the same chat at that moment — only when there was exactly one (a web-chat turn at the same time counts as a writer of unknown origin); otherwise the job stays without. `/cron` marks such jobs (`🤖 autopilot · <lane>`, or `lane <lane>`), and the web job card names the lane. When an autopilot run ends — `/autopilot off`, one of its limits, or `/lane rm` — the jobs and background agents of that run that are still active are listed with buttons to pause the jobs, stop the agents, or keep them; nothing stops without a tap, and paused jobs can be resumed here. The origin is information for you, not a permission: a tool can overwrite the variables. Jobs created before 5.138.0 carry none.

### 8.4 Delivery

ai-query jobs route through the sub-agent delivery router (see §7). Other job types (reminder, shell, http, message) use the legacy delivery-queue path with retry and exponential backoff. Both paths respect the job's `target.platform` and `target.chatId`.

---

## 9. Commands reference

All commands are triggered from any platform that supports commands (Telegram, Discord).

### 9.1 Core

| Command | Purpose |
|---|---|
| `/start` | Show the bot intro |
| `/help` | List all commands |
| `/new` | Start a fresh session (wipes current history) |
| `/status` | Current status: provider, model, session age, token usage |
| `/cancel` | Cancel the currently running request |
| `/dir <path>` | Change the bot's working directory |

### 9.2 AI control

| Command | Purpose |
|---|---|
| `/provider` | Global provider, and the global sub-model of the Agent SDK provider |
| `/model` | Model of the lane you are in |
| `/fallback` | Rearrange fallback chain |
| `/effort low\|medium\|high\|xhigh\|max` | Set reasoning depth |
| `/voice on\|off` | Toggle voice replies (ElevenLabs or Edge TTS) |
| `/language en\|de\|es\|fr` | Switch session locale |

### 9.3 Memory and history

| Command | Purpose |
|---|---|
| `/remember <text>` | Add something to long-term memory |
| `/recall <query>` | Semantic search across memories |
| `/export` | Export the current conversation to JSON |

### 9.4 Tools

| Command | Purpose |
|---|---|
| `/web <query>` | Quick web search |
| `/imagine <prompt>` | Generate an image (Gemini Nano Banana / Google Imagen) |
| `/remind 30m <text>` | One-shot reminder |

### 9.5 Bot management

| Command | Purpose |
|---|---|
| `/cron` | Manage scheduled jobs |
| `/subagents` | Show sub-agent status |
| `/subagents max <n>` | Set max parallel (0 = auto) |
| `/subagents queue <n>` | Set bounded-queue cap (0 = disabled) |
| `/subagents visibility <auto\|banner\|silent\|live>` | Delivery mode |
| `/subagents list` | List all (queued + running + recent) |
| `/subagents cancel <name\|id>` | Cancel one |
| `/subagents result <name\|id>` | Show a completed result |
| `/subagents stats` | Last 24h run stats (by source + status) |
| `/webui` | Open web UI URL |
| `/setup` | Re-run the setup wizard flow from chat |
| `/restart [jetzt\|frei\|abbrechen]` | Restart the bot process; if work is running, it is listed first with now / when idle / cancel |
| `/update [jetzt\|frei]` | Pull latest, rebuild, restart; asks first if work is running or a job is due within 8:55 min |
| `/tts <provider\|unset> [jetzt\|frei]` | Switch the speech provider (restarts the bot); asks first if work is running |
| `/autoupdate on\|off\|status` | Configure auto-update |

### 9.6 CLI commands (from a terminal)

| Command | Purpose |
|---|---|
| `alvin-bot setup` | Initial setup wizard |
| `alvin-bot start` | Start in background (pm2) |
| `alvin-bot start -f` | Start in foreground (for debugging) |
| `alvin-bot stop` | Stop the bot |
| `alvin-bot tui` | Terminal chat UI |
| `alvin-bot doctor` | Health check and diagnostics |
| `alvin-bot audit` | Security audit |
| `alvin-bot search <query>` | Search assets, memories, and skills |
| `alvin-bot update` | Fetch the latest published version, install, rebuild |
| `alvin-bot launchd install` | **macOS only** — install as LaunchAgent (see §14.1) |
| `alvin-bot launchd uninstall` | Remove the LaunchAgent |
| `alvin-bot launchd status` | Show LaunchAgent state + recent logs |
| `alvin-bot version` | Print version |

---

## 10. Platforms

### 10.1 Telegram

The primary platform. Full support: streaming messages, inline keyboards, voice transcription (via OpenAI Whisper or Edge TTS), photo understanding, document ingestion, sticker replies, command autocomplete.

Setup: `BOT_TOKEN` from BotFather + your user ID in `ALLOWED_USERS`.

### 10.2 WhatsApp

Via WhatsApp Web using `whatsapp-web.js`. Two modes:

- **Self-chat** — treat your own WhatsApp number as a personal assistant notepad
- **Group whitelist** — the bot only responds in explicitly allowed groups, with per-contact access control inside those groups

Group messages go through an approval flow: the owner gets a Telegram notification (or WhatsApp DM fallback) before the bot responds, so there's no surprise chatter from the bot in a group.

Setup: scan the QR code printed on bot startup. Session cookies persist in `~/.alvin-bot/.wwebjs_auth/`.

### 10.3 Discord

Bot with mention detection, slash commands, voice channel support. Uses the standard Discord bot token flow.

Setup: `DISCORD_TOKEN` in `.env`, invite the bot to your server with the correct intents (Message Content + Guild Messages).

### 10.4 Signal

Via `signal-cli` REST API. Less feature-rich than the others because of Signal's tight UI model, but text, images, and voice messages work.

### 10.5 Web UI

A full dashboard at `http://localhost:3100` (configurable via `WEB_PORT`). Password-protected via `WEB_PASSWORD`. Features:

- Live chat with streaming
- Dashboard: provider status, heartbeat, resource usage
- Memory manager: browse and edit long-term memories. Since v5.157.0 it lists every file the memory index reads (root, `privat/`, `projects/`, `research/`, `ws-*`, `lane-*`, the lane archive), restores or deletes archived lanes and edits workspace grants. Saving checks that the file has not changed since it was loaded: if the bot appended to it in the meantime (fact extraction, daily log), the page asks before overwriting those lines, and unsaved text is never replaced without a question
- File browser: navigate and edit files the bot has access to
- Cron job editor
- Settings and env editor
- Plugin and MCP server manager
- Web terminal (in-browser shell)
- Security audit report
- **Lanes view (v5.82)** — the parallel-lane concept from §6.3 now has a home in the dashboard. Open **Lanes** and every active lane appears as its own live column: a status light (working / idle / waiting / error), the lane's workspace identity, and today's spend, all updating in real time as the lane works. A message sent from a column runs through the exact same pipeline as one sent from Telegram — same session, same memory, same tools — and the reply lands in both the column and your chat. Switching a lane's active status from a column works the same way `/lane <name>` does from chat.

### 10.6 TUI

`alvin-bot tui` starts a terminal chat with ANSI colors and streaming. Useful on remote servers without a browser. The terminal client has no lanes: its `/provider <key>` switches the global provider, and its `/model` lists the models and points there.

### 10.7 Slack

Uses `@slack/bolt`. Supports DMs and channel mentions.

---

## 11. Plugins and MCP servers

### 11.1 Plugins

JavaScript modules under `plugins/` that register new Telegram commands and extend the bot's capabilities. Each plugin exports:

- `name`
- `version`
- `commands` (array of `{ name, description, handler }`)
- `init(ctx)` — called at startup, gets access to the bot instance
- `unload()` — called at shutdown

Built-in plugins:

| Plugin | Purpose |
|---|---|
| `calendar` | Google Calendar integration |
| `email` | Gmail / IMAP ingest |
| `finance` | Bank account queries |
| `notes` | Apple Notes / Obsidian sync |
| `smarthome` | Home Assistant control |
| `weather` | Weather forecasts |

User plugins go in `~/.alvin-bot/plugins/` and hot-reload on save.

### 11.2 MCP servers

Model Context Protocol servers extend the bot with new tools. Configure them in `~/.mcp.json` or `~/.alvin-bot/mcp.json`:

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"]
    }
  }
}
```

The bot auto-discovers MCP tools at startup and makes them available to the AI provider (the Agent SDK supports them natively; other providers get the tools as descriptions in the system prompt).

---

## 12. Skills

Skills are Markdown files under `skills/` that teach the AI how to do specific tasks. Each skill is a `SKILL.md` file with:

- Title and description
- When to use it (triggers)
- Step-by-step procedure
- Code templates and examples

Skills auto-activate based on message context. Built-in skills include:

- **apple-notes** — create and search Apple Notes
- **browser-automation** — control Chrome via Playwright
- **code-project** — scaffold, refactor, and test code projects
- **data-analysis** — pandas/jupyter-style data exploration
- **document-creation** — PDFs, plus real PowerPoint decks, Excel workbooks and Word files
- **email-summary** — triage and summarize email
- **github** — issues, PRs, releases
- **summarize** — generic summarization with citations
- **system-administration** — shell tasks on Linux/macOS
- **weather** — forecast queries
- **web-research** — structured web research with sources

User skills go in `~/.alvin-bot/skills/` and are hot-reloaded.

---

## 13. Security

Security is taken seriously because this bot has real system access.

### 13.1 Authentication

Only users listed in `ALLOWED_USERS` can chat with the Telegram bot. The `authMiddleware` silently drops everyone else.

For WhatsApp groups, each group must be explicitly whitelisted and the owner approves each message before the bot responds.

For the web UI, access is gated by `WEB_PASSWORD`. If `WEB_HOST` is not a loopback address and `WEB_PASSWORD` is empty, the routes that write or execute, media downloads (`/api/medien`) and the memory read routes below answer 403, and so does a cross-site browser request to them; other read routes, such as the file browser, are not covered by this rule. Since v5.157.0 that includes reading memory: `MEMORY.md`, today's log, the memory page's file tree and files (`privat/`, `projects/`, lane folders, archive), the lane archive and the workspace grants.

### 13.2 Execution sandboxing

The `EXEC_SECURITY` env var controls how shell commands are gated:

- `full` — no restrictions (use only on trusted machines)
- `allowlist` (default) — only whitelisted binaries from `~/.alvin-bot/exec-allowlist.txt` can run
- `deny` — shell execution completely disabled

### 13.3 Security audit

`alvin-bot audit` runs a series of health checks:

- Are secrets in `.env` readable only by you?
- Is the data directory mode `0700`?
- Are there any API keys leaked into version-controlled files?
- Is the bot exposed on a public port?
- Are the allowed users list and exec allowlist intact?

Each check reports `PASS` / `WARN` / `FAIL` with a fix suggestion.

### 13.4 Checkpoints during long runs

Alvin's Agent SDK provider injects a `[CHECKPOINT]` reminder into the prompt every 5 turns once certain thresholds are crossed (10+ messages or 15+ tool calls in a session). The reminder tells the model to write a checkpoint to its memory file before processing the next request. This protects against context compaction losing progress on long multi-hour sessions.

### 13.5 Git safety

The bot's own code is protected against accidental destruction:

- Never changes user passwords in projects
- Never touches auth functions without explicit instruction
- Never runs `git push --force` on main/master
- Never bypasses pre-commit hooks (`--no-verify`)
- Never amends commits that might be lost

---

## 14. Running in production

### 14.1 macOS: `launchd` (recommended)

On macOS with the Agent SDK provider, you **must** run the bot as a `launchd` user agent, not via pm2. The agent CLI stores the OAuth token for your subscription in the macOS Keychain, and only processes running inside the user's GUI login session can access that Keychain without a manual unlock.

Pm2 starts its daemon in a detached launchd context without Keychain access. Result: the bot sees `Not logged in` on every Agent SDK call. Launchd user agents, on the other hand, run inside the GUI session and inherit the unlocked Keychain automatically.

```bash
alvin-bot launchd install
```

This writes `~/Library/LaunchAgents/com.alvinbot.app.plist` with:

- `RunAtLoad true` — starts on login
- `KeepAlive Crashed=true` — auto-restart on crash
- `ThrottleInterval 10` — prevents restart loops
- `PATH` covering Apple Silicon and Intel Homebrew plus `~/.local/bin`
- stdout → `~/.alvin-bot/logs/alvin-bot.out.log`
- stderr → `~/.alvin-bot/logs/alvin-bot.err.log`

Management:

```bash
alvin-bot launchd status       # plist state, PID, last log lines
alvin-bot launchd uninstall    # unload and remove the plist

# Restart:
launchctl kickstart -k gui/$UID/com.alvinbot.app
```

If you'd previously set up the bot via pm2, uninstall the pm2 process first (`pm2 delete alvin-bot; pm2 kill`) before running `launchd install`.

### 14.2 Linux / Windows: pm2

The `alvin-bot start` command wraps pm2:

```bash
alvin-bot start       # start in background, auto-restart on crash
alvin-bot start -f    # start in foreground (for debugging)
alvin-bot stop        # stop the bot
pm2 logs alvin-bot    # live logs
```

For systemd users, you can write a user unit pointing at `node dist/index.js` — see the example in `docs/systemd.md` (if included in your release).

### 14.3 Auto-update

`/autoupdate on` tells the bot to check for updates daily. When an update is found, it runs `git pull`, `npm install`, `npm run build`, and restarts itself. The auto-update flag lives at `~/.alvin-bot/auto-update.flag`.

### 14.4 Environment variables reference

Common env vars (all optional unless marked):

| Variable | Default | Purpose |
|---|---|---|
| `BOT_TOKEN` | — | **Required**. Telegram bot token. |
| `ALLOWED_USERS` | — | **Required**. Comma-separated Telegram user IDs. |
| `PRIMARY_PROVIDER` | `claude-sdk` | Registry key of the default provider. |
| `FALLBACK_PROVIDERS` | — | Comma-separated fallback chain. |
| `GOOGLE_API_KEY` | — | Required if using `google` as provider. |
| `GROQ_API_KEY` | — | For custom Groq provider. |
| `OPENAI_API_KEY` | — | For custom OpenAI provider. |
| `OPENROUTER_API_KEY` | — | For custom OpenRouter provider. |
| `NVIDIA_API_KEY` | — | For custom NVIDIA NIM provider. |
| `ELEVENLABS_API_KEY` | — | Voice synthesis (falls back to Edge TTS). |
| `WEB_PORT` | `3100` | Web UI port. |
| `WEB_PASSWORD` | — | Web UI access password. |
| `SESSION_MODE` | `per-user` | Session isolation mode. |
| `ALVIN_STUCK_TIMEOUT_MINUTES` | `10` | Adaptive stuck-detector window. |
| `TOKEN_STREAMING` | `true` | Real-time token streaming (Agent SDK provider). `false`/`0` = block-level chunks. |
| `ALVIN_EMPTY_STREAM_RETRY_TIMEOUT_MS` | `60000` streaming / `300000` not | How long the automatic empty-turn retry may stay silent before it is written off. Default follows `TOKEN_STREAMING`, which decides how soon a first chunk can appear. |
| `ALVIN_DISABLE_DEADMAN_LIVENESS` | unset | Set to `true` to skip the startup check that confirms the external dead-man watcher (macOS launchd only) is actually ticking, not just installed. |
| `MAX_SUBAGENTS` | `0` (auto) | Max parallel sub-agents. |
| `SUBAGENT_TIMEOUT` | `300000` | Per-agent timeout in ms. |
| `COMPACTION_THRESHOLD` | `80000` | Tokens before context compaction triggers. |
| `EXEC_SECURITY` | `allowlist` | Shell execution sandbox mode. |
| `ALVIN_FREIE_HAND` | unset | v5.139.0. `1` lifts **every** tool guard: the destructive-command guard including its catastrophic baseline, the write-path guard including system directories, and the shell allowlist. For owners who want their bot unrestricted — responsibility moves to you, and the bot says so at startup and in `/status`. Access control and the fencing of external content are unaffected. |
| `ALVIN_SHELL_TIMEOUT_SEC` | `600` | v5.139.0. Default time limit for `run_shell` (was a fixed 30 s). |
| `ALVIN_PYTHON_TIMEOUT_SEC` | `600` | v5.139.0. Default time limit for `python_execute` (was a fixed 60 s). |
| `ALVIN_SHELL_TIMEOUT_MAX_SEC` | `1800` | v5.139.0. Ceiling a single call may request via the tools' `timeout_seconds` argument. |
| `ALVIN_DATA_DIR` | `~/.alvin-bot` | Data directory path. |
| `RESTART_WHEN_IDLE_MAX_MIN` | `90` | v5.155.0. Longest wait for "restart when idle", in minutes (5 to 720). At the limit the restart goes ahead and the owner receives the list of interrupted work. |
| `MEDIEN_AKTIV` | on | v5.156.0. `false` switches the Web-UI copies of sent files off; delivery to Telegram is unaffected. |
| `MEDIEN_MAX_TAGE` | `30` | v5.156.0. Days a Web-UI copy of a sent file is kept (1–365). |
| `MEDIEN_MAX_BYTES` | `1000000000` | v5.156.0. Upper limit for all Web-UI copies together, oldest removed first (≥ 10000000). |
| `PRIVATE_QUELLEN` | empty | v5.156.2, extended in v5.157.0. Comma-separated prefixes of memory sources that are private in addition to the built-in ones (`memory/privat/`, dated topic notes `memory/YYYY-MM-DD-<topic>.md`), e.g. `memory/projects/,assets/legal/`. They reach only the main lane and lanes whose workspace lists them under `privateQuellen:` (`*` = all private sources, `datierte-notizen` = dated topic notes). Changed in the web UI (Settings, Environment Variables) it takes effect at once; edited in `.env` by hand it needs a restart. |
| `ALVIN_HUB_DIR` | `~/.claude/hub/MEMORY` | v5.157.0. Folder whose `.md` files the memory index reads as `hub/…`. |

---

## 15. Troubleshooting

### 15.1 Bot starts but doesn't respond

1. `alvin-bot doctor` — runs 10+ health checks
2. Check the log: `pm2 logs alvin-bot` (or `~/.alvin-bot/logs/alvin-bot.err.log` under launchd)
3. Verify your provider: `/status` in chat shows the active provider and its health

### 15.2 The Agent SDK says "Not logged in"

You're hitting the Keychain problem documented in §14.1. Three paths:

- **Preferred**: switch to `alvin-bot launchd install` on macOS
- **Temporary**: `security unlock-keychain -p '<your-login-password>' ~/Library/Keychains/login.keychain-db`, then restart the bot in the same terminal session
- **Fallback**: start the agent CLI interactively (`claude`), run `/login` in it, then re-run the bot

### 15.3 Sub-agent limit reached

Either increase the cap:

```
/subagents max 8
```

Or cancel a stuck agent:

```
/subagents list
/subagents cancel <name>
```

### 15.4 Cron job not firing

- Is it `enabled: true`? `/cron` or `cat ~/.alvin-bot/cron-jobs.json`
- Is the schedule valid? Try `/cron run <id>` to trigger manually
- Check the bot log for `[cron]` lines

### 15.5 Web UI shows "Not authorized"

`WEB_PASSWORD` isn't set or doesn't match. Add `WEB_PASSWORD=<pick-a-password>` to `.env` and restart.

### 15.6 Sub-agent results shown twice

Happens if you upgrade from a version before 4.6.0 and a mid-stream shutdown race fired. Fixed in 4.6.0 — see CHANGELOG §9.2.

### 15.7 A dispatched background agent didn't survive the conversation ending

If a task you asked to run in the background stopped producing output the moment the chat that started it went idle or ended, it may have run as a temporary in-session helper instead of a real detached agent — the two look identical while running, but only the detached kind survives past the turn. Check the bot log for `[dispatch-gap]` lines; each one names the surface (message type or platform) where this happened. It's always a wiring bug on the bot's side, never something you did — if you see it, it's worth reporting.

### 15.8 "My external watchdog isn't ticking" DM

On macOS, shortly after every start the bot samples the dead-man LaunchAgent's run counter twice and DMs you once if it never moved — installed does not mean running. If you get this: `launchctl print gui/$UID/com.alvinbot.deadman | grep runs`, and if it's stuck, `alvin-bot launchd install` re-registers both LaunchAgents. Suppress the check with `ALVIN_DISABLE_DEADMAN_LIVENESS=true`.

### 15.9 Upgrading from 4.5.x

- Run `npm install -g alvin-bot@latest`
- Run `alvin-bot update` from chat (pulls, rebuilds, restarts)
- On macOS, consider switching from pm2 to `alvin-bot launchd install` for the Keychain fix

---

## 16. Upgrading

### 16.1 Data directory compatibility

Alvin Bot follows semver for the **data directory format**. Minor version bumps never break `~/.alvin-bot/`; major bumps might introduce migration scripts that run automatically on first startup.

### 16.2 From 4.5.x to 4.6.0

- Sub-agents: new fields in `sub-agents.json` (`visibility`). Old files auto-upgrade — the loader treats missing fields as defaults.
- Cron jobs: no schema change.
- Memory: no schema change.
- `.env`: no new required variables. `MAX_SUBAGENTS` and `SUBAGENT_TIMEOUT` are optional.

### 16.3 From 4.6.x to 4.7.0

- Sub-agents: new fields in `sub-agents.json` (`queueCap`, defaults to 20). Old files auto-upgrade.
- New file `~/.alvin-bot/subagent-stats.json` — auto-created when the first sub-agent finishes.
- `start`/`stop` now auto-detect the LaunchAgent on macOS. No migration needed; if you previously installed the LaunchAgent in 4.6.0, `alvin-bot start` now correctly reloads it instead of spawning a parallel pm2 process.
- No new required `.env` variables.

### 16.4 From npm

```bash
npm install -g alvin-bot@latest
alvin-bot stop
alvin-bot start
```

If you run under launchd, reload it afterwards with
`launchctl kickstart -k gui/$UID/com.alvinbot.app`.

### 16.5 Rollback

```bash
npm install -g alvin-bot@4.5.1
```

Old data in `~/.alvin-bot/` continues to work — nothing is deleted on upgrade.

---

## Feedback and bug reports

- Contact: alvbln7@gmail.com
- Pull requests welcome
- Maintained by @alvbln
