# local-server/ — Local AI Server

Runs on the user's machine. Connects to the Cloud Gateway via WebSocket, receives Teams messages, and processes them through one of two swappable agent backends (Claude Agent SDK in-process or GitHub Copilot CLI spawned per turn) before sending replies back.

## Key Constraints

- Code **runs only on the user's local machine**, spawned by daemon-entry.ts
- Must NOT depend on @microsoft/teams.* or @azure/identity
- Uses NodeNext module resolution (ESM imports with `.js` extensions)

## Device Identity

On startup, `index.ts` resolves a stable identity for this install and passes it to `CloudChannel`:

- **`deviceId`** — UUIDv4 persisted at `~/.brainbotbeta/device-id` (mode `0o600`). Created on first start; reused on every subsequent start. The Gateway routes bound Teams conversations to this id, so it must be stable across restarts. Wipe the file (or `~/.brainbotbeta/`) to force a new identity.
- **`deviceName`** — `process.env.BRAIN_DEVICE_NAME?.trim() || os.hostname()`. Sent to the Gateway and displayed in the device picker. Display only — never used for routing.

Both are sent on every WSS connect as headers:
- `x-brain-device-id: <uuidv4>`
- `x-brain-device-name: <URL-encoded UTF-8>`

## Source Layout

```
src/
├── index.ts              — Entry point: CloudChannel + onMessage handler + processInBackground
├── push.ts               — Proactive push via CloudChannel.sendPush
├── types.ts              — IncomingMessage, ReplyStrategy, SchedulerDependencies
├── config.ts / config-schema.ts / load-config.ts — User config (~/.brainbotbeta/config/config.json)
├── logger.ts             — Pino structured logger (stdout + file rotation)
├── paths.ts              — Path constants
├── commands.ts           — # command handlers (#new, #add-dir, #workspace, etc.)
├── agentlink.ts          — Optional integration: reads `~/.agentlink/agent.json` and builds deep links into the AgentLink web UI used by `#list-sessions`
├── lock.ts               — Per-key async mutex (serializes per conversation)
├── semaphore.ts          — Counting semaphore (limits concurrent Claude processes)
├── retry.ts              — Exponential backoff retry for transient errors
├── spawn-serialiser.ts   — Custom spawn hook with synchronous retry for OS errors
├── process-background.ts — Fire-and-forget pipeline (concurrency → lock → retry → agent)
├── background-counter.ts — Shared mutable counter for in-flight tasks
├── workspace.ts          — Per-conversation workspace initialization
├── graph.ts              — Microsoft Graph API client (channels, messages, threads)
├── images.ts             — Image attachment persistence to disk
├── push.ts               — pushMessage helper (proactive notifications)
├── ask.ts                — askUser helper + late-click handler wiring (bridges the `ask_user` MCP tool to CloudChannel)
├── relay/
│   ├── types.ts          — Wire protocol frame types (synced with bot-app)
│   ├── wire-frames.ts    — Client-side encode/decode
│   ├── cloud-channel.ts  — WSS client: connect, reconnect, heartbeat, send queue; `sendAskChoice` / `onChoiceResponse`
│   ├── pending-asks.ts   — In-memory registry of in-flight ask_user Promises + history for late clicks
│   └── html-to-markdown.ts — Teams HTML → Markdown converter
├── agent/
│   ├── index.ts          — processMessage dispatcher (resolveBackend → claude or copilot path) + Claude SDK query + safePush
│   ├── copilot-runner.ts — Copilot CLI driver: spawns `copilot --output-format json ...` per turn, parses JSONL stdout into AgentResult
│   ├── context.ts        — Conversation context builder
│   ├── hooks.ts          — Pre-compact hook (Claude backend only)
│   ├── system-prompt.ts  — System prompt: NECESSARY + OVERRIDABLE layers, composeSystemPrompt()
│   ├── history.ts        — history.md append-only session log
│   ├── summarize.ts      — Transcript summarization via Anthropic API
│   ├── guides.ts         — Guide files seeded into ~/.brainbotbeta/global/guides/
│   └── formatter.ts      — Message → compact XML for prompt
├── db/
│   ├── index.ts          — Re-exports all DB modules
│   ├── schema.ts         — SQLite schema + init
│   ├── messages.ts       — Message CRUD
│   ├── sessions.ts       — Session persistence
│   ├── session-size.ts   — Transcript-size guard: rotates oversized scheduled-task sessions
│   ├── state.ts          — Router state KV
│   ├── tasks.ts          — Scheduled task CRUD
│   ├── directories.ts    — Per-session directory management
│   ├── workspace-override.ts — Per-session workspace cwd override
│   └── images.ts         — Image attachment CRUD
├── mcp/
│   ├── index.ts          — MCP server factory
│   ├── push-message.ts   — push_message tool
│   ├── ask-user.ts       — ask_user tool: multiple-choice card; replaces the SDK's disallowed AskUserQuestion built-in
│   ├── schedule-task.ts  — schedule_task tool
│   ├── list-tasks.ts     — list_tasks tool
│   └── manage-tasks.ts / manage-dirs.ts — Task/dir management tools
└── scheduler/
    ├── index.ts          — Scheduler loop (setTimeout chain)
    ├── runner.ts         — Task execution with ReplyStrategy
    └── next-run.ts       — Cron next-run calculation
```

## Agent Backends

`processMessage()` in `agent/index.ts` is a thin dispatcher that calls `resolveBackend(conversationKey)` and routes to one of two implementations:

| Backend | Module | How it runs | Capabilities |
|---------|--------|-------------|--------------|
| `claude` (default) | `agent/index.ts` (`processClaudeMessage`) | `@anthropic-ai/claude-agent-sdk` `query()` in-process | Full MCP servers, PreCompact hooks, Agent Teams sub-agents, additional directories, session resume |
| `copilot` | `agent/copilot-runner.ts` (`runCopilotTurn`) | Per-turn `spawn('copilot', ['--output-format', 'json', '--allow-all', '-s', '--no-ask-user', '--no-auto-update', '--no-custom-instructions', ...])`. Prompt via stdin (avoids Windows arg-length limits). JSONL stdout parsed for `assistant.message_delta` (buffered into final reply) and `result` (provides session id for `--resume` next turn). | Copilot's built-in tool set + bundled `github-mcp-server`. **No** MCP servers, PreCompact hooks, or Agent Teams sub-agents from this codebase. |

Both return the same `AgentResult`, so the downstream `processInBackground` pipeline (typing indicator, `sendResponse`, push, session persistence) is identical.

**Resolution order** (`resolveBackend`):
1. `router_state['backend:<conversationKey>']` (per-conversation, set by `#backend`)
2. `router_state['global:defaultBackend']` (set by `#default-backend`)
3. `config.claude.backend`
4. Fallback `'claude'`

Unknown values at any tier log a warning and fall through to the next tier — they never throw.

**Session staleness guard:** `processMessage` tracks the last-used backend per conversation as `router_state['lastBackend:<key>']`. If the resolved backend changes between turns, the stored session id is cleared before invoking the new backend (Claude and Copilot session IDs cannot be reused across backends in the shared `sessions` table — same pattern as the cwd / model / system-prompt staleness guards).

**Binary resolution** (Copilot only): `COPILOT_CLI_PATH` env var wins; otherwise PATH-based `where` / `which` lookup, cached for process lifetime. Prefers `copilot.exe` over `copilot.cmd` on Windows; falls back to `cmd.exe /c copilot.cmd` if only the wrapper is on PATH. 15-minute per-turn `SIGKILL` timeout.

## Communication — WSS Relay

Messages flow through the `CloudChannel` class (`src/relay/cloud-channel.ts`):

- **Inbound**: Gateway sends `MessageFrame` → CloudChannel strips @mentions, converts HTML→Markdown → calls `onMessage` handler
- **Outbound responses**: `cloudChannel.sendResponse(channelId, content, 'markdown')` — directed reply (consumes ReplyContext on Gateway)
- **Outbound push**: `cloudChannel.sendPush(content, format, title, sessionKey)` — proactive message (does NOT consume ReplyContext)
- **HTTP API push**: `POST /api/push` — BrainCore integration endpoint for proactive channel messages (see below)
- **Heartbeat**: Gateway sends `ping` every 45s, CloudChannel replies `pong` directly (bypasses send queue)
- **Reconnection**: Exponential backoff 1s→60s with ±20% jitter. Auth failure (401/403) switches to 2-minute fixed-interval reconnection (picks up refreshed token from disk).

### ReplyStrategy

```typescript
type ReplyStrategy =
  | { mode: 'response'; channelId: string }   // Final reply — sendResponse (deletes ReplyContext)
  | { mode: 'push'; sessionKey?: string }      // Intermediate/proactive — sendPush (preserves ReplyContext)
```

**Only the final result uses `sendResponse`**. All intermediate messages (sub-agent completions, queue notifications, error notifications) use `sendPush` to avoid consuming the ReplyContext.

### ask_user MCP tool

The Claude SDK's built-in `AskUserQuestion` is disabled (via `disallowedTools: ['AskUserQuestion']` in `agent/index.ts`) because its question payload never reaches Teams. The Copilot CLI uses `--no-ask-user` for the same reason. Both backends instead surface multi-choice prompts via our `ask_user` MCP tool (`src/mcp/ask-user.ts` — Claude only; the Copilot CLI has no MCP server hook):

1. Tool input: `{ question, description?, options: [{title, description?}], multi_select? }`. Option ids are positional (`"0"`, `"1"`, ...).
2. `ask.ts::askUser()` registers a `PendingAsks` Promise, sends an `AskChoiceFrame` over WSS, persists the question to the message DB (so post-`#new` sessions retain context), and awaits the response.
3. Resolution kinds (returned to the tool callback as `AskResolution`):
   - `answered` — user clicked one or more options; resolved with `titles[]` and raw `selectedIds[]`.
   - `wire_cancel` — Gateway forwarded a cancelled `ChoiceResponseFrame` (`expired` or `user_cancel`).
   - `local_cancel` — Local cancellation: `superseded` (new user message arrived), `query_ended` (SDK turn finished), or `shutdown`.
4. **Cancel-on-supersede**: when a new user message arrives, `index.ts` calls `cancelAsksForConversation(sessionKey, 'superseded')` before queueing the message. The SDK turn winds down with the `local_cancel` tool result; the bot-app `AskTrackerStore` entry stays alive (7-day TTL).
5. **Late-click handler**: if the user later clicks the now-stale card, the response arrives with no pending Promise. `ask.ts` looks up the history entry, deletes it (consume-once), and calls the registered late-click handler — which `storeMessage()`s a synthetic `IncomingMessage` (text = comma-joined option titles) and pushes it through `processInBackground` with a `{mode: 'push'}` strategy. The model treats it like a normal user message.

Neither side persists asks — Gateway restart wipes `AskTrackerStore` (user sees "card expired"); local-server restart rejects in-flight Promises via `cancelAllAsks('shutdown')`.

## Development Rules

### Error Handling — No Silent Failures

Every error must leave a trace:
1. **Agent/MCP tools**: catch → `{ isError: true }` with user-readable message
2. **Scheduler tasks**: catch → log + `task_run_logs` + push failure notification
3. **Database operations**: let errors propagate (or re-throw with context)
4. **Startup/Init**: crash on failure — don't silently continue in a broken state

**Rule of thumb**: `catch { }` or `catch { /* ignore */ }` is almost certainly wrong. At minimum, add `logger.warn` with context.

### Code Style

- **All logging uses `logger`** from `src/logger.ts` — never `console.log/error/warn`
- Use `{ err }` key for errors: `logger.error({ err }, 'msg')` — pino auto-serializes stacks
- Use lazy-init pattern for prepared statements (see `db/messages.ts`)
- Keep modules focused: one concern per file, export a small public API

### Concurrency

- `withConcurrencyLimit()` — global semaphore (max 5 concurrent Claude processes, 10-min queue timeout)
- `withLock()` — per-conversation-key mutex (serializes `processMessage` within a conversation)
- Both user messages and scheduled tasks go through: `withConcurrencyLimit` → `withLock` → `withRetry` → `processMessage`
- The scheduler runs tasks sequentially within each tick (setTimeout chain, not setInterval)

### Scheduled-task session rotation

Isolated scheduled tasks (`context_mode !== 'conversation'`) reuse a stable `scheduled:{task_id}` session key on every fire, so the resumed Claude transcript grows unbounded and eventually crosses the upstream 1,000,000-token cap — after which every fire dies instantly with `400 prompt is too long` before the model does any work. Interactive conversations never hit this (they get context compaction and `#new`); only unattended schedulers accumulate.

`runner.ts` guards against this by calling `rotateSessionIfOversized(conversationKey)` right after deriving the key, **only for isolated schedules**:

- `db/session-size.ts` stats the on-disk transcript (located by its globally-unique `<sessionId>.jsonl` filename under the Claude projects dir, respecting `CLAUDE_CONFIG_DIR`). If it exceeds the byte budget, `clearSession()` drops the row so the next run starts a fresh session.
- Size-based, not error-based: the detailed `prompt is too long: N tokens` message is flattened to a generic `400` before it reaches the runner, so transcript **size** (~4.6 bytes/token observed) is used as a reliable proxy.
- Threshold defaults to **3 MB (~650K tokens)**, well below the 1M wall; override with `BRAIN_SESSION_MAX_BYTES`.
- Wrapped in try/catch — a size-check failure is non-fatal and never blocks the run. Safe because monitor tasks are stateless-by-design: durable state lives in their workspace files, not the transcript.

### `#` Commands

Messages starting with `#` are intercepted before reaching Claude. Replies sent via `sendResponse`.

| Command | Description |
|---------|-------------|
| `#help` | Show all available commands |
| `#new [topic]` | Create a new Teams channel |
| `#add-dir <path>` | Add a directory globally (all conversations) |
| `#remove-dir <path>` | Remove a directory globally |
| `#list-dirs` | List all active additional directories |
| `#workspace [path]` | Set per-conversation working directory (no arg = clear) |
| `#default-workspace [path]` | Set/clear global default workspace for all conversations |
| `#list-models` | Show available models and current selection |
| `#model [name]` | Show current model / switch per-conversation model / `reset` to revert |
| `#default-model [name]` | Set/clear global default model for all conversations |
| `#system-prompt [prompt]` | Set per-conversation system prompt override (no arg = clear). Overrides only the style/guidelines layer; the necessary layer (identity, tools, execution model) is always preserved. Echoes the full composed prompt. |
| `#default-system-prompt <prompt>` | Replace the global default overridable layer. Echoes the full composed prompt. |
| `#reset-system-prompt` | Restore the built-in default overridable layer and clear this conversation's override. Echoes the full composed prompt. |
| `#list-sessions [<page>\|next\|prev]` | List Claude sessions in this workspace (40 per page). If [AgentLink](https://github.com/yilee/agentlink) is running on the same machine (`~/.agentlink/agent.json` present), each row also gets an `[open]` link that opens the same Claude session in the AgentLink web UI via its `#/chat_v2/<encodedCwd>_<sessionId>` route. Silent no-op when AgentLink isn't running. |
| `#session <n>` | Resume the Nth session from the most recent `#list-sessions` page. Bypasses cwd/model/system-prompt staleness guards for that turn. |
| `#backend [claude\|copilot\|reset]` | Show / switch the agent backend for this conversation (`reset` clears the per-conversation override and reverts to the global default). Switching clears the persisted session id because Claude and Copilot session IDs are not interchangeable. |
| `#default-backend [claude\|copilot]` | Show / set / clear the global default backend (no-arg clears the override and falls back to `config.claude.backend`, default `claude`). |

## Environment Variables

| Variable | Source | Purpose |
|----------|--------|---------|
| `GATEWAY_URL` | CLI daemon | WSS Gateway URL (required) |
| `RELAY_TOKEN_FILE` | CLI daemon | Path to Entra ID access token file (primary, refreshable) |
| `RELAY_ACCESS_TOKEN` | CLI daemon | Entra ID access token (fallback, stale after spawn) |
| `GRAPH_TOKEN_FILE` | CLI daemon | Path to Graph API token file |
| `PORT` | CLI daemon | HTTP health-check port (default 3978) |
| `ANTHROPIC_MODEL` | Config | Fixed to `config.claude.model`, passed to SDK sub-processes |
| `ANTHROPIC_AUTH_TOKEN` | Config / env | Anthropic API key override |
| `ANTHROPIC_API_KEY` | Config / env | Anthropic API key (fallback) |
| `ANTHROPIC_BASE_URL` | Config / env | API base URL override (for LLM proxy) |
| `ANTHROPIC_SMALL_FAST_MODEL` | Config / env | Sub-agent model (defaults to main model) |
| `COPILOT_CLI_PATH` | Local override | Absolute path to the `copilot` binary. Overrides the PATH-based resolution used by the `copilot` agent backend. Cached for the process lifetime. |
| `CLAUDE_CODE_SKIP_AUTH_LOGIN` | Config | Skip Claude Code auth login (default 'true') |
| `CLAUDE_ADD_DIRS` | Config / env | Comma-separated additional directories |
| `BRAIN_TEAM_ID` | CLI daemon | Teams Team ID for #new command and thread context |
| `BRAIN_SESSION_MAX_BYTES` | Config / env | Transcript-size threshold (bytes) above which an isolated scheduled task's session is rotated. Default 3,000,000 (~650K tokens). See `db/session-size.ts`. |
| `BRAIN_DEVICE_NAME` | CLI daemon (from `--name`) | Human-readable device name shown in the Gateway picker; falls back to `os.hostname()` if unset or blank after trim. Display only — never used for routing. |
| `BRAIN_WORKSPACE_ROOT` | Testing | Override workspace root directory |
| `BRAIN_CONFIG_FILE` | Testing | Override config file path |
| `BRAIN_AGENTLINK_RUNTIME_FILE` | Testing | Override the path used by `agentlink.ts` instead of `~/.agentlink/agent.json` |
| `TZ` | System | Timezone override |
| `LOG_LEVEL` | Config / env | Console log level (default 'info') |

## HTTP API — `POST /api/push`

Local REST endpoint for BrainCore to proactively push messages to Teams channel threads.

**Security** (all three layers enforced):
1. **Loopback-only** — rejects requests not from `127.0.0.1` / `::1` / `::ffff:127.0.0.1` (403)
2. **Bearer token** — auto-generated 32-byte hex token at `~/.brainbotbeta/api-token` (mode `0600`); requires `Authorization: Bearer <token>` header (401)
3. **Origin check** — rejects requests with an `Origin` header to block browser CSRF (403)

**Request**:
```
POST http://localhost:3978/api/push
Authorization: Bearer <token from ~/.brainbotbeta/api-token>
Content-Type: application/json

{
  "content": "Hello!",
  "targetChannelId": "19:xxx@thread.tacv2",
  "conversationKey": "cloud_teams:oid:...",
  "threadId": "1781062301786",       // optional
  "sessionId": "uuid",               // optional — binds Claude session
  "workspace": "D:\\my-project",     // optional — binds workspace
  "format": "markdown",              // optional — "markdown" | "html"
  "mentionOid": "...",               // optional
  "mentionName": "..."               // optional
}
```

**Response**: `202 Accepted` with `{ ok: true, conversationKey }` — message is queued in the send buffer, not confirmed delivered.

**Body limit**: 10 KB max.
